mirror of
https://github.com/Govor-team/Govor.git
synced 2026-07-21 11:44:56 +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:
@@ -1,6 +1,6 @@
|
||||
using AutoFixture;
|
||||
using Govor.API.Services.AdminsStuff.Interfaces;
|
||||
using Govor.Application.Infrastructure.AdminsStuff;
|
||||
using Govor.Application.Interfaces;
|
||||
using Govor.Core.Models;
|
||||
using Govor.Core.Repositories.Invaites;
|
||||
using Moq;
|
||||
|
||||
@@ -2,10 +2,8 @@ using AutoFixture;
|
||||
using Govor.Core.Infrastructure.Extensions;
|
||||
using Govor.Core.Models;
|
||||
using Govor.Core.Repositories.Users;
|
||||
using Govor.API.Services.Authentication.Interfaces;
|
||||
using Govor.Application.Exceptions.AuthService;
|
||||
using Govor.Application.Interfaces.Authentication;
|
||||
using Govor.Application.Services;
|
||||
using Govor.Application.Services.Authentication;
|
||||
using Govor.Core.Models.Users;
|
||||
using Govor.Core.Repositories.Admins;
|
||||
@@ -52,6 +50,7 @@ public class AuthServiceTests
|
||||
);
|
||||
}
|
||||
|
||||
// Tests for Register action
|
||||
[Test]
|
||||
public void Given_ExistUser_When_Register_Should_Throw_UserAlreadyExistsException()
|
||||
{
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using AutoFixture;
|
||||
using Govor.API.Services.Authentication.Interfaces;
|
||||
using Govor.Application.Interfaces.Authentication;
|
||||
using Govor.Application.Services.Authentication;
|
||||
using Govor.Core.Models.Users;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Moq;
|
||||
|
||||
namespace Govor.Application.Tests.Services.Authentication;
|
||||
@@ -13,11 +15,13 @@ namespace Govor.Application.Tests.Services.Authentication;
|
||||
public class JwtServiceTests
|
||||
{
|
||||
private Fixture _fixture;
|
||||
private Mock<IOptions<JwtOption>> _jwtOptionsMock;
|
||||
private Mock<IOptions<JwtAccessOption>> _jwtOptionsMock;
|
||||
private Mock<IOptions<JwtRefreshOption>> _jwtRefreshOptionsMock;
|
||||
private Mock<IInvitesService> _invitesServiceMock;
|
||||
private IJwtService _jwtService;
|
||||
|
||||
private JwtOption _testJwtOptions;
|
||||
private JwtAccessOption _testJwtAccessOptions;
|
||||
private JwtRefreshOption _testJwtRefreshOptions;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
@@ -26,18 +30,29 @@ public class JwtServiceTests
|
||||
_fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList().ForEach(b => _fixture.Behaviors.Remove(b));
|
||||
_fixture.Behaviors.Add(new OmitOnRecursionBehavior());
|
||||
|
||||
_testJwtOptions = new JwtOption
|
||||
_testJwtAccessOptions = new JwtAccessOption
|
||||
{
|
||||
SecretKeу = "THIS IS A TEST SECRET KEY THAT IS LONG ENOUGH", // Ensure key size is sufficient for HMACSHA256
|
||||
Hours = 1
|
||||
SecretKeу = "THIS_IS_A_TEST_SECRET_KEY_THAT_IS_LONG_ENOUGH_1234", // Ensure key size is sufficient for HMACSHA256
|
||||
Minutes = 5
|
||||
};
|
||||
|
||||
_jwtOptionsMock = new Mock<IOptions<JwtOption>>();
|
||||
_jwtOptionsMock.Setup(o => o.Value).Returns(_testJwtOptions);
|
||||
|
||||
_testJwtRefreshOptions = new JwtRefreshOption()
|
||||
{
|
||||
RefreshTokenLifetimeDays = 30
|
||||
};
|
||||
|
||||
_jwtOptionsMock = new Mock<IOptions<JwtAccessOption>>();
|
||||
_jwtOptionsMock.Setup(o => o.Value).Returns(_testJwtAccessOptions);
|
||||
|
||||
_jwtRefreshOptionsMock = new Mock<IOptions<JwtRefreshOption>>();
|
||||
_jwtRefreshOptionsMock.Setup(o => o.Value).Returns(_testJwtRefreshOptions);
|
||||
|
||||
_invitesServiceMock = new Mock<IInvitesService>();
|
||||
|
||||
_jwtService = new JwtService(_jwtOptionsMock.Object, _invitesServiceMock.Object);
|
||||
_jwtService = new JwtService(
|
||||
_jwtOptionsMock.Object,
|
||||
_jwtRefreshOptionsMock.Object,
|
||||
_invitesServiceMock.Object);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -48,7 +63,7 @@ public class JwtServiceTests
|
||||
var expectedRole = "User";
|
||||
_invitesServiceMock.Setup(s => s.GetRoleAsync(user)).Returns(Task.FromResult(expectedRole));
|
||||
// Act
|
||||
var tokenString = await _jwtService.GenerateJwtTokenAsync(user);
|
||||
var tokenString = await _jwtService.GenerateAccessTokenAsync(user);
|
||||
|
||||
// Assert
|
||||
Assert.That(tokenString, Is.Not.Null.And.Not.Empty);
|
||||
@@ -57,4 +72,57 @@ public class JwtServiceTests
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
Assert.DoesNotThrow(() => handler.ReadJwtToken(tokenString));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GenerateRefreshTokenAsync_ReturnsValidRefreshToken()
|
||||
{
|
||||
// Arrange
|
||||
var user = new User { Id = Guid.NewGuid() };
|
||||
|
||||
// Act
|
||||
var token = await _jwtService.GenerateRefreshTokenAsync(user);
|
||||
|
||||
// Assert
|
||||
Assert.That(token, Is.Not.Null);
|
||||
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwt = handler.ReadJwtToken(token);
|
||||
|
||||
Assert.That(user.Id.ToString(), Is.EqualTo(jwt.Claims.First(c => c.Type == "userId").Value));
|
||||
Assert.That("refresh",Is.EqualTo(jwt.Claims.First(c => c.Type == "tokenType").Value));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetPrincipalFromExpiredToken_ReturnsValidClaimsPrincipal()
|
||||
{
|
||||
// Arrange
|
||||
var userId = Guid.NewGuid();
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_testJwtAccessOptions.SecretKeу));
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
var token = handler.CreateToken(new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim("userId", userId.ToString())
|
||||
}),
|
||||
NotBefore = now.AddSeconds(-10),
|
||||
IssuedAt = now.AddSeconds(-10),
|
||||
Expires = now.AddSeconds(-5),
|
||||
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
|
||||
});
|
||||
|
||||
var expiredToken = handler.WriteToken(token);
|
||||
|
||||
// Act
|
||||
var principal = _jwtService.GetPrincipalFromExpiredToken(expiredToken);
|
||||
|
||||
// Assert
|
||||
Assert.That(principal, Is.Not.Null);
|
||||
var claim = principal.FindFirst("userId");
|
||||
Assert.That(claim, Is.Not.Null);
|
||||
Assert.That(userId.ToString(), Is.EqualTo(claim.Value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using Govor.Application.Interfaces.Authentication;
|
||||
using Govor.Application.Services.Authentication;
|
||||
using Govor.Application.Services.UserSessions;
|
||||
using Govor.Core.Models;
|
||||
using Govor.Core.Models.Users;
|
||||
using Govor.Core.Repositories.UserSessionsRepository;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Moq;
|
||||
|
||||
namespace Govor.Application.Tests.Services.UserSessions;
|
||||
|
||||
[TestFixture]
|
||||
public class UserSessionOpenerTests
|
||||
{
|
||||
private Mock<IUserSessionsRepository> _repositoryMock;
|
||||
private Mock<IJwtService> _jwtServiceMock;
|
||||
private Mock<ILogger<UserSessionOpener>> _loggerMock;
|
||||
private IOptions<JwtRefreshOption> _options;
|
||||
private UserSessionOpener _service;
|
||||
private User _user;
|
||||
private const string DeviceInfo = "Chrome on Windows";
|
||||
private const string GeneratedToken = "new-refresh-token";
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
_repositoryMock = new Mock<IUserSessionsRepository>();
|
||||
_jwtServiceMock = new Mock<IJwtService>();
|
||||
_loggerMock = new Mock<ILogger<UserSessionOpener>>();
|
||||
_options = Options.Create(new JwtRefreshOption { RefreshTokenLifetimeDays = 30 });
|
||||
|
||||
_service = new UserSessionOpener(
|
||||
_repositoryMock.Object,
|
||||
_jwtServiceMock.Object,
|
||||
_options,
|
||||
_loggerMock.Object
|
||||
);
|
||||
|
||||
_user = new User
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "test",
|
||||
PasswordHash = "hashed",
|
||||
IconId = Guid.NewGuid(),
|
||||
CreatedOn = DateOnly.FromDateTime(DateTime.UtcNow),
|
||||
WasOnline = DateTime.UtcNow,
|
||||
InviteId = Guid.NewGuid()
|
||||
};
|
||||
|
||||
_jwtServiceMock
|
||||
.Setup(j => j.GenerateRefreshTokenAsync(_user))
|
||||
.ReturnsAsync(GeneratedToken);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OpenSessionAsync_ShouldReturnExistingToken_IfSessionValid()
|
||||
{
|
||||
// Arrange
|
||||
var session = new Core.Models.UserSession
|
||||
{
|
||||
UserId = _user.Id,
|
||||
DeviceInfo = DeviceInfo,
|
||||
RefreshToken = "valid-token",
|
||||
CreatedAt = DateTime.UtcNow.AddDays(-10),
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(10),
|
||||
IsRevoked = false
|
||||
};
|
||||
|
||||
_repositoryMock
|
||||
.Setup(r => r.GetByUserIdAsync(_user.Id))
|
||||
.ReturnsAsync(new List<UserSession> { session });
|
||||
|
||||
// Act
|
||||
var result = await _service.OpenSessionAsync(_user, DeviceInfo);
|
||||
|
||||
// Asser
|
||||
Assert.That(result, Is.EqualTo("valid-token"));
|
||||
_repositoryMock.Verify(r => r.UpdateAsync(It.IsAny<UserSession>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OpenSessionAsync_ShouldUpdateSession_IfExpiredOrRevoked()
|
||||
{
|
||||
// Arrange
|
||||
var session = new Core.Models.UserSession
|
||||
{
|
||||
UserId = _user.Id,
|
||||
DeviceInfo = DeviceInfo,
|
||||
RefreshToken = "old-token",
|
||||
CreatedAt = DateTime.UtcNow.AddDays(-40),
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(-1),
|
||||
IsRevoked = false
|
||||
};
|
||||
|
||||
_repositoryMock
|
||||
.Setup(r => r.GetByUserIdAsync(_user.Id))
|
||||
.ReturnsAsync(new List<UserSession> { session });
|
||||
|
||||
// Act
|
||||
var result = await _service.OpenSessionAsync(_user, DeviceInfo);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EqualTo(GeneratedToken));
|
||||
_repositoryMock.Verify(r => r.UpdateAsync(It.Is<UserSession>(s => s.RefreshToken == GeneratedToken)), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OpenSessionAsync_ShouldCreateNewSession_IfNoneExists()
|
||||
{
|
||||
// Arrange
|
||||
_repositoryMock
|
||||
.Setup(r => r.GetByUserIdAsync(_user.Id))
|
||||
.ReturnsAsync(new List<UserSession>());
|
||||
|
||||
// Act
|
||||
var result = await _service.OpenSessionAsync(_user, DeviceInfo);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EqualTo(GeneratedToken));
|
||||
_repositoryMock.Verify(r => r.AddAsync(It.Is<UserSession>(s =>
|
||||
s.UserId == _user.Id &&
|
||||
s.DeviceInfo == DeviceInfo &&
|
||||
s.RefreshToken == GeneratedToken
|
||||
)), Times.Once);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user