mirror of
https://github.com/Govor-team/Govor.git
synced 2026-07-21 19:54:55 +00:00
Implement user session management and JWT refresh tokens
Added user session models, interfaces, repository, and service for managing user sessions and refresh tokens. Refactored authentication flow to return user objects and open sessions with device info, supporting refresh token generation and validation. Updated JWT configuration to separate access and refresh options, and refactored related tests and API contracts. Improved media upload handling and error logging. Migrated dependency references and DI registrations accordingly.
This commit is contained in:
@@ -30,7 +30,7 @@ public class AuthService : IAccountService
|
||||
_usernameValidator = usernameValidator;
|
||||
}
|
||||
|
||||
public async Task<string> RegistrationAsync(string name, string password, Invitation invitation)
|
||||
public async Task<User> RegistrationAsync(string name, string password, Invitation invitation)
|
||||
{
|
||||
_usernameValidator.Validate(name);
|
||||
|
||||
@@ -55,11 +55,11 @@ public class AuthService : IAccountService
|
||||
|
||||
await SetRole(user, invitation);
|
||||
|
||||
return await _jwtService.GenerateJwtTokenAsync(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
public async Task<string> LoginAsync(string name, string password)
|
||||
public async Task<User> LoginAsync(string name, string password)
|
||||
{
|
||||
if (await _usersRepository.ExistsUsernameAsync(name) == false)
|
||||
throw new UserNotRegisteredException(name);
|
||||
@@ -69,9 +69,34 @@ public class AuthService : IAccountService
|
||||
if (_passwordHasher.Verify(password, user.PasswordHash) == false)
|
||||
throw new LoginUserException();
|
||||
|
||||
return await _jwtService.GenerateJwtTokenAsync(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
/*
|
||||
public async Task<string> RefreshTokenAsync(string refreshToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var principal = _jwtService.GetPrincipalFromExpiredToken(refreshToken);
|
||||
|
||||
var userId = Guid.Parse(principal?.FindFirst("userId")?.Value ?? string.Empty);
|
||||
|
||||
var storedTokens = await _userSessionsRepository.GetUserTokensAsync(userId);
|
||||
|
||||
if (!storedTokens.Contains(refreshToken))
|
||||
throw new UnauthorizedAccessException("Invalid refresh token");
|
||||
|
||||
var user = await _usersRepository.FindByIdAsync(userId);
|
||||
var newAccessToken = await _jwtService.GenerateAccessTokenAsync(user);
|
||||
return newAccessToken;
|
||||
}
|
||||
catch (SecurityTokenException ex)
|
||||
{
|
||||
throw new InvalidOperationException("Invalid refresh token", ex);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
private async Task SetRole(User user, Invitation invitation)
|
||||
{
|
||||
if(invitation.IsAdmin)
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
namespace Govor.Application.Services.Authentication;
|
||||
public class JwtOption
|
||||
public class JwtAccessOption
|
||||
{
|
||||
public string SecretKeу {get; set;}
|
||||
public int Hours { get; set; }
|
||||
public int Minutes { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Govor.Application.Services.Authentication;
|
||||
|
||||
public class JwtRefreshOption
|
||||
{
|
||||
public int RefreshTokenLifetimeDays { get; set; }
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Govor.API.Services.Authentication.Interfaces;
|
||||
using Govor.Application.Interfaces.Authentication;
|
||||
using Govor.Core.Models.Users;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -11,16 +10,18 @@ namespace Govor.Application.Services.Authentication;
|
||||
|
||||
public class JwtService : IJwtService
|
||||
{
|
||||
private JwtOption _jwtOption;
|
||||
private JwtAccessOption _jwtAccessOption;
|
||||
private JwtRefreshOption _refreshOptions;
|
||||
private IInvitesService _invitesService;
|
||||
|
||||
public JwtService(IOptions<JwtOption> options, IInvitesService invitesService)
|
||||
public JwtService(IOptions<JwtAccessOption> options, IOptions<JwtRefreshOption> refreshOptions, IInvitesService invitesService)
|
||||
{
|
||||
_jwtOption = options.Value;
|
||||
_refreshOptions = refreshOptions.Value;
|
||||
_jwtAccessOption = options.Value;
|
||||
_invitesService = invitesService;
|
||||
}
|
||||
|
||||
public async Task<string> GenerateJwtTokenAsync(User user)
|
||||
public async Task<string> GenerateAccessTokenAsync(User user)
|
||||
{
|
||||
var claims = new[]
|
||||
{
|
||||
@@ -29,13 +30,55 @@ public class JwtService : IJwtService
|
||||
};
|
||||
|
||||
var singing = new SigningCredentials(
|
||||
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOption.SecretKeу)),
|
||||
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKeу)),
|
||||
SecurityAlgorithms.HmacSha256Signature);
|
||||
|
||||
var token = new JwtSecurityToken(signingCredentials: singing,
|
||||
expires: DateTime.UtcNow.AddHours(_jwtOption.Hours),
|
||||
var token = new JwtSecurityToken(
|
||||
expires: DateTime.UtcNow.AddMinutes(_jwtAccessOption.Minutes),
|
||||
signingCredentials: singing,
|
||||
claims: claims);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
|
||||
public async Task<string> GenerateRefreshTokenAsync(User user)
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKeу));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim("userId", user.Id.ToString()),
|
||||
new Claim("tokenType", "refresh")
|
||||
};
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
expires: DateTime.UtcNow.AddDays(_refreshOptions.RefreshTokenLifetimeDays),
|
||||
signingCredentials: creds,
|
||||
claims: claims
|
||||
);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
|
||||
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
|
||||
{
|
||||
var tokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateAudience = false,
|
||||
ValidateIssuer = false,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKeу)),
|
||||
ValidateLifetime = false // << important
|
||||
};
|
||||
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var principal = handler.ValidateToken(token, tokenValidationParameters, out var securityToken);
|
||||
|
||||
if (securityToken is not JwtSecurityToken jwtToken || jwtToken.Header.Alg != SecurityAlgorithms.HmacSha256)
|
||||
throw new SecurityTokenException("Invalid token");
|
||||
|
||||
return principal;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
using Govor.API.Services.Authentication.Interfaces;
|
||||
using Govor.Application.Exceptions.InvitesService;
|
||||
using Govor.Application.Interfaces.Authentication;
|
||||
using Govor.Core.Models;
|
||||
using Govor.Core.Models.Users;
|
||||
using Govor.Core.Repositories.Invaites;
|
||||
|
||||
@@ -67,7 +67,7 @@ public class MediaService : IMediaService
|
||||
var mediaFile = await _dbContext.MediaFiles
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.Id == mediaId)
|
||||
?? throw new KeyNotFoundException("No media found");
|
||||
?? throw new KeyNotFoundException($"No media found by given id {mediaId}");
|
||||
|
||||
// Загрузить бинарные данные из хранилища
|
||||
Stream dataStream = await _storageService.LoadAsync(mediaFile.Url);
|
||||
@@ -83,8 +83,8 @@ public class MediaService : IMediaService
|
||||
return new Media(
|
||||
mediaFile.UploaderId,
|
||||
mediaFile.DateCreated,
|
||||
mediaFile.MediaType.ToString(),
|
||||
contentBytes,
|
||||
string.Empty,
|
||||
mediaFile.MediaType,
|
||||
mediaFile.MineType,
|
||||
string.Empty
|
||||
@@ -96,5 +96,4 @@ public class MediaService : IMediaService
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Govor.Application.Interfaces.Authentication;
|
||||
using Govor.Application.Interfaces.UserSession;
|
||||
using Govor.Application.Services.Authentication;
|
||||
using Govor.Core.Models.Users;
|
||||
using Govor.Core.Repositories.UserSessionsRepository;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Govor.Application.Services.UserSessions;
|
||||
|
||||
public class UserSessionOpener : IUserSessionOpener
|
||||
{
|
||||
private readonly IUserSessionsRepository _repository;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly ILogger<UserSessionOpener> _logger;
|
||||
private readonly JwtRefreshOption _options;
|
||||
|
||||
public UserSessionOpener(IUserSessionsRepository repository, IJwtService jwtService, IOptions<JwtRefreshOption> options, ILogger<UserSessionOpener> logger)
|
||||
{
|
||||
_jwtService = jwtService;
|
||||
_repository = repository;
|
||||
_logger = logger;
|
||||
_options = options.Value;
|
||||
}
|
||||
public async Task<string> OpenSessionAsync(User user, string deviceInfo)
|
||||
{
|
||||
_logger.LogInformation($"Opening session for user {user.Id} on device '{deviceInfo}'");
|
||||
|
||||
var sessions = await _repository.GetByUserIdAsync(user.Id);
|
||||
var session = sessions.FirstOrDefault(s => s.DeviceInfo == deviceInfo);
|
||||
|
||||
var newRefreshToken = await _jwtService.GenerateRefreshTokenAsync(user);
|
||||
var newExpiresAt = DateTime.UtcNow.AddDays(_options.RefreshTokenLifetimeDays);
|
||||
|
||||
if (session is not null)
|
||||
{
|
||||
if (session.IsRevoked || session.ExpiresAt <= DateTime.UtcNow)
|
||||
{
|
||||
// Update Session
|
||||
session.RefreshToken = newRefreshToken;
|
||||
session.ExpiresAt = newExpiresAt;
|
||||
session.CreatedAt = DateTime.UtcNow;
|
||||
session.IsRevoked = false;
|
||||
|
||||
await _repository.UpdateAsync(session);
|
||||
_logger.LogInformation($"Updated expired/revoked session for user {user.Id} on device '{deviceInfo}'");
|
||||
}
|
||||
|
||||
return session.RefreshToken;
|
||||
}
|
||||
|
||||
// New Session
|
||||
var newSession = new Core.Models.UserSession
|
||||
{
|
||||
UserId = user.Id,
|
||||
DeviceInfo = deviceInfo,
|
||||
RefreshToken = newRefreshToken,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
ExpiresAt = newExpiresAt,
|
||||
IsRevoked = false
|
||||
};
|
||||
|
||||
await _repository.AddAsync(newSession);
|
||||
_logger.LogInformation($"Created new session for user {user.Id} on device '{deviceInfo}'");
|
||||
|
||||
return newRefreshToken;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user