50 lines
1.6 KiB
C#
50 lines
1.6 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Knot.Shared.Kernel;
|
|
using Knot.Modules.Identity.Application.Users.Auth;
|
|
using Knot.Modules.Identity.Application.Users.Register;
|
|
using Knot.Modules.Identity.Application.Users.Login;
|
|
using Knot.Modules.Identity.Application.Users.GetMe;
|
|
using MediatR;
|
|
|
|
namespace Host.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
public sealed class AuthController : ControllerBase
|
|
{
|
|
private readonly ISender _sender;
|
|
|
|
public AuthController(ISender sender)
|
|
{
|
|
_sender = sender;
|
|
}
|
|
|
|
[HttpPost("register")]
|
|
public async Task<IActionResult> Register([FromBody] RegisterUserCommand command, CancellationToken ct)
|
|
{
|
|
var result = await _sender.Send(command, ct);
|
|
if (result.IsFailure) return BadRequest(new { error = result.Error.Code ?? result.Error.Description });
|
|
return Ok(result.Value);
|
|
}
|
|
|
|
[HttpGet("me")]
|
|
[Authorize]
|
|
public async Task<IActionResult> GetMe([FromServices] IUserContext userContext, CancellationToken ct)
|
|
{
|
|
var result = await _sender.Send(new GetMeQuery(userContext.UserId), ct);
|
|
if (result.IsFailure)
|
|
{
|
|
return NotFound();
|
|
}
|
|
return Ok(new { User = result.Value.User });
|
|
}
|
|
|
|
[HttpPost("login")]
|
|
public async Task<IActionResult> Login([FromBody] LoginUserCommand command, CancellationToken ct)
|
|
{
|
|
var result = await _sender.Send(command, ct);
|
|
if (result.IsFailure) return Unauthorized(new { error = result.Error.Code ?? result.Error.Description });
|
|
return Ok(result.Value);
|
|
}
|
|
} |