2026-02-05 23:51:49 +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.AuthToken;
|
|
|
|
|
|
|
|
|
|
|
|
public class AuthTokenHandler : IRequestHandler<AuthTokenCommand, AuthTokenResult>
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly DatabaseContext _databaseContext;
|
2026-02-06 00:10:00 +01:00
|
|
|
|
private readonly ITokenHelper _tokenHelper;
|
2026-02-05 23:51:49 +01:00
|
|
|
|
|
2026-02-06 00:10:00 +01:00
|
|
|
|
public AuthTokenHandler(DatabaseContext databaseContext, ITokenHelper tokenHelper)
|
2026-02-05 23:51:49 +01:00
|
|
|
|
{
|
|
|
|
|
|
_databaseContext = databaseContext;
|
2026-02-06 00:10:00 +01:00
|
|
|
|
_tokenHelper = tokenHelper;
|
2026-02-05 23:51:49 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public async Task<AuthTokenResult> Handle(AuthTokenCommand request, CancellationToken cancellationToken)
|
|
|
|
|
|
{
|
2026-02-06 00:10:00 +01:00
|
|
|
|
RefreshToken? refreshToken = await _databaseContext.RefreshTokens
|
2026-02-05 23:51:49 +01:00
|
|
|
|
.Include(x => x.Account)
|
|
|
|
|
|
.FirstOrDefaultAsync(x => x.Token == Guid.Parse(request.RefreshToken), cancellationToken);
|
2026-02-06 00:10:00 +01:00
|
|
|
|
if (refreshToken is null || refreshToken.ExpirationDate < DateTimeOffset.UtcNow || !_tokenHelper.ValidateExpiredAccessToken(request.AccessToken))
|
2026-02-05 23:51:49 +01:00
|
|
|
|
{
|
|
|
|
|
|
return AuthTokenResult.Failure();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-06 00:10:00 +01:00
|
|
|
|
string accessToken = _tokenHelper.GenerateAccessToken(refreshToken.Account.Id);
|
|
|
|
|
|
|
|
|
|
|
|
if (refreshToken.IsExtendable)
|
2026-02-05 23:51:49 +01:00
|
|
|
|
{
|
2026-02-06 00:10:00 +01:00
|
|
|
|
refreshToken.ExpirationDate = _tokenHelper.CalculateRefreshTokenExpirationDate();
|
|
|
|
|
|
await _databaseContext.SaveChangesAsync(cancellationToken);
|
2026-02-05 23:51:49 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-06 00:10:00 +01:00
|
|
|
|
return AuthTokenResult.Success(accessToken, refreshToken.Token.ToString());
|
2026-02-05 23:51:49 +01:00
|
|
|
|
}
|
|
|
|
|
|
}
|