Files
mws.backend.dotnet/mws.application/Auth/AuthService.cs
T

35 lines
1.1 KiB
C#
Raw Normal View History

2026-08-13 23:10:22 +07:00
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),
};
}
}