35 lines
1.1 KiB
C#
35 lines
1.1 KiB
C#
using AutoMapper;
|
|||
|
|
using Mws.Application.Common;
|
||
|
|
|
||
|
|
namespace Mws.Application.Auth;
|
||
|
|
|
||
|
|
public interface IAuthService
|
||
|
|
{
|
||
|
|
Task<LoginResponse> LoginAsync(LoginRequest request, CancellationToken cancellationToken = default);
|
||
|
|
}
|
||
|
|
|
||
|
|
public class AuthService(IUnitOfWork uow, IPasswordHasher passwordHasher, ITokenService tokenService, IMapper mapper)
|
||
|
|
: IAuthService
|
||
|
|
{
|
||
|
|
public async Task<LoginResponse> LoginAsync(LoginRequest request, CancellationToken cancellationToken = default)
|
||
|
|
{
|
||
|
|
var username = request.Username.Trim();
|
||
|
|
var user = await uow.Users.GetByUsernameWithRoleAsync(username, cancellationToken);
|
||
|
|
|
||
|
|
if (user is null || !passwordHasher.Verify(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),
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|