60 lines
1.8 KiB
C#
60 lines
1.8 KiB
C#
using MediatR;
|
|
using Nashel.Modules.Identity.Domain.Aggregates;
|
|
using Nashel.Modules.Identity.Domain.Enums;
|
|
using Nashel.Modules.Identity.Domain.Repositories;
|
|
using Nashel.Modules.Identity.Domain.Services;
|
|
|
|
namespace Nashel.Modules.Identity.Application.Commands;
|
|
|
|
/// <summary>
|
|
/// Команда входа пользователя.
|
|
/// </summary>
|
|
public record LoginCommand : IRequest<string>
|
|
{
|
|
/// <summary>
|
|
/// Номер телефона.
|
|
/// </summary>
|
|
public string Phone { get; init; } = default!;
|
|
|
|
/// <summary>
|
|
/// Пароль.
|
|
/// </summary>
|
|
public string Password { get; init; } = default!;
|
|
|
|
public LoginCommand(string phone, string password)
|
|
{
|
|
Phone = phone;
|
|
Password = password;
|
|
}
|
|
|
|
public LoginCommand() { }
|
|
} // Возвращает JWT
|
|
|
|
public class LoginCommandHandler : IRequestHandler<LoginCommand, string>
|
|
{
|
|
private readonly IAccountRepository _accountRepository;
|
|
private readonly IJwtTokenGenerator _jwtTokenGenerator;
|
|
private readonly IPasswordHasher _passwordHasher;
|
|
|
|
public LoginCommandHandler(
|
|
IAccountRepository accountRepository,
|
|
IJwtTokenGenerator jwtTokenGenerator,
|
|
IPasswordHasher passwordHasher)
|
|
{
|
|
_accountRepository = accountRepository;
|
|
_jwtTokenGenerator = jwtTokenGenerator;
|
|
_passwordHasher = passwordHasher;
|
|
}
|
|
|
|
public async Task<string> Handle(LoginCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var account = await _accountRepository.GetByPhoneAsync(request.Phone, cancellationToken);
|
|
if (account == null || !_passwordHasher.VerifyPassword(request.Password, account.PasswordHash))
|
|
{
|
|
throw new Exception("Неверные учетные данные");
|
|
}
|
|
|
|
return _jwtTokenGenerator.GenerateToken(account.Id, account.Roles);
|
|
}
|
|
}
|