Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,215 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.ChangePassword;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword;
/// <summary>
/// Contains unit tests for the <see cref="ChangePasswordCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ChangePasswordCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPasswordHashService _mockHashService;
private readonly IUserRepository _mockUserRepository;
private readonly ChangePasswordCommandHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly ChangePasswordCommandFixture _changePasswordCommandFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordCommandHandlerTests"/> class.
/// </summary>
public ChangePasswordCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockHashService = Substitute.For<IPasswordHashService>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
IValidator<ChangePasswordCommand> mockValidator = Substitute.For<IValidator<ChangePasswordCommand>>();
mockValidator.Validate(Arg.Any<ChangePasswordCommand>())
.Returns([]);
_sut = new ChangePasswordCommandHandler(
_mockUnitOfWork,
_mockHashService,
mockValidator);
}
[Fact]
public async Task HandleAsync_WhenPasswordChangeIsSuccessful_ShouldUpdateUserAndReturnSuccess()
{
// Arrange
string currentPassword = "currentPassword";
string newPassword = "newPassword";
string hashedNewPassword = "hashedNewPassword";
string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword");
UserEntity user = _userEntityFixture.Create();
user.Password = escapedHashedCurrentPassword;
ChangePasswordCommand command = _changePasswordCommandFixture.Create(
user.Username,
currentPassword,
newPassword,
newPassword);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword")
.Returns(true);
_mockHashService.HashString(newPassword)
.Returns(hashedNewPassword);
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<ChangePasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.IsPasswordChanged);
await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>());
_mockHashService.Received(1).CheckStringAgainstHash(currentPassword, "hashedCurrentPassword");
_mockHashService.Received(1).HashString(newPassword);
await _mockUserRepository.Received(1).UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create("nonexistentUser", "oldPass", "newPass", "newPass");
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
// Act
Result<ChangePasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.UsernameDoesNotExist, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnError()
{
// Arrange
UserEntity user = _userEntityFixture.Create();
string incorrectPassword = "wrongPassword";
ChangePasswordCommand command = _changePasswordCommandFixture.Create(
user.Username,
incorrectPassword,
"newPass",
"newPass");
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password))
.Returns(false);
// Act
Result<ChangePasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.InvalidCurrentPassword, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>());
_mockHashService.Received(1).CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password));
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnError()
{
// Arrange
string currentPassword = "currentPassword";
string newPassword = "newPassword";
string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword");
Error error = Error.Failure("Database.Error", "Failed to update user");
UserEntity user = _userEntityFixture.Create();
user.Password = escapedHashedCurrentPassword;
ChangePasswordCommand command = _changePasswordCommandFixture.Create(
user.Username,
currentPassword,
newPassword,
newPassword);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword")
.Returns(true);
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ChangePasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>());
_mockHashService.Received(1).CheckStringAgainstHash(currentPassword, "hashedCurrentPassword");
await _mockUserRepository.Received(1).UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError()
{
// Arrange
string currentPassword = "currentPassword";
string newPassword = "newPassword";
UserEntity user = _userEntityFixture.Create();
ChangePasswordCommand command = _changePasswordCommandFixture.Create(
user.Username,
currentPassword,
newPassword,
newPassword);
Error error = Error.Failure("Database.Error", "Failed to check username");
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ChangePasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,283 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.ChangePassword;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword;
/// <summary>
/// Contains unit tests for the <see cref="ChangePasswordCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ChangePasswordCommandValidatorTests
{
private readonly ChangePasswordCommandValidator _validator = new();
private readonly ChangePasswordCommandFixture _changePasswordCommandFixture = new();
[Fact]
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { Username = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { Username = string.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { Username = " " };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenCurrentPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { CurrentPassword = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.CurrentPasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenCurrentPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { CurrentPassword = string.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.CurrentPasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenCurrentPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { CurrentPassword = " " };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.CurrentPasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenNewPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPassword = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.NewPasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenNewPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPassword = string.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.NewPasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenNewPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPassword = " " };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.NewPasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenNewPasswordConfirmIsNull_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPasswordConfirm = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty);
}
[Fact]
public void Validate_WhenNewPasswordConfirmIsEmpty_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPasswordConfirm = string.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty);
}
[Fact]
public void Validate_WhenNewPasswordConfirmIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPasswordConfirm = " " };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty);
}
[Fact]
public void Validate_WhenNewPasswordAndNewPasswordConfirmDontMatch_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPasswordConfirm = "$321Bcda" };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordsNotMatch);
}
[Theory]
[InlineData("password123")] // Missing uppercase and special character.
[InlineData("PASSWORD123")] // Missing special character.
[InlineData("Password123")] // Missing special character.
[InlineData("Password!@#")] // Missing number.
[InlineData("Pass1!")] // Too short.
[InlineData("password")] // Missing uppercase, number, and special character.
public void Validate_WhenCurrentPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { CurrentPassword = password };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.InvalidPassword);
}
[Theory]
[InlineData("password123")] // Missing uppercase and special character.
[InlineData("PASSWORD123")] // Missing special character.
[InlineData("Password123")] // Missing special character.
[InlineData("Password!@#")] // Missing number.
[InlineData("Pass1!")] // Too short.
[InlineData("password")] // Missing uppercase, number, and special character.
public void Validate_WhenNewPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPassword = password, NewPasswordConfirm = password };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.InvalidPassword);
}
[Theory]
[InlineData("Password1!")] // Valid password.
[InlineData("Complex1@Password")] // Valid password.
[InlineData("MyP@ssw0rd")] // Valid password.
[InlineData("Abcd123!@#")] // Valid password.
public void Validate_WhenPasswordsMatchPattern_ShouldNotHaveValidationError(string password)
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with
{
CurrentPassword = password,
NewPassword = password,
NewPasswordConfirm = password
};
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword);
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword);
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword);
result.ShouldNotHaveValidationError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty);
}
}
@@ -0,0 +1,296 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RecoverPassword;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword;
/// <summary>
/// Contains unit tests for the <see cref="RecoverPasswordCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RecoverPasswordCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPasswordHashService _mockHashService;
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
private readonly ICryptographyService _mockCryptographyService;
private readonly IUserRepository _mockUserRepository;
private readonly RecoverPasswordCommandHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly RecoverPasswordCommandFixture _recoverPasswordCommandFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationQueryHandlerTests"/> class.
/// </summary>
public RecoverPasswordCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockHashService = Substitute.For<IPasswordHashService>();
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockCryptographyService = Substitute.For<ICryptographyService>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
IValidator<RecoverPasswordCommand> mockValidator = Substitute.For<IValidator<RecoverPasswordCommand>>();
mockValidator.Validate(Arg.Any<RecoverPasswordCommand>())
.Returns([]);
_sut = new RecoverPasswordCommandHandler(
_mockUnitOfWork,
_mockHashService,
_mockTotpTokenGenerator,
_mockCryptographyService,
mockValidator);
}
[Fact]
public async Task HandleAsync_WhenUserExistsAndTotpIsValid_ShouldResetPassword()
{
// Arrange
string totpCode = "123456";
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
string hashedTempPassword = "hashedTempPassword";
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
user.TempPassword = null;
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, totpCode);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockCryptographyService.Decrypt(encryptedTotpSecret)
.Returns(decryptedTotpSecret);
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
.Returns(true);
_mockHashService.HashString("Abcd123$")
.Returns(hashedTempPassword);
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<RecoverPasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.IsPasswordReset);
await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>());
_mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any<byte[]>(), totpCode);
_mockHashService.Received(1).HashString("Abcd123$");
await _mockUserRepository.Received(1).UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnError()
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create("nonexistentUser", "123456");
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
// Act
Result<RecoverPasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.UsernameDoesNotExist, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTempPasswordExists_ShouldReturnError()
{
// Arrange
UserEntity user = _userEntityFixture.Create();
user.TempPassword = "existingTempPassword";
user.TempPasswordCreated = DateTime.UtcNow;
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, "123456");
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
Result<RecoverPasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.PasswordResetAlreadyRequested, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotUseTOTP_ShouldReturnError()
{
// Arrange
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = null;
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, "123456");
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
Result<RecoverPasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTotpCodeIsInvalid_ShouldReturnError()
{
// Arrange
string totpCode = "123456";
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, totpCode);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockCryptographyService.Decrypt(encryptedTotpSecret)
.Returns(decryptedTotpSecret);
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
.Returns(false);
// Act
Result<RecoverPasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>());
_mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any<byte[]>(), totpCode);
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnError()
{
// Arrange
string totpCode = "123456";
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
Error error = Error.Failure("Database.Error", "Failed to update user");
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, totpCode);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockCryptographyService.Decrypt(encryptedTotpSecret)
.Returns(decryptedTotpSecret);
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
.Returns(true);
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<RecoverPasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>());
_mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any<byte[]>(), totpCode);
await _mockUserRepository.Received(1).UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError()
{
// Arrange
string totpCode = "123456";
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, totpCode);
Error error = Error.Failure("Database.Error", "Failed to check username");
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<RecoverPasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserUsesTOTPButNoCodeProvided_ShouldReturnError()
{
// Arrange
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, includeTotpCode: false);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
Result<RecoverPasswordResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>());
_mockTotpTokenGenerator.DidNotReceive().ValidateToken(Arg.Any<byte[]>(), Arg.Any<string>());
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,156 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RecoverPassword;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword;
/// <summary>
/// Contains unit tests for the <see cref="RecoverPasswordCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RecoverPasswordCommandValidatorTests
{
private readonly RecoverPasswordCommandValidator _validator = new();
private readonly RecoverPasswordCommandFixture _recoverPasswordCommandFixture = new();
[Fact]
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { Username = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { Username = string.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { Username = " " };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenTotpCodeIsNull_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.TotpCannotBeEmpty);
}
[Fact]
public void Validate_WhenTotpCodeIsEmpty_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = string.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.TotpCannotBeEmpty);
}
[Fact]
public void Validate_WhenTotpCodeIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = " " };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.TotpCannotBeEmpty);
}
[Theory]
[InlineData("12345")] // Too short.
[InlineData("1234567")] // Too long.
[InlineData("abcdef")] // Contains letters.
[InlineData("12345a")] // Contains letters.
[InlineData("12.345")] // Contains special characters.
[InlineData("12 345")] // Contains whitespace.
public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode)
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = totpCode };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.InvalidTotpCode);
}
[Theory]
[InlineData("123456")]
[InlineData("000000")]
[InlineData("999999")]
public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode)
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = totpCode };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidTotpCode);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Authentication.TotpCannotBeEmpty);
}
}
@@ -0,0 +1,204 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser;
/// <summary>
/// Contains unit tests for the <see cref="RegisterUserCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterUserCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPasswordHashService _mockHashService;
private readonly ICryptographyService _mockCryptographyService;
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
private readonly IQRCodeGenerator _mockQRCodeGenerator;
private readonly IUserRepository _mockUserRepository;
private readonly RegisterUserCommandHandler _sut;
private readonly RegisterUserCommandFixture _registerUserCommandFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RegisterUserCommandHandlerTests"/> class.
/// </summary>
public RegisterUserCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockHashService = Substitute.For<IPasswordHashService>();
_mockCryptographyService = Substitute.For<ICryptographyService>();
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
IValidator<RegisterUserCommand> mockValidator = Substitute.For<IValidator<RegisterUserCommand>>();
mockValidator.Validate(Arg.Any<RegisterUserCommand>())
.Returns([]);
_sut = new RegisterUserCommandHandler(
_mockUnitOfWork,
_mockHashService,
_mockCryptographyService,
_mockTotpTokenGenerator,
_mockQRCodeGenerator,
mockValidator);
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotExistAndWith2FA_ShouldRegisterUser()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
byte[] totpSecret = [1, 2, 3];
string qrCodeUri = "data:image/png;base64,test";
string encryptedSecret = "encryptedSecret";
string hashedPassword = "hashedPassword";
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
_mockHashService.HashString(command.Password!)
.Returns(hashedPassword);
_mockTotpTokenGenerator.GenerateSecret()
.Returns(totpSecret);
_mockQRCodeGenerator.GenerateQrCodeDataUri(command.Username!, totpSecret)
.Returns(qrCodeUri);
_mockCryptographyService.Encrypt(Convert.ToBase64String(totpSecret))
.Returns(encryptedSecret);
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(command.Username, result.Value.Username);
Assert.Equal(qrCodeUri, result.Value.TotpSecret);
await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>());
_mockHashService.Received(1).HashString(command.Password!);
_mockTotpTokenGenerator.Received(1).GenerateSecret();
_mockQRCodeGenerator.Received(1).GenerateQrCodeDataUri(command.Username!, totpSecret);
_mockCryptographyService.Received(1).Encrypt(Convert.ToBase64String(totpSecret));
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotExistAndWithout2FA_ShouldRegisterUser()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create() with { Use2fa = false };
string hashedPassword = "hashedPassword";
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
_mockHashService.HashString(command.Password!)
.Returns(hashedPassword);
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(command.Username, result.Value.Username);
Assert.Null(result.Value.TotpSecret);
await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>());
_mockHashService.Received(1).HashString(command.Password!);
_mockTotpTokenGenerator.DidNotReceive().GenerateSecret();
_mockQRCodeGenerator.DidNotReceive().GenerateQrCodeDataUri(Arg.Any<string>(), Arg.Any<byte[]>());
_mockCryptographyService.DidNotReceive().Encrypt(Arg.Any<string>());
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserAlreadyExists_ShouldReturnError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
UserEntity existingUser = _userEntityFixture.Create();
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(existingUser));
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.UsernameAlreadyExists, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenInsertFails_ShouldReturnError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to insert user");
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>());
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to check username");
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,282 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser;
/// <summary>
/// Contains unit tests for the <see cref="RegisterUserCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterUserCommandValidatorTests
{
private readonly RegisterUserCommandValidator _validator = new();
private readonly RegisterUserCommandFixture _registerUserCommandFixture = new();
[Fact]
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = string.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = " " };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = string.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = " " };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { PasswordConfirm = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { PasswordConfirm = string.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { PasswordConfirm = " " };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { PasswordConfirm = "$321Bcda" };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordsNotMatch);
}
[Theory]
[InlineData("password123")] // Missing uppercase and special character.
[InlineData("PASSWORD123")] // Missing special character.
[InlineData("Password123")] // Missing special character.
[InlineData("Password!@#")] // Missing number.
[InlineData("Pass1!")] // Too short.
[InlineData("password")] // Missing uppercase, number, and special character.
public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = password, PasswordConfirm = password };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.InvalidPassword);
}
[Theory]
[InlineData("Password1!")] // Valid password.
[InlineData("Complex1@Password")] // Valid password.
[InlineData("MyP@ssw0rd")] // Valid password.
[InlineData("Abcd123!@#")] // Valid password.
public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password)
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = password, PasswordConfirm = password };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with
{
Username = "valid.user123",
Password = "$321Bcda",
PasswordConfirm = "$321Bcda"
};
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword);
result.ShouldNotHaveValidationError(Errors.Authentication.PasswordConfirmCannotBeEmpty);
}
[Theory]
[InlineData("a")] // Too short.
[InlineData("ab")] // Too short.
[InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] // Too long (256 chars).
public void Validate_WhenUsernameHasInvalidLength_ShouldHaveValidationError(string username)
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = username };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong);
}
[Theory]
[InlineData(".username")] // Starts with special character.
[InlineData("username.")] // Ends with special character.
[InlineData("_username")] // Starts with special character.
[InlineData("username_")] // Ends with special character.
[InlineData("-username")] // Starts with special character.
[InlineData("username-")] // Ends with special character.
[InlineData("user name")] // Contains space.
[InlineData("user@name")] // Contains invalid special char.
[InlineData("user#name")] // Contains invalid special char.
[InlineData("user$name")] // Contains invalid special char.
public void Validate_WhenUsernameHasInvalidFormat_ShouldHaveValidationError(string username)
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = username };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.InvalidUsername);
}
[Theory]
[InlineData("user123")] // Basic alphanumeric.
[InlineData("user.name")] // With dot.
[InlineData("user_name")] // With underscore.
[InlineData("user-name")] // With hyphen.
[InlineData("User.Name123")] // Mixed case with special chars and numbers.
[InlineData("a1b")] // Minimum length.
[InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] // Maximum length (255 chars).
public void Validate_WhenUsernameHasValidFormat_ShouldNotHaveValidationError(string username)
{
// Arrange
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = username };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidUsername);
}
}
@@ -0,0 +1,138 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.GetUsers;
using Lumina.Contracts.Responses.UsersManagement.Users;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.GetUsers;
/// <summary>
/// Contains unit tests for the <see cref="GetUsersQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUsersQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IUserRepository _mockUserRepository;
private readonly GetUsersQueryHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly PaginatedResultDtoFixture<UserEntity> _paginatedResultDtoFixture = new();
private readonly GetUsersQueryFixture _getUsersQueryFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="GetUsersQueryHandlerTests"/> class.
/// </summary>
public GetUsersQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockUserRepository = Substitute.For<IUserRepository>();
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_sut = new GetUsersQueryHandler(
_mockAuthorizationService,
_mockCurrentUserService,
_mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
GetUsersQuery query = _getUsersQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<IEnumerable<UserResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockUserRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetUsersQuery query = _getUsersQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IEnumerable<UserResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetUsersFails_ShouldReturnError()
{
// Arrange
GetUsersQuery query = _getUsersQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get users");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
_mockUserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<IEnumerable<UserResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnUsers()
{
// Arrange
GetUsersQuery query = _getUsersQueryFixture.Create();
List<UserEntity> users = _userEntityFixture.CreateMany(2);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
_mockUserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: users, currentPage: 1, perPage: users.Count, count: users.Count, numberOfPages: 1)));
// Act
Result<IEnumerable<UserResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count());
}
}
@@ -0,0 +1,370 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser;
/// <summary>
/// Contains unit tests for the <see cref="LoginUserQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginUserQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPasswordHashService _mockHashService;
private readonly IJwtTokenGenerator _mockJwtTokenGenerator;
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
private readonly ICryptographyService _mockCryptographyService;
private readonly IUserRepository _mockUserRepository;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly LoginUserQueryHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LoginUserQueryFixture _loginUserQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryHandlerTests"/> class.
/// </summary>
public LoginUserQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockHashService = Substitute.For<IPasswordHashService>();
_mockJwtTokenGenerator = Substitute.For<IJwtTokenGenerator>();
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockCryptographyService = Substitute.For<ICryptographyService>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
IValidator<LoginUserQuery> mockValidator = Substitute.For<IValidator<LoginUserQuery>>();
mockValidator.Validate(Arg.Any<LoginUserQuery>())
.Returns([]);
_sut = new LoginUserQueryHandler(
_mockUnitOfWork,
_mockHashService,
_mockJwtTokenGenerator,
_mockTotpTokenGenerator,
_mockCryptographyService,
_mockDateTimeProvider,
mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidCredentialsWithoutTOTP_ShouldReturnLoginResponse()
{
// Arrange
string password = "password123";
string hashedPassword = "hashedPassword";
string jwtToken = "jwtToken";
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TotpSecret = null;
LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
.Returns(true);
_mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username)
.Returns(jwtToken);
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(user.Id, result.Value.Id);
Assert.Equal(user.Username, result.Value.Username);
Assert.Equal(jwtToken, result.Value.Token);
Assert.False(result.Value.UsesTotp);
}
[Fact]
public async Task HandleAsync_WhenValidCredentialsWithTOTP_ShouldReturnLoginResponse()
{
// Arrange
string password = "password123";
string hashedPassword = "hashedPassword";
string jwtToken = "jwtToken";
string totpCode = "123456";
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TotpSecret = encryptedTotpSecret;
LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password, totpCode: totpCode);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
.Returns(true);
_mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username)
.Returns(jwtToken);
_mockCryptographyService.Decrypt(encryptedTotpSecret)
.Returns(decryptedTotpSecret);
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
.Returns(true);
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(user.Id, result.Value.Id);
Assert.Equal(user.Username, result.Value.Username);
Assert.Equal(jwtToken, result.Value.Token);
Assert.True(result.Value.UsesTotp);
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create("nonexistentUser", "password");
_mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.InvalidUsernameOrPassword, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenPasswordIsIncorrect_ShouldReturnError()
{
// Arrange
string password = "wrongPassword";
string hashedPassword = "hashedPassword";
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TempPassword = null;
LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
.Returns(false);
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.InvalidUsernameOrPassword, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenTempPasswordIsExpired_ShouldReturnError()
{
// Arrange
string password = "tempPassword";
string hashedPassword = "hashedPassword";
string hashedTempPassword = "hashedTempPassword";
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TempPassword = Uri.EscapeDataString(hashedTempPassword);
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // Expired (more than 15 minutes old).
LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
.Returns(false);
_mockHashService.CheckStringAgainstHash(password, hashedTempPassword)
.Returns(true);
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.TempPasswordExpired, result.FirstError);
await _mockUserRepository.Received(1).UpdateAsync(Arg.Is<UserEntity>(u =>
u.TempPassword == null && u.TempPasswordCreated == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidTempPassword_ShouldReturnLoginResponse()
{
// Arrange
string password = "tempPassword";
string hashedPassword = "hashedPassword";
string hashedTempPassword = "hashedTempPassword";
string jwtToken = "jwtToken";
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TempPassword = Uri.EscapeDataString(hashedTempPassword);
// Set temp password created time to 10 minutes ago (still valid).
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10);
user.TotpSecret = null; // Ensure no TOTP validation is needed.
LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
.Returns(false); // Regular password check fails.
_mockHashService.CheckStringAgainstHash(password, hashedTempPassword)
.Returns(true); // Temp password check succeeds.
_mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username)
.Returns(jwtToken);
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(user.Id, result.Value.Id);
Assert.Equal(user.Username, result.Value.Username);
Assert.Equal(jwtToken, result.Value.Token);
Assert.False(result.Value.UsesTotp);
}
[Fact]
public async Task HandleAsync_WhenUserHasTOTPButNoCodeProvided_ShouldReturnError()
{
// Arrange
string password = "password123";
string hashedPassword = "hashedPassword";
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TotpSecret = encryptedTotpSecret;
LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
.Returns(true);
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenTOTPCodeIsInvalid_ShouldReturnError()
{
// Arrange
string password = "password123";
string hashedPassword = "hashedPassword";
string totpCode = "123456";
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TotpSecret = encryptedTotpSecret;
LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password, totpCode: totpCode);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
.Returns(true);
_mockCryptographyService.Decrypt(encryptedTotpSecret)
.Returns(decryptedTotpSecret);
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
.Returns(false);
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.InvalidTotpCode, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create("username", "password");
Error error = Error.Failure("Database.Error", "Failed to retrieve user");
_mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenBothRegularAndTempPasswordsAreIncorrect_ShouldReturnError()
{
// Arrange
string password = "wrongPassword";
string hashedPassword = "hashedPassword";
string hashedTempPassword = "hashedTempPassword";
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TempPassword = Uri.EscapeDataString(hashedTempPassword);
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); // Valid timeframe.
LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password);
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
.Returns(false); // Regular password check fails.
_mockHashService.CheckStringAgainstHash(password, hashedTempPassword)
.Returns(false); // Temp password check also fails.
// Act
Result<LoginResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authentication.InvalidUsernameOrPassword, result.FirstError);
_mockHashService.Received(1).CheckStringAgainstHash(password, hashedPassword);
_mockHashService.Received(1).CheckStringAgainstHash(password, hashedTempPassword);
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,209 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser;
/// <summary>
/// Contains unit tests for the <see cref="LoginUserQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginUserQueryValidatorTests
{
private readonly LoginUserQueryValidator _validator = new();
private readonly LoginUserQueryFixture _loginUserQueryFixture = new();
[Fact]
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Username = null! };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Username = string.Empty };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Username = " " };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = null! };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = string.Empty };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty);
}
[Fact]
public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = " " };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.PasswordCannotBeEmpty);
}
[Theory]
[InlineData("password123")] // Missing uppercase and special character.
[InlineData("PASSWORD123")] // Missing special character.
[InlineData("Password123")] // Missing special character.
[InlineData("Password!@#")] // Missing number.
[InlineData("Pass1!")] // Too short.
[InlineData("password")] // Missing uppercase, number, and special character.
public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = password };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.InvalidPassword);
}
[Theory]
[InlineData("Password1!")] // Valid password.
[InlineData("Complex1@Password")] // Valid password.
[InlineData("MyP@ssw0rd")] // Valid password.
[InlineData("Abcd123!@#")] // Valid password.
public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password)
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = password };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword);
}
[Theory]
[InlineData("12345")] // Too short.
[InlineData("1234567")] // Too long.
[InlineData("abcdef")] // Contains letters.
[InlineData("12345a")] // Contains letters.
[InlineData("12.345")] // Contains special characters.
[InlineData("12 345")] // Contains whitespace.
public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode)
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { TotpCode = totpCode };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Authentication.InvalidTotpCode);
}
[Theory]
[InlineData("123456")]
[InlineData("000000")]
[InlineData("999999")]
public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode)
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { TotpCode = totpCode };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidTotpCode);
}
[Fact]
public void Validate_WhenTotpCodeIsNull_ShouldNotHaveValidationError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { TotpCode = null };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidTotpCode);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
{
// Arrange
LoginUserQuery query = _loginUserQueryFixture.Create(includeTotpCode: true);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Authentication.UsernameCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidPassword);
result.ShouldNotHaveValidationError(Errors.Authentication.InvalidTotpCode);
}
}