38 lines
1.4 KiB
C#
38 lines
1.4 KiB
C#
using Distribution.Infra.Authorization;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace Distribution.Features.Auth;
|
|
|
|
[ApiController]
|
|
[Route("api/auth")]
|
|
public class AuthController(AuthService service, ICurrentUserService currentUser) : ControllerBase
|
|
{
|
|
private static IActionResult ToActionResult(AuthHexResponse result) =>
|
|
result.Success ? new OkObjectResult(result) : new ObjectResult(result) { StatusCode = result.StatusCode is >= 400 and < 600 ? result.StatusCode : 401 };
|
|
|
|
[HttpPost("login")]
|
|
public async Task<IActionResult> Login(LoginRequest request, CancellationToken ct) =>
|
|
ToActionResult(await service.LoginAsync(request, ct));
|
|
|
|
[HttpPost("register")]
|
|
public async Task<IActionResult> Register(RegisterRequest request, CancellationToken ct) =>
|
|
ToActionResult(await service.RegisterAsync(request, ct));
|
|
|
|
[HttpGet("me")]
|
|
[Authorize]
|
|
public async Task<IActionResult> Me(CancellationToken ct)
|
|
{
|
|
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
|
return ToActionResult(await service.GetUserDetailsAsync(userId, ct));
|
|
}
|
|
|
|
[HttpPost("logout")]
|
|
[Authorize]
|
|
public async Task<IActionResult> Logout(CancellationToken ct)
|
|
{
|
|
var token = Request.Headers.Authorization.ToString().Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);
|
|
return ToActionResult(await service.LogoutAsync(token, ct));
|
|
}
|
|
}
|