Newsbot.Collector/Newsbot.Collector.Api/Controllers/v1/IdentityController.cs

104 lines
2.8 KiB
C#
Raw Normal View History

2023-07-14 22:24:32 -07:00
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
2023-07-14 22:24:32 -07:00
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;
namespace Newsbot.Collector.Api.Controllers.v1;
[ApiController]
[Route("/api/v1/account")]
public class IdentityController : ControllerBase
{
private IIdentityService _identityService;
public IdentityController(IIdentityService identityService)
{
_identityService = identityService;
}
[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);
}
2023-07-14 22:24:32 -07:00
[HttpPost("addRole")]
[Authorize(Roles = Authorization.AdministratorsRole)]
2023-07-14 22:24:32 -07:00
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)
{
return new BadRequestObjectResult( new AuthFailedResponse
{
Errors = result.ErrorMessage
});
}
return new OkObjectResult(new AuthSuccessfulResponse
{
Token = result.Token,
RefreshToken = result.RefreshToken
});
}
}