Newsbot.Collector/Newsbot.Collector.Api/Controllers/v1/IdentityController.cs
2023-08-06 13:32:35 -07:00

107 lines
3.0 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newsbot.Collector.Api.Domain.Consts;
using Newsbot.Collector.Domain.Requests;
using Newsbot.Collector.Domain.Response;
using Newsbot.Collector.Domain.Results;
using Newsbot.Collector.Services;
namespace Newsbot.Collector.Api.Controllers.v1;
[ApiController]
[Route("/api/v1/account")]
public class IdentityController : ControllerBase
{
private readonly ILogger<IdentityController> _logger;
private readonly IIdentityService _identityService;
public IdentityController(IIdentityService identityService, ILogger<IdentityController> logger)
{
_identityService = identityService;
_logger = logger;
}
[HttpPost("register")]
public IActionResult Register([FromBody] RegisterUserRequest user)
{
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(new AuthFailedResponse
{
Errors = ModelState.Values
.Select(x => x.Errors
.Select(y => y.ErrorMessage).FirstOrDefault())
});
}
if (user.Email is null)
{
return new BadRequestResult();
}
if (user.Password is null)
{
return new BadRequestResult();
}
var response = _identityService.Register(user.Email, user.Password);
return CheckIfSuccessful(response);
}
[HttpPost("login")]
public IActionResult Login([FromBody] UserLoginRequest request)
{
if (request.Email is null)
{
return new BadRequestResult();
}
if (request.Password is null)
{
return new BadRequestResult();
}
var response = _identityService.Login(request.Email, request.Password);
return CheckIfSuccessful(response);
}
[HttpPost("refresh")]
public ActionResult RefreshToken([FromBody] UserRefreshTokenRequest request)
{
var response = _identityService.RefreshToken(request.Token ?? "", request.RefreshToken ?? "");
return CheckIfSuccessful(response);
}
[HttpPost("addRole")]
[Authorize(Roles = Authorization.AdministratorsRole)]
public ActionResult AddRole([FromBody] AddRoleRequest request)
{
try
{
_identityService.AddRole(request.RoleName ?? "", request.UserId ?? "");
return new OkResult();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to add role to user");
return new BadRequestResult();
}
}
private ActionResult CheckIfSuccessful(AuthenticationResult result)
{
if (!result.IsSuccessful)
{
return new BadRequestObjectResult( new AuthFailedResponse
{
Errors = result.ErrorMessage
});
}
return new OkObjectResult(new AuthSuccessfulResponse
{
Token = result.Token,
RefreshToken = result.RefreshToken
});
}
}