Adding roles into the Identity side

This commit is contained in:
James Tombleson 2023-07-14 22:24:32 -07:00
parent 712ce4f4da
commit 0aa6c1489d
4 changed files with 44 additions and 3 deletions

View File

@ -1,11 +1,10 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newsbot.Collector.Api.Domain;
using Newsbot.Collector.Api.Domain.Requests;
using Newsbot.Collector.Api.Domain.Response;
using Newsbot.Collector.Api.Domain.Results;
using Newsbot.Collector.Api.Services;
using Newsbot.Collector.Domain.Dto;
using Newsbot.Collector.Domain.Entities;
namespace Newsbot.Collector.Api.Controllers;
@ -71,6 +70,21 @@ public class AccountController : ControllerBase
return CheckIfSuccessful(response);
}
[HttpPost("addRole")]
[Authorize(Roles = AuthorizationRoles.Administrators)]
public ActionResult AddRole([FromBody] AddRoleRequest request)
{
try
{
_identityService.AddRole(request.RoleName ?? "", request.UserId ?? "");
return new OkResult();
}
catch (Exception ex)
{
return new BadRequestResult();
}
}
private ActionResult CheckIfSuccessful(AuthenticationResult result)
{
if (!result.IsSuccessful)

View File

@ -0,0 +1,6 @@
namespace Newsbot.Collector.Api.Domain;
public class AuthorizationRoles
{
public const string Administrators = "Administrators";
}

View File

@ -0,0 +1,7 @@
namespace Newsbot.Collector.Api.Domain.Requests;
public class AddRoleRequest
{
public string? RoleName { get; set; }
public string? UserId { get; set; }
}

View File

@ -16,6 +16,7 @@ public interface IIdentityService
AuthenticationResult Register(string email, string password);
AuthenticationResult Login(string email, string password);
AuthenticationResult RefreshToken(string token, string refreshToken);
void AddRole(string roleName, string userId);
}
public class IdentityService : IIdentityService
@ -178,6 +179,19 @@ public class IdentityService : IIdentityService
return GenerateJwtToken(user.Result);
}
public void AddRole(string roleName, string userId)
{
var user = _userManager.FindByIdAsync(userId);
user.Wait();
if (user.Result is null)
{
throw new Exception("User was not found");
}
_userManager.AddToRoleAsync(user.Result, roleName);
}
private ClaimsPrincipal? CheckTokenSigner(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();