Adds the MediatR package and wires AddMediatR in DI. Replaces IAuthService/AuthService with LoginCommand/LoginHandler, the pattern the remaining modules will follow.
34 lines
1.0 KiB
C#
34 lines
1.0 KiB
C#
using AutoMapper;
|
|
using MediatR;
|
|
using Mws.Application.Common;
|
|
|
|
namespace Mws.Application.Auth;
|
|
|
|
public record LoginCommand(LoginRequest Request) : IRequest<LoginResponse>;
|
|
|
|
public class LoginHandler(IUnitOfWork uow, IPasswordHasher passwordHasher, ITokenService tokenService, IMapper mapper)
|
|
: IRequestHandler<LoginCommand, LoginResponse>
|
|
{
|
|
public async Task<LoginResponse> Handle(LoginCommand command, CancellationToken ct)
|
|
{
|
|
var username = command.Request.Username.Trim();
|
|
var user = await uow.Users.GetByUsernameWithRoleAsync(username, ct);
|
|
|
|
if (user is null || !passwordHasher.Verify(command.Request.Password, user.PasswordHash))
|
|
{
|
|
throw new UnauthorizedException("Invalid username or password");
|
|
}
|
|
|
|
if (!user.IsActive)
|
|
{
|
|
throw new ForbiddenException("Account disabled");
|
|
}
|
|
|
|
return new LoginResponse
|
|
{
|
|
Token = tokenService.CreateToken(user.Id, user.Username),
|
|
User = mapper.Map<UserDto>(user),
|
|
};
|
|
}
|
|
}
|