mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 19:21:10 +00:00
Adds authentication unit tests
This commit is contained in:
1 parent
a6dcf65d1c
commit
4f91f29b62
101 files changed
+5549
-135
No files matched your search
+207
@@ -0,0 +1,207 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
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.Core.UsersManagement.Authentication.Commands.ChangePassword;
|
||||
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
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 IHashService _mockHashService;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly ChangePasswordCommandHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ChangePasswordCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockHashService = Substitute.For<IHashService>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
||||
|
||||
_sut = new ChangePasswordCommandHandler(
|
||||
_mockUnitOfWork,
|
||||
_mockHashService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenPasswordChangeIsSuccessful_ShouldUpdateUserAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
string currentPassword = "currentPassword";
|
||||
string newPassword = "newPassword";
|
||||
string hashedNewPassword = "hashedNewPassword";
|
||||
string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword");
|
||||
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.Password = escapedHashedCurrentPassword;
|
||||
|
||||
ChangePasswordCommand command = new(
|
||||
user.Username,
|
||||
currentPassword,
|
||||
newPassword,
|
||||
newPassword);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.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
|
||||
ErrorOr<ChangePasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.IsPasswordChanged.Should().BeTrue();
|
||||
|
||||
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 Handle_WhenUserDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = new("nonexistentUser", "oldPass", "newPass", "newPass");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
|
||||
// Act
|
||||
ErrorOr<ChangePasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.UsernameDoesNotExist);
|
||||
|
||||
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 Handle_WhenCurrentPasswordIsIncorrect_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
string incorrectPassword = "wrongPassword";
|
||||
|
||||
ChangePasswordCommand command = new(
|
||||
user.Username,
|
||||
incorrectPassword,
|
||||
"newPass",
|
||||
"newPass");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password))
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
ErrorOr<ChangePasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.InvalidCurrentPassword);
|
||||
|
||||
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 Handle_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.CreateUserEntity();
|
||||
user.Password = escapedHashedCurrentPassword;
|
||||
|
||||
ChangePasswordCommand command = new(
|
||||
user.Username,
|
||||
currentPassword,
|
||||
newPassword,
|
||||
newPassword);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword")
|
||||
.Returns(true);
|
||||
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<ChangePasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
|
||||
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 Handle_WhenGetByUsernameReturnsError_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string currentPassword = "currentPassword";
|
||||
string newPassword = "newPassword";
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
ChangePasswordCommand command = new(
|
||||
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
|
||||
ErrorOr<ChangePasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
|
||||
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>());
|
||||
}
|
||||
}
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation.TestHelper;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
|
||||
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures;
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordCommandValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public ChangePasswordCommandValidatorTests()
|
||||
{
|
||||
_validator = new ChangePasswordCommandValidator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { Username = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { Username = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { Username = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCurrentPasswordIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { CurrentPassword = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.CurrentPassword)
|
||||
.WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCurrentPasswordIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { CurrentPassword = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.CurrentPassword)
|
||||
.WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCurrentPasswordIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { CurrentPassword = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.CurrentPassword)
|
||||
.WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNewPasswordIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { NewPassword = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.NewPassword)
|
||||
.WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNewPasswordIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { NewPassword = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.NewPassword)
|
||||
.WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNewPasswordIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { NewPassword = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.NewPassword)
|
||||
.WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNewPasswordConfirmIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { NewPasswordConfirm = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm)
|
||||
.WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNewPasswordConfirmIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { NewPasswordConfirm = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm)
|
||||
.WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNewPasswordConfirmIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { NewPasswordConfirm = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm)
|
||||
.WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNewPasswordAndNewPasswordConfirmDontMatch_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { NewPasswordConfirm = "$321Bcda" };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.NewPassword)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description);
|
||||
}
|
||||
|
||||
[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.CreateChangePasswordCommand();
|
||||
command = command with { CurrentPassword = password };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.CurrentPassword)
|
||||
.WithErrorMessage(Errors.Authentication.InvalidPassword.Description);
|
||||
}
|
||||
|
||||
[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.CreateChangePasswordCommand();
|
||||
command = command with { NewPassword = password, NewPasswordConfirm = password };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.NewPassword)
|
||||
.WithErrorMessage(Errors.Authentication.InvalidPassword.Description);
|
||||
}
|
||||
|
||||
[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.CreateChangePasswordCommand();
|
||||
command = command with
|
||||
{
|
||||
CurrentPassword = password,
|
||||
NewPassword = password,
|
||||
NewPasswordConfirm = password
|
||||
};
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.CurrentPassword);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.NewPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Username);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.CurrentPassword);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.NewPassword);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.NewPasswordConfirm);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ChangePasswordCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for changing a password.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static ChangePasswordCommand CreateChangePasswordCommand()
|
||||
{
|
||||
string currentPassword = "Abcd123$";
|
||||
string newPassword = "Wxyz789#";
|
||||
return new Faker<ChangePasswordCommand>()
|
||||
.CustomInstantiator(f => new ChangePasswordCommand(
|
||||
default!,
|
||||
default!,
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Username, f => f.Person.UserName)
|
||||
.RuleFor(x => x.CurrentPassword, currentPassword)
|
||||
.RuleFor(x => x.NewPassword, newPassword)
|
||||
.RuleFor(x => x.NewPasswordConfirm, newPassword);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ChangePasswordRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public ChangePasswordRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ChangePasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="ChangePasswordRequest"/>.</returns>
|
||||
public ChangePasswordRequest CreateChangePasswordRequest(
|
||||
string? username = null,
|
||||
string? currentPassword = null,
|
||||
string? newPassword = null,
|
||||
string? newPasswordConfirm = null)
|
||||
{
|
||||
return new ChangePasswordRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
currentPassword ?? _faker.Internet.Password(),
|
||||
newPassword ?? _faker.Internet.Password(),
|
||||
newPasswordConfirm ?? _faker.Internet.Password()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ChangePasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<ChangePasswordRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateChangePasswordRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RecoverPasswordCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for password recovery.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static RecoverPasswordCommand CreateRecoverPasswordCommand()
|
||||
{
|
||||
return new Faker<RecoverPasswordCommand>()
|
||||
.CustomInstantiator(f => new RecoverPasswordCommand(
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Username, f => f.Person.UserName)
|
||||
.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RecoverPasswordRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RecoverPasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="RecoverPasswordRequest"/>.</returns>
|
||||
public RecoverPasswordRequest CreateRecoverPasswordRequest(
|
||||
string? username = null,
|
||||
string? totpCode = null)
|
||||
{
|
||||
return new RecoverPasswordRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
totpCode ?? _faker.Random.Number(100000, 999999).ToString()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RecoverPasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<RecoverPasswordRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateRecoverPasswordRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
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.Core.UsersManagement.Authentication.Commands.RecoverPassword;
|
||||
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
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 IHashService _mockHashService;
|
||||
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
|
||||
private readonly ICryptographyService _mockCryptographyService;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly RecoverPasswordCommandHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckInitializationQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockHashService = Substitute.For<IHashService>();
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
||||
|
||||
_sut = new RecoverPasswordCommandHandler(
|
||||
_mockUnitOfWork,
|
||||
_mockHashService,
|
||||
_mockTotpTokenGenerator,
|
||||
_mockCryptographyService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_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.CreateUserEntity();
|
||||
user.TotpSecret = encryptedTotpSecret;
|
||||
user.TempPassword = null;
|
||||
|
||||
RecoverPasswordCommand command = new(user.Username, totpCode);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.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
|
||||
ErrorOr<RecoverPasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.IsPasswordReset.Should().BeTrue();
|
||||
|
||||
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 Handle_WhenUserDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = new("nonexistentUser", "123456");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.UsernameDoesNotExist);
|
||||
|
||||
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 Handle_WhenTempPasswordExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.TempPassword = "existingTempPassword";
|
||||
user.TempPasswordCreated = DateTime.UtcNow;
|
||||
|
||||
RecoverPasswordCommand command = new(user.Username, "123456");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.PasswordResetAlreadyRequested);
|
||||
|
||||
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 Handle_WhenUserDoesNotUseTOTP_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.TotpSecret = null;
|
||||
|
||||
RecoverPasswordCommand command = new(user.Username, "123456");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode);
|
||||
|
||||
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 Handle_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.CreateUserEntity();
|
||||
user.TotpSecret = encryptedTotpSecret;
|
||||
|
||||
RecoverPasswordCommand command = new(user.Username, totpCode);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockCryptographyService.Decrypt(encryptedTotpSecret)
|
||||
.Returns(decryptedTotpSecret);
|
||||
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode);
|
||||
|
||||
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 Handle_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.CreateUserEntity();
|
||||
user.TotpSecret = encryptedTotpSecret;
|
||||
|
||||
RecoverPasswordCommand command = new(user.Username, totpCode);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.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
|
||||
ErrorOr<RecoverPasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
|
||||
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 Handle_WhenGetByUsernameReturnsError_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string totpCode = "123456";
|
||||
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
|
||||
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.TotpSecret = encryptedTotpSecret;
|
||||
|
||||
RecoverPasswordCommand command = new(user.Username, totpCode);
|
||||
Error error = Error.Failure("Database.Error", "Failed to check username");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
|
||||
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 Handle_WhenUserUsesTOTPButNoCodeProvided_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
|
||||
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.TotpSecret = encryptedTotpSecret;
|
||||
|
||||
RecoverPasswordCommand command = new(user.Username, null);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode);
|
||||
|
||||
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>());
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation.TestHelper;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
|
||||
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures;
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordCommandValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordCommandValidatorTests()
|
||||
{
|
||||
_validator = new RecoverPasswordCommandValidator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
command = command with { Username = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
command = command with { Username = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
command = command with { Username = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTotpCodeIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
command = command with { TotpCode = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.TotpCode)
|
||||
.WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTotpCodeIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
command = command with { TotpCode = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.TotpCode)
|
||||
.WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTotpCodeIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
command = command with { TotpCode = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.TotpCode)
|
||||
.WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[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.CreateRecoverPasswordCommand();
|
||||
command = command with { TotpCode = totpCode };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.TotpCode)
|
||||
.WithErrorMessage(Errors.Authentication.InvalidTotpCode.Description);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("123456")]
|
||||
[InlineData("000000")]
|
||||
[InlineData("999999")]
|
||||
public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode)
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
command = command with { TotpCode = totpCode };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.TotpCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Username);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.TotpCode);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RegisterUserCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterUserCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for a new account registration.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static RegisterUserCommand CreateRegisterCommand()
|
||||
{
|
||||
string password = "Abcd123$";
|
||||
return new Faker<RegisterUserCommand>()
|
||||
.CustomInstantiator(f => new RegisterUserCommand(
|
||||
default!,
|
||||
default!,
|
||||
default!,
|
||||
true
|
||||
))
|
||||
.RuleFor(x => x.Username, f => f.Person.UserName)
|
||||
.RuleFor(x => x.Password, password)
|
||||
.RuleFor(x => x.PasswordConfirm, password);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RegistrationRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegistrationRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegistrationRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public RegistrationRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RegistrationRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="RegistrationRequest"/>.</returns>
|
||||
public RegistrationRequest CreateRegistrationRequest(
|
||||
string? username = null,
|
||||
string? password = null,
|
||||
string? passwordConfirm = null,
|
||||
bool? use2fa = null)
|
||||
{
|
||||
password ??= _faker.Internet.Password();
|
||||
|
||||
return new RegistrationRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
password,
|
||||
passwordConfirm ?? password,
|
||||
use2fa ?? _faker.Random.Bool()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RegistrationRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<RegistrationRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateRegistrationRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
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.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
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 IHashService _mockHashService;
|
||||
private readonly ICryptographyService _mockCryptographyService;
|
||||
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
|
||||
private readonly IQRCodeGenerator _mockQRCodeGenerator;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly RegisterUserCommandHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterUserCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public RegisterUserCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockHashService = Substitute.For<IHashService>();
|
||||
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
||||
|
||||
_sut = new RegisterUserCommandHandler(
|
||||
_mockUnitOfWork,
|
||||
_mockHashService,
|
||||
_mockCryptographyService,
|
||||
_mockTotpTokenGenerator,
|
||||
_mockQRCodeGenerator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenUserDoesNotExistAndWith2FA_ShouldRegisterUser()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
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(ErrorOrFactory.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
|
||||
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Username.Should().Be(command.Username);
|
||||
result.Value.TotpSecret.Should().Be(qrCodeUri);
|
||||
|
||||
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 Handle_WhenUserDoesNotExistAndWithout2FA_ShouldRegisterUser()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand() with { Use2fa = false };
|
||||
string hashedPassword = "hashedPassword";
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
_mockHashService.HashString(command.Password!)
|
||||
.Returns(hashedPassword);
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Username.Should().Be(command.Username);
|
||||
result.Value.TotpSecret.Should().BeNull();
|
||||
|
||||
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 Handle_WhenUserAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
UserEntity existingUser = UserEntityFixture.CreateUserEntity();
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(existingUser));
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.UsernameAlreadyExists);
|
||||
|
||||
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 Handle_WhenInsertFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
Error error = Error.Failure("Database.Error", "Failed to insert user");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
|
||||
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 Handle_WhenGetByUsernameReturnsError_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
Error error = Error.Failure("Database.Error", "Failed to check username");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
|
||||
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>());
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation.TestHelper;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterUserCommandValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public RegisterUserCommandValidatorTests()
|
||||
{
|
||||
_validator = new RegisterUserCommandValidator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { Username = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { Username = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { Username = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { Password = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { Password = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { Password = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { PasswordConfirm = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { PasswordConfirm = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { PasswordConfirm = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { PasswordConfirm = "$321Bcda" };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description);
|
||||
}
|
||||
|
||||
[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.CreateRegisterCommand();
|
||||
command = command with { Password = password, PasswordConfirm = password };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||
.WithErrorMessage(Errors.Authentication.InvalidPassword.Description);
|
||||
}
|
||||
|
||||
[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.CreateRegisterCommand();
|
||||
command = command with { Password = password, PasswordConfirm = password };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Password);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RegisterUserCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Username);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Password);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.PasswordConfirm);
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LoginRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public LoginRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="LoginRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="LoginRequest"/>.</returns>
|
||||
public LoginRequest CreateLoginRequest(
|
||||
string? username = null,
|
||||
string? password = null,
|
||||
string? totpCode = null)
|
||||
{
|
||||
return new LoginRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
password ?? _faker.Internet.Password(),
|
||||
totpCode ?? _faker.Random.Number(100000, 999999).ToString()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="LoginRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<LoginRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateLoginRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LoginUserQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginUserQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query for user login.
|
||||
/// </summary>
|
||||
/// <param name="includeTotpCode">Whether to include a TOTP code in the query.</param>
|
||||
/// <returns>The created query.</returns>
|
||||
public static LoginUserQuery CreateLoginQuery(bool includeTotpCode = false)
|
||||
{
|
||||
string password = "Abcd123$";
|
||||
Faker<LoginUserQuery> faker = new Faker<LoginUserQuery>()
|
||||
.CustomInstantiator(f => new LoginUserQuery(
|
||||
default!,
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.Username, f => f.Person.UserName)
|
||||
.RuleFor(x => x.Password, password);
|
||||
|
||||
if (includeTotpCode)
|
||||
faker.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits
|
||||
return faker;
|
||||
}
|
||||
}
|
||||
+357
@@ -0,0 +1,357 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
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.Core.UsersManagement.Authentication.Queries.LoginUser;
|
||||
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
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 IHashService _mockHashService;
|
||||
private readonly IJwtTokenGenerator _mockJwtTokenGenerator;
|
||||
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
|
||||
private readonly ICryptographyService _mockCryptographyService;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly LoginUserQueryHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginUserQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public LoginUserQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockHashService = Substitute.For<IHashService>();
|
||||
_mockJwtTokenGenerator = Substitute.For<IJwtTokenGenerator>();
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
||||
|
||||
_sut = new LoginUserQueryHandler(
|
||||
_mockUnitOfWork,
|
||||
_mockHashService,
|
||||
_mockJwtTokenGenerator,
|
||||
_mockTotpTokenGenerator,
|
||||
_mockCryptographyService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenValidCredentialsWithoutTOTP_ShouldReturnLoginResponse()
|
||||
{
|
||||
// Arrange
|
||||
string password = "password123";
|
||||
string hashedPassword = "hashedPassword";
|
||||
string jwtToken = "jwtToken";
|
||||
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.Password = Uri.EscapeDataString(hashedPassword);
|
||||
user.TotpSecret = null;
|
||||
|
||||
LoginUserQuery query = new(user.Username, password);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(true);
|
||||
_mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username)
|
||||
.Returns(jwtToken);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Id.Should().Be(user.Id);
|
||||
result.Value.Username.Should().Be(user.Username);
|
||||
result.Value.Token.Should().Be(jwtToken);
|
||||
result.Value.UsesTotp.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_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.CreateUserEntity();
|
||||
user.Password = Uri.EscapeDataString(hashedPassword);
|
||||
user.TotpSecret = encryptedTotpSecret;
|
||||
|
||||
LoginUserQuery query = new(user.Username, password, totpCode);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.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
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Id.Should().Be(user.Id);
|
||||
result.Value.Username.Should().Be(user.Username);
|
||||
result.Value.Token.Should().Be(jwtToken);
|
||||
result.Value.UsesTotp.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenUserDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = new("nonexistentUser", "password");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.InvalidUsernameOrPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenPasswordIsIncorrect_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string password = "wrongPassword";
|
||||
string hashedPassword = "hashedPassword";
|
||||
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.Password = Uri.EscapeDataString(hashedPassword);
|
||||
user.TempPassword = null;
|
||||
|
||||
LoginUserQuery query = new(user.Username, password);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.InvalidUsernameOrPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenTempPasswordIsExpired_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string password = "tempPassword";
|
||||
string hashedPassword = "hashedPassword";
|
||||
string hashedTempPassword = "hashedTempPassword";
|
||||
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.Password = Uri.EscapeDataString(hashedPassword);
|
||||
user.TempPassword = Uri.EscapeDataString(hashedTempPassword);
|
||||
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // Expired (more than 15 minutes old)
|
||||
|
||||
LoginUserQuery query = new(user.Username, password);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(false);
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedTempPassword)
|
||||
.Returns(true);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.TempPasswordExpired);
|
||||
|
||||
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 Handle_WhenValidTempPassword_ShouldReturnLoginResponse()
|
||||
{
|
||||
// Arrange
|
||||
string password = "tempPassword";
|
||||
string hashedPassword = "hashedPassword";
|
||||
string hashedTempPassword = "hashedTempPassword";
|
||||
string jwtToken = "jwtToken";
|
||||
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
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 = new(user.Username, password);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.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
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Id.Should().Be(user.Id);
|
||||
result.Value.Username.Should().Be(user.Username);
|
||||
result.Value.Token.Should().Be(jwtToken);
|
||||
result.Value.UsesTotp.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenUserHasTOTPButNoCodeProvided_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string password = "password123";
|
||||
string hashedPassword = "hashedPassword";
|
||||
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
|
||||
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.Password = Uri.EscapeDataString(hashedPassword);
|
||||
user.TotpSecret = encryptedTotpSecret;
|
||||
|
||||
LoginUserQuery query = new(user.Username, password);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(true);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_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.CreateUserEntity();
|
||||
user.Password = Uri.EscapeDataString(hashedPassword);
|
||||
user.TotpSecret = encryptedTotpSecret;
|
||||
|
||||
LoginUserQuery query = new(user.Username, password, totpCode);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(true);
|
||||
_mockCryptographyService.Decrypt(encryptedTotpSecret)
|
||||
.Returns(decryptedTotpSecret);
|
||||
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = new("username", "password");
|
||||
Error error = Error.Failure("Database.Error", "Failed to retrieve user");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenBothRegularAndTempPasswordsAreIncorrect_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string password = "wrongPassword";
|
||||
string hashedPassword = "hashedPassword";
|
||||
string hashedTempPassword = "hashedTempPassword";
|
||||
|
||||
UserEntity user = UserEntityFixture.CreateUserEntity();
|
||||
user.Password = Uri.EscapeDataString(hashedPassword);
|
||||
user.TempPassword = Uri.EscapeDataString(hashedTempPassword);
|
||||
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); // Valid timeframe
|
||||
|
||||
LoginUserQuery query = new(user.Username, password);
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.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
|
||||
ErrorOr<LoginResponse> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Authentication.InvalidUsernameOrPassword);
|
||||
|
||||
_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>());
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation.TestHelper;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
|
||||
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginUserQueryValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public LoginUserQueryValidatorTests()
|
||||
{
|
||||
_validator = new LoginUserQueryValidator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
query = query with { Username = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
query = query with { Username = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
query = query with { Username = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
query = query with { Password = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
query = query with { Password = string.Empty };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
query = query with { Password = " " };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[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.CreateLoginQuery();
|
||||
query = query with { Password = password };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||
.WithErrorMessage(Errors.Authentication.InvalidPassword.Description);
|
||||
}
|
||||
|
||||
[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.CreateLoginQuery();
|
||||
query = query with { Password = password };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Password);
|
||||
}
|
||||
|
||||
[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.CreateLoginQuery();
|
||||
query = query with { TotpCode = totpCode };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationErrorFor(x => x.TotpCode)
|
||||
.WithErrorMessage(Errors.Authentication.InvalidTotpCode.Description);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("123456")]
|
||||
[InlineData("000000")]
|
||||
[InlineData("999999")]
|
||||
public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode)
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
query = query with { TotpCode = totpCode };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.TotpCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTotpCodeIsNull_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
query = query with { TotpCode = null };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.TotpCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(true);
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Username);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Password);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.TotpCode);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user