2026-01-20 02:14:01 +01:00
|
|
|
|
using MediatR;
|
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
|
using TimetableDesigner.Backend.Services.Authentication.Core.Helpers;
|
|
|
|
|
|
using TimetableDesigner.Backend.Services.Authentication.Database;
|
|
|
|
|
|
using TimetableDesigner.Backend.Services.Authentication.Database.Model;
|
|
|
|
|
|
|
|
|
|
|
|
namespace TimetableDesigner.Backend.Services.Authentication.Core.Commands.AuthPassword;
|
|
|
|
|
|
|
|
|
|
|
|
public class AuthPasswordHandler : IRequestHandler<AuthPasswordCommand, AuthPasswordResult>
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly DatabaseContext _databaseContext;
|
|
|
|
|
|
private readonly IPasswordHasher _passwordHasher;
|
2026-02-06 00:10:00 +01:00
|
|
|
|
private readonly ITokenHelper _tokenHelper;
|
2026-01-20 02:14:01 +01:00
|
|
|
|
|
2026-02-06 00:10:00 +01:00
|
|
|
|
public AuthPasswordHandler(DatabaseContext databaseContext, IPasswordHasher passwordHasher, ITokenHelper tokenHelper)
|
2026-01-20 02:14:01 +01:00
|
|
|
|
{
|
|
|
|
|
|
_databaseContext = databaseContext;
|
|
|
|
|
|
_passwordHasher = passwordHasher;
|
2026-02-06 00:10:00 +01:00
|
|
|
|
_tokenHelper = tokenHelper;
|
2026-01-20 02:14:01 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public async Task<AuthPasswordResult> Handle(AuthPasswordCommand request, CancellationToken cancellationToken)
|
|
|
|
|
|
{
|
|
|
|
|
|
Account? account = await _databaseContext.Accounts.FirstOrDefaultAsync(x => x.Email == request.Email, cancellationToken);
|
|
|
|
|
|
if (account is null)
|
|
|
|
|
|
{
|
|
|
|
|
|
return AuthPasswordResult.Failure();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
PasswordHashData hash = new PasswordHashData(account.Password, account.PasswordSalt);
|
|
|
|
|
|
if (!_passwordHasher.ValidatePassword(hash, request.Password))
|
|
|
|
|
|
{
|
|
|
|
|
|
return AuthPasswordResult.Failure();
|
|
|
|
|
|
}
|
2026-02-05 23:51:49 +01:00
|
|
|
|
|
2026-02-06 00:10:00 +01:00
|
|
|
|
string accessToken = _tokenHelper.GenerateAccessToken(account.Id);
|
2026-02-05 23:51:49 +01:00
|
|
|
|
|
2026-02-06 00:10:00 +01:00
|
|
|
|
RefreshToken refreshToken = new RefreshToken
|
|
|
|
|
|
{
|
|
|
|
|
|
Token = Guid.NewGuid(),
|
|
|
|
|
|
IsExtendable = request.RememberMe,
|
|
|
|
|
|
AccountId = account.Id,
|
|
|
|
|
|
ExpirationDate = _tokenHelper.CalculateRefreshTokenExpirationDate(request.RememberMe),
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
await _databaseContext.RefreshTokens.AddAsync(refreshToken, cancellationToken);
|
2026-02-05 23:51:49 +01:00
|
|
|
|
await _databaseContext.SaveChangesAsync(cancellationToken);
|
2026-01-20 02:14:01 +01:00
|
|
|
|
|
2026-02-05 23:51:49 +01:00
|
|
|
|
return AuthPasswordResult.Success(accessToken, refreshToken.Token.ToString());
|
2026-01-20 02:14:01 +01:00
|
|
|
|
}
|
|
|
|
|
|
}
|