Add JWT authentication and authorization infrastructure
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Auth;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/auth")]
|
||||
public class AuthController(AuthService service) : ControllerBase
|
||||
{
|
||||
[HttpPost("login")]
|
||||
public async Task<IActionResult> Login(LoginRequest request)
|
||||
{
|
||||
var result = await service.LoginAsync(request);
|
||||
return result is null ? Unauthorized() : Ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace Distribution.Features.Auth;
|
||||
|
||||
public record LoginRequest(string Username, string Password);
|
||||
|
||||
public record LoginResponse(string Token, Guid UserId, string Username, string RoleName);
|
||||
@@ -0,0 +1,24 @@
|
||||
using Distribution.Features.User;
|
||||
using Distribution.Infra.Auth;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Distribution.Features.Auth;
|
||||
|
||||
public class AuthService(IUserRepository userRepo, IJwtTokenService tokenService)
|
||||
{
|
||||
private readonly PasswordHasher<Models.User> _hasher = new();
|
||||
|
||||
public async Task<LoginResponse?> LoginAsync(LoginRequest request)
|
||||
{
|
||||
var user = await userRepo.GetByUsernameAsync(request.Username);
|
||||
if (user is null || !user.IsActive)
|
||||
return null;
|
||||
|
||||
var result = _hasher.VerifyHashedPassword(user, user.PasswordHash, request.Password);
|
||||
if (result == PasswordVerificationResult.Failed)
|
||||
return null;
|
||||
|
||||
var token = tokenService.GenerateToken(user);
|
||||
return new LoginResponse(token, user.Id, user.Username, user.Role?.Name ?? string.Empty);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user