basic player management

This commit is contained in:
Michele 2021-02-21 22:59:43 +00:00
parent 350a283b5e
commit bab170552e
12 changed files with 244 additions and 91 deletions

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using MediatR;
using Sledgemapper.Shared.Entities;
namespace Sledgemapper.Api.Commands
{
public class GetCampaignPlayersCommand : IRequest<List<Player>>
{
public double Timestamp { get; private set; }
public string CampaignName { get; private set; }
public string UserId { get; private set; }
public GetCampaignPlayersCommand(string campaingName, string userId)
{
Timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
CampaignName = campaingName;
UserId = userId;
}
}
}

View File

@ -0,0 +1,15 @@
using System.Collections.Generic;
using MediatR;
namespace Sledgemapper.Api.Commands
{
public class GetCampaignsCommand : IRequest<List<Core.Entities.Campaign>>
{
public string UserId { get; private set; }
public GetCampaignsCommand(string userId)
{
UserId = userId;
}
}
}

View File

@ -0,0 +1,21 @@
using System;
using MediatR;
namespace Sledgemapper.Api.Commands
{
public class InvitePlayerToCampaignCommand : IRequest<bool>
{
public double Timestamp { get; private set; }
public string CampaignName { get; private set; }
public string Email { get; private set; }
public string UserId { get; private set; }
public InvitePlayerToCampaignCommand(string campaingName, string email, string userId)
{
Timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
CampaignName = campaingName;
UserId = userId;
Email = email;
}
}
}

View File

@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using MediatR;
namespace Sledgemapper.Api.Commands
@ -24,13 +23,4 @@ namespace Sledgemapper.Api.Commands
}
}
public class GetCampaignsCommand : IRequest<List<Core.Entities.Campaign>>
{
public string UserId { get; private set; }
public GetCampaignsCommand(string userId)
{
UserId = userId;
}
}
}

View File

@ -1,14 +1,10 @@
using MediatR;
using Microsoft.AspNetCore.Authorization;
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Notifications;
using Sledgemapper.Entities;
using Sledgemapper.Models.Users;
using Sledgemapper.Shared.Entities;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
@ -19,19 +15,21 @@ using System.Threading.Tasks;
namespace Sledgemapper.Api.Controllers
{
[Route("[controller]")] // api/authmanagement
[ApiController]
public class AuthManagementController : ControllerBase
{
private readonly UserManager<User> _userManager;
private readonly JwtConfig _jwtConfig;
private readonly IMapper _mapper;
public AuthManagementController(UserManager<User> userManager,
IOptionsMonitor<JwtConfig> optionsMonitor)
IOptionsMonitor<JwtConfig> optionsMonitor,
IMapper mapper)
{
_userManager = userManager;
_jwtConfig = optionsMonitor.CurrentValue;
_mapper = mapper;
}
[HttpPost]
@ -55,7 +53,8 @@ namespace Sledgemapper.Api.Controllers
});
}
var newUser = new User() { Email = user.Email, UserName = user.UserName };
var newUser = _mapper.Map<User>(user);
// var newUser = new User() { Email = user.Email, UserName = user.UserName };
var isCreated = await _userManager.CreateAsync(newUser, user.Password);
if (isCreated.Succeeded)
{
@ -86,43 +85,6 @@ namespace Sledgemapper.Api.Controllers
});
}
private string GenerateJwtToken(User user)
{
// Now its ime to define the jwt token which will be responsible of creating our tokens
var jwtTokenHandler = new JwtSecurityTokenHandler();
// We get our secret from the appsettings
var key = Encoding.ASCII.GetBytes(_jwtConfig.Secret);
// we define our token descriptor
// We need to utilise claims which are properties in our token which gives information about the token
// which belong to the specific user who it belongs to
// so it could contain their id, name, email the good part is that these information
// are generated by our server and identity framework which is valid and trusted
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
// the JTI is used for our refresh token which we will be convering in the next video
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}),
// the life span of the token needs to be shorter and utilise refresh token to keep the user signedin
// but since this is a demo app we can extend it to fit our current need
Expires = DateTime.UtcNow.AddHours(6),
// here we are adding the encryption alogorithim information which will be used to decrypt our token
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
};
var token = jwtTokenHandler.CreateToken(tokenDescriptor);
var jwtToken = jwtTokenHandler.WriteToken(token);
return jwtToken;
}
[HttpPost]
[Route("Login")]
public async Task<IActionResult> Login([FromBody] UserLoginRequest user)
@ -178,7 +140,43 @@ namespace Sledgemapper.Api.Controllers
}
});
}
private string GenerateJwtToken(User user)
{
// Now its ime to define the jwt token which will be responsible of creating our tokens
var jwtTokenHandler = new JwtSecurityTokenHandler();
// We get our secret from the appsettings
var key = Encoding.ASCII.GetBytes(_jwtConfig.Secret);
// we define our token descriptor
// We need to utilise claims which are properties in our token which gives information about the token
// which belong to the specific user who it belongs to
// so it could contain their id, name, email the good part is that these information
// are generated by our server and identity framework which is valid and trusted
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
// the JTI is used for our refresh token which we will be convering in the next video
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}),
// the life span of the token needs to be shorter and utilise refresh token to keep the user signedin
// but since this is a demo app we can extend it to fit our current need
Expires = DateTime.UtcNow.AddHours(6),
// here we are adding the encryption alogorithim information which will be used to decrypt our token
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
};
var token = jwtTokenHandler.CreateToken(tokenDescriptor);
var jwtToken = jwtTokenHandler.WriteToken(token);
return jwtToken;
}
}
}

View File

@ -35,5 +35,20 @@ namespace Sledgemapper.Api.Controllers
return result;
}
[HttpPost]
[Route("{campaignName}/players/{email}")]
public async Task<bool> Invite(string campaignName, string email)
{
var result = await _mediator.Send(new InvitePlayerToCampaignCommand(campaignName, email, UserId.ToString()));
return result;
}
[HttpGet]
[Route("{campaignName}/players")]
public async Task<List<Player>> GetPlayers(string campaignName)
{
var result = await _mediator.Send(new GetCampaignPlayersCommand(campaignName, UserId.ToString()));
return result;
}
}
}

View File

@ -2,7 +2,6 @@ using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Notifications;
using Sledgemapper.Shared.Entities;
using System.Threading.Tasks;
@ -17,8 +16,6 @@ namespace Sledgemapper.Api.Controllers
public MapController(IMediator mediator) => _mediator = mediator;
[HttpPost]
public async Task<bool> Post(string mapName)
{

View File

@ -0,0 +1,43 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Infrastructure.Data;
using Sledgemapper.Shared.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Sledgemapper.Api.Handlers
{
public class GetCampaignPlayersCommandHandler : IRequestHandler<GetCampaignPlayersCommand, List<Player>>
{
private readonly IMediator _mediator;
private readonly SledgemapperDbContext _dbcontext;
public GetCampaignPlayersCommandHandler(IMediator mediator, SledgemapperDbContext dbcontext)
{
_mediator = mediator;
_dbcontext = dbcontext;
}
public async Task<List<Player>> Handle(GetCampaignPlayersCommand command, CancellationToken cancellationToken)
{
try
{
var user = await _dbcontext.Users.FindAsync(command.UserId);
_dbcontext.Attach(user);
var campaign = await _dbcontext.Campaigns.Where(campaign=>campaign.CampaignName==command.CampaignName && campaign.OwnerId==command.UserId).Include(campaign=>campaign.InvitedUsers).FirstAsync();
var players=campaign.InvitedUsers.Select(user=>new Player{Initials=user.Initials, UserName=user.UserName}).ToList();
return players;
}
catch (Exception ex)
{
}
return null;
}
}
}

View File

@ -0,0 +1,39 @@
using MediatR;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Infrastructure.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Sledgemapper.Api.Handlers
{
public class GetCampaignsCommandHandler : IRequestHandler<GetCampaignsCommand, List<Core.Entities.Campaign>>
{
private readonly IMediator _mediator;
private readonly SledgemapperDbContext _dbcontext;
public GetCampaignsCommandHandler(IMediator mediator, SledgemapperDbContext dbcontext)
{
_mediator = mediator;
_dbcontext = dbcontext;
}
public async Task<List<Core.Entities.Campaign>> Handle(GetCampaignsCommand command, CancellationToken cancellationToken)
{
try
{
var user = await _dbcontext.Users.FindAsync(command.UserId);
_dbcontext.Attach(user);
var campaigns = _dbcontext.Campaigns.Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user));
return campaigns.ToList();
}
catch (Exception ex)
{
}
return new List<Core.Entities.Campaign>();
}
}
}

View File

@ -0,0 +1,44 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Infrastructure.Data;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Sledgemapper.Api.Handlers
{
public class InvitePlayerToCampaignCommandHandler : IRequestHandler<InvitePlayerToCampaignCommand, bool>
{
private readonly IMediator _mediator;
private readonly SledgemapperDbContext _dbcontext;
public InvitePlayerToCampaignCommandHandler(IMediator mediator, SledgemapperDbContext dbcontext)
{
_mediator = mediator;
_dbcontext = dbcontext;
}
public async Task<bool> Handle(InvitePlayerToCampaignCommand command, CancellationToken cancellationToken)
{
try
{
var user = await _dbcontext.Users.FindAsync(command.UserId);
var campaign = await _dbcontext.Campaigns.Where(campaign=>campaign.CampaignName==command.CampaignName && campaign.OwnerId==command.UserId).Include(campaign=>campaign.InvitedUsers).FirstAsync();
var invitedUser = await _dbcontext.Users.FirstOrDefaultAsync(user=>user.Email==command.Email);
_dbcontext.Attach(invitedUser);
_dbcontext.Attach(campaign);
campaign.InvitedUsers.Add(invitedUser);
_dbcontext.Campaigns.Update(campaign);
await _dbcontext.SaveChangesAsync();
return true;
}
catch (Exception ex)
{
}
return false;
}
}
}

View File

@ -1,10 +1,7 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Infrastructure.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@ -47,32 +44,4 @@ namespace Sledgemapper.Api.Handlers
return false;
}
}
public class GetCampaignsCommandHandler : IRequestHandler<GetCampaignsCommand, List<Core.Entities.Campaign>>
{
private readonly IMediator _mediator;
private readonly SledgemapperDbContext _dbcontext;
public GetCampaignsCommandHandler(IMediator mediator, SledgemapperDbContext dbcontext)
{
_mediator = mediator;
_dbcontext = dbcontext;
}
public async Task<List<Core.Entities.Campaign>> Handle(GetCampaignsCommand command, CancellationToken cancellationToken)
{
try
{
var user = await _dbcontext.Users.FindAsync(command.UserId);
_dbcontext.Attach(user);
var campaigns = _dbcontext.Campaigns.Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user));
return campaigns.ToList();
}
catch (Exception ex)
{
}
return new List<Core.Entities.Campaign>();
}
}
}

View File

@ -4,6 +4,7 @@ namespace Sledgemapper.Shared.Entities
{
public int UserId { get; set; }
public string Color { get; set; }
public string UserName { get; set; }
public string Initials { get; set; }
public Tile Position { get; set; }