Files
Govor/Govor.Application/Users/UserSessions/UserSessionRefresher.cs
T
Artemy 6d1c53beeb Refactor: migrate Core -> Domain and reorganize projects
Large refactor that renames/moves core types into a new Govor.Domain surface and reorganizes the Application layer. Models, configurations, migrations and many files moved from Govor.Core/Govor.Data to Govor.Domain; numerous Application services, interfaces and implementations were relocated or added (authentication, friends, messages, medias, push notifications, user sessions, storage, synching, private chats, etc.). Tests updated to use Govor.Domain namespaces and adjusted project references (removed Govor.Data reference from API tests). Also updated API, Hub and mapping code and project files to reflect the new structure and naming. This is primarily a codebase-wide namespace and module reorganization to establish a Domain project and restructure application services.
2026-07-16 19:27:45 +07:00

81 lines
3.1 KiB
C#

using Govor.Application.Authentication.JWT;
using Govor.Domain;
using Govor.Domain.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Govor.Application.Users.UserSessions;
public class UserSessionRefresher : IUserSessionRefresher
{
private readonly ILogger<UserSessionRefresher> _logger;
private readonly JwtRefreshOption _options;
private readonly IJwtTokenHasher _jwtTokenHasher;
private readonly IJwtService _jwtService;
private readonly GovorDbContext _context;
public UserSessionRefresher(
ILogger<UserSessionRefresher> logger,
IOptions<JwtRefreshOption> options,
IJwtTokenHasher jwtTokenHasher,
IJwtService jwtService,
GovorDbContext context)
{
_logger = logger;
_options = options.Value;
_jwtTokenHasher = jwtTokenHasher;
_jwtService = jwtService;
_context = context;
}
public async Task<Result<RefreshResult>> RefreshTokenAsync(string refreshToken)
{
if (string.IsNullOrWhiteSpace(refreshToken))
{
return Result<RefreshResult>.Failure(new Error("Auth.EmptyToken", "Refresh token cannot be empty."));
}
var hashedToken = _jwtTokenHasher.HashToken(refreshToken);
try
{
var session = await _context.UserSessions
.AsNoTracking()
.Include(userSession => userSession.User)
.FirstOrDefaultAsync(s => s.RefreshTokenHash == hashedToken);
if (session is null)
{
_logger.LogWarning("Refresh token session not found for hashed token");
return Result<RefreshResult>.Failure(new Error("Auth.InvalidToken", "Invalid refresh token."));
}
if (session.IsRevoked || session.ExpiresAt <= DateTime.UtcNow)
{
_logger.LogWarning("Attempted to refresh an expired or revoked session: {SessionId}", session.Id);
return Result<RefreshResult>.Failure(new Error("Auth.InvalidToken", "Refresh token is invalid or expired."));
}
var newAccessToken = await _jwtService.GenerateAccessTokenAsync(session.User, session.Id);
var newRefreshToken = await _jwtService.GenerateRefreshTokenAsync(session.User);
var newRefreshTokenHash = _jwtTokenHasher.HashToken(newRefreshToken);
session.RefreshTokenHash = newRefreshTokenHash;
session.CreatedAt = DateTime.UtcNow;
session.ExpiresAt = DateTime.UtcNow.AddDays(_options.RefreshTokenLifetimeDays);
await _context.SaveChangesAsync();
_logger.LogInformation("Successfully refreshed session {SessionId} for user {UserId}", session.Id, session.UserId);
return new RefreshResult(newRefreshToken, newAccessToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Database error occurred during token refresh execution");
return Result<RefreshResult>.Failure(ex);
}
}
}