54 lines
1.7 KiB
C#
54 lines
1.7 KiB
C#
|
|
using Knot.Modules.Auth.Domain;
|
|
using Knot.Modules.Auth.Application.Abstractions;
|
|
using Knot.Shared.Kernel;
|
|
using Knot.Modules.Auth.Application.Users.Auth;
|
|
using BCrypt.Net;
|
|
|
|
namespace Knot.Modules.Auth.Application.Users.Login;
|
|
|
|
/// <summary>
|
|
/// Команда для входа пользователя. Возвращает AuthResponseDto.
|
|
/// </summary>
|
|
public sealed record LoginUserCommand(string Username, string Password) : ICommand<AuthResponseDto>;
|
|
|
|
public sealed class LoginUserCommandHandler : ICommandHandler<LoginUserCommand, AuthResponseDto>
|
|
{
|
|
private readonly IUserRepository _userRepository;
|
|
private readonly IJwtTokenProvider _tokenProvider;
|
|
|
|
public LoginUserCommandHandler(IUserRepository userRepository, IJwtTokenProvider tokenProvider)
|
|
{
|
|
_userRepository = userRepository;
|
|
_tokenProvider = tokenProvider;
|
|
}
|
|
|
|
public async Task<Result<AuthResponseDto>> Handle(LoginUserCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var user = await _userRepository.GetByUsernameAsync(request.Username, cancellationToken);
|
|
|
|
if (user is null || !BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
|
|
{
|
|
return Result.Failure<AuthResponseDto>(AuthErrors.IdentityInvalidCredentials);
|
|
}
|
|
|
|
string token = _tokenProvider.Generate(user);
|
|
|
|
return Result.Success(new AuthResponseDto(
|
|
token,
|
|
new AuthUserDto(
|
|
user.Id,
|
|
user.Username,
|
|
user.DisplayName,
|
|
user.Email,
|
|
user.Bio,
|
|
user.Avatar,
|
|
user.Birthday,
|
|
true, // IsOnline (placeholder)
|
|
user.CreatedAt
|
|
)
|
|
));
|
|
}
|
|
}
|
|
|