41 lines
1.3 KiB
C#
41 lines
1.3 KiB
C#
using MikrocopApi.Dtos;
|
|
using MikrocopApi.Exceptions;
|
|
using MikrocopApi.Mappers;
|
|
using MikrocopDb.Repositories;
|
|
|
|
namespace MikrocopApi.Services;
|
|
|
|
public sealed class AuthService : IAuthService
|
|
{
|
|
private readonly IUserRepository _userRepository;
|
|
private readonly IPasswordHashingService _passwordHashingService;
|
|
private readonly IJwtTokenService _jwtTokenService;
|
|
|
|
public AuthService(
|
|
IUserRepository userRepository,
|
|
IPasswordHashingService passwordHashingService,
|
|
IJwtTokenService jwtTokenService)
|
|
{
|
|
_userRepository = userRepository;
|
|
_passwordHashingService = passwordHashingService;
|
|
_jwtTokenService = jwtTokenService;
|
|
}
|
|
|
|
public async Task<LoginResponseDto> LoginAsync(LoginRequestDto request, CancellationToken cancellationToken = default)
|
|
{
|
|
var user = await _userRepository.GetByUserNameAsync(request.UserName, cancellationToken);
|
|
if (user is null)
|
|
{
|
|
throw new UnauthorizedException("Invalid username or password.");
|
|
}
|
|
|
|
var isValid = _passwordHashingService.VerifyPassword(request.Password, user.PasswordHash, user.PasswordSalt);
|
|
if (!isValid)
|
|
{
|
|
throw new UnauthorizedException("Invalid username or password.");
|
|
}
|
|
|
|
return _jwtTokenService.Generate(user).ToDto();
|
|
}
|
|
}
|