Implements account registration

This commit is contained in:
BinaryAlley committed 2024-11-10 21:14:19 +02:00
1 parent d971b53512
commit bd97c2e8c1
13 files changed
+736

No files matched your search

@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
using Lumina.Application.Core.UsersManagement.Register;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Application.Common.Mapping.Authentication;
/// <summary>
/// Extension methods for converting <see cref="RegistrationRequest"/>.
/// </summary>
public static class RegistrationRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="SetupApplicationCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static SetupApplicationCommand ToSetupCommand(this RegistrationRequest request)
{
return new SetupApplicationCommand(
request.Username,
request.Password,
request.PasswordConfirm,
request.Use2fa
);
}
/// <summary>
/// Converts <paramref name="request"/> to <see cref="RegisterCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static RegisterCommand ToCommand(this RegistrationRequest request)
{
return new RegisterCommand(
request.Username,
request.Password,
request.PasswordConfirm,
request.Use2fa
);
}
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
#endregion
namespace Lumina.Application.Core.UsersManagement.Register;
/// <summary>
/// Command for registering a new account.
/// </summary>
/// <param name="Username">The username for the new account.</param>
/// <param name="Password">The password for the new account.</param>
/// <param name="PasswordConfirm">Confirmation of the password.</param>
/// <param name="Use2fa">Indicates whether to enable two-factor authentication for the new account.</param>
public record RegisterCommand(
string? Username,
string? Password,
string? PasswordConfirm,
bool Use2fa
) : IRequest<ErrorOr<RegistrationResponse>>;
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
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.Contracts.Responses.Authentication;
using Mediator;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.UsersManagement.Register;
/// <summary>
/// Handler for the command to register a new user account.
/// </summary>
public class RegisterCommandHandler : IRequestHandler<RegisterCommand, ErrorOr<RegistrationResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IHashService _hashService;
private readonly ICryptographyService _cryptographyService;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly IQRCodeGenerator _qRCodeGenerator;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="hashService">Injected service for password hashing functionality.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
public RegisterCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_cryptographyService = cryptographyService;
_totpTokenGenerator = totpTokenGenerator;
_qRCodeGenerator = qRCodeGenerator;
}
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(RegisterCommand request, CancellationToken cancellationToken)
{
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is not null)
return Errors.Authentication.UsernameAlreadyExists;
string? totpSecret = null;
UserEntity user = new()
{
Id = Guid.NewGuid(),
Username = request.Username!,
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
Created = DateTime.UtcNow,
Libraries = []
};
// if the user enabled two factor auth, include a QR with the totp secret
if (request.Use2fa)
{
// generate a TOTP secret
byte[] secret = _totpTokenGenerator.GenerateSecret();
// convert the secret into a QR code for the user to scan
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(request.Username!, secret);
// store the TOTP secret in the repository, encrypted
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken);
if (resultInsertUser.IsError)
return resultInsertUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// TODO: insert the default admin profile preferences when they are implemented
// if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
return new RegistrationResponse(user.Id, user.Username, totpSecret);
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
#endregion
namespace Lumina.Application.Core.UsersManagement.Register;
/// <summary>
/// Validates the needed validation rules for <see cref="RegisterCommand"/>.
/// </summary>
public class RegisterCommandValidator : AbstractValidator<RegisterCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RegisterCommandValidator"/> class.
/// </summary>
public RegisterCommandValidator()
{
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description);
RuleFor(x => x.PasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
RuleFor(x => x.Password).Equal(x => x.PasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description);
}
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Authentication;
/// <summary>
/// Represents the request model for user registration.
/// </summary>
/// <param name="Username">The desired username for the new account.</param>
/// <param name="Password">The password for the new account.</param>
/// <param name="PasswordConfirm">The confirmation of the entered password, used to ensure consistency.</param>
/// <param name="Use2fa">Indicates whether two-factor authentication (2FA) should be enabled for the new account.</param>
[DebuggerDisplay("Username: {Username}")]
public record RegistrationRequest(
string? Username = null,
string? Password = null,
string? PasswordConfirm = null,
bool Use2fa = true
);
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Authentication;
/// <summary>
/// Represents the response model for user registration.
/// </summary>
/// <param name="Id">The Id of the user.</param>
/// <param name="Username">The username of the user.</param>
/// <param name="TotpSecret">The TOTP (Time-Based One-Time Password) secret used for two-factor authentication.</param>
[DebuggerDisplay("Username: {Username}")]
public record RegistrationResponse(
Guid Id,
string Username,
string? TotpSecret
);
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Register;
/// <summary>
/// API endpoint for the <c>/account/register</c> route.
/// </summary>
public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public RegisterEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Account.REGISTER_ACCOUNT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Registers a new account.
/// </summary>
/// <param name="request">The request containing the account to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken)
{
ErrorOr<RegistrationResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Users.GET_USER_BY_ID}/{result.Value.Id}", result.Value), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Register;
/// <summary>
/// Class used for providing a textual description for the <see cref="RegisterEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class RegisterEndpointSummary : Summary<RegisterEndpoint, RegistrationRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEndpointSummary"/> class.
/// </summary>
public RegisterEndpointSummary()
{
Summary = "Registers a new account.";
Description = "Registes a new application account.";
RequestParam(r => r.Username, "The desired username for the new account.");
RequestParam(r => r.Password, "The password for the new account.");
RequestParam(r => r.PasswordConfirm, "The confirmation of the entered password, used to ensure consistency.");
RequestParam(r => r.Use2fa, "Indicates whether two-factor authentication (2FA) should be enabled for the new account.");
Response(200, "The new account of the application is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the request model for user registration.
/// </summary>
/// <param name="Username">The desired username for the new account.</param>
/// <param name="Password">The password for the new account.</param>
/// <param name="PasswordConfirm">The confirmation of the entered password, used to ensure consistency.</param>
/// <param name="RegistrationType">Specifies the type of registration, e.g., "Admin" or "User".</param>
/// <param name="Use2fa">Indicates whether two-factor authentication (2FA) should be enabled for the new account.</param>
[DebuggerDisplay("Username: {Username}")]
public record RegisterRequestModel(
string? Username = null,
string? Password = null,
string? PasswordConfirm = null,
string? RegistrationType = null,
bool Use2fa = true
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the response model for a successful registration.
/// </summary>
/// <param name="Username">The username of the registered user.</param>
/// <param name="TotpSecret">The TOTP (Time-Based One-Time Password) secret used for two-factor authentication.</param>
[DebuggerDisplay("Username: {Username}")]
public record RegisterResponseModel(
string? Username,
string? TotpSecret
);
@@ -0,0 +1,134 @@
@*
/account/register/
*@
@using Lumina.Presentation.Web.Common.Models.UsersManagement
@{
string? registrationType = ViewData["RegistrationType"] as string;
}
@model RegisterRequestModel
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<form asp-controller="Account" asp-action="Register" method="post" id="register-account-form" class="inline">
@Html.AntiForgeryToken()
<!-- section for determining registration type (regular user/admin) -->
<input type="hidden" name="RegistrationType" value="@registrationType" />
<div class="form-container">
@if (registrationType == "Admin")
{
<div class="form-row">
<p class="invalid-feedback w-95 text-center f-18">Admin account registration</p>
</div>
}
<!-- Username -->
<div class="form-row">
<div class="form-label">
<label asp-for="Username">Username</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input asp-for="Username" autocomplete="username" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionUsername</small>
</div>
<!-- Password -->
<div class="form-row">
<div class="form-label">
<label asp-for="Password">Password</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input type="password" asp-for="Password" autocomplete="new-password" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionPassword</small>
</div>
<!-- Password Confirm-->
<div class="form-row">
<div class="form-label">
<label asp-for="PasswordConfirm">Password Confirm</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input type="password" asp-for="PasswordConfirm" autocomplete="new-password" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionPasswordConfirm</small>
</div>
<!-- 2FA -->
<input type="hidden" id="hiddenUseTwoFa" name="use2fa" value="true">
<div class="form-row">
<div class="form-field">
<label class="enlightenment-checkbox-label">
<input type="checkbox" asp-for="Use2fa" class="enlightenment-checkbox-hidden" value="true" />
<span class="enlightenment-checkbox"></span>
Enable two factor authentication
</label>
</div>
<small class="form-label text-disabled form-description">Description2Fa</small>
</div>
<div class="form-row">
<span id="register2FaAttention" class="invalid-feedback w-95 text-center hidden">Password recovery is allowed only if two factor authentication is enabled!</span>
</div>
<div class="form-row" style="justify-content: center;">
<button type="submit" class="confirm-button h-22px w-100px">Register</button>
</div>
</div>
</form>
<!-- section registration success -->
<div class="text-center w-100">
<p id="registerSuccess" class="text-light-one w-100 hidden">Account Created</p>
<img id="totpImage" class="w-200px h-200px h-align-m mx-auto mt-10 hidden" />
<p id="totpMessage" class="text-light-one w-100 hidden">Scan Totp Code</p>
<a id="redirectButton" asp-controller="Account" asp-action="Login" class="confirm-button f-14 pt-0 pb-0 h-22px w-80px mt-10 mb-10 mx-auto hidden">Login</a>
</div>
</div>
@section Scripts {
<script type="text/javascript" defer>
document.getElementById('register-account-form').addEventListener('submit', async (event) => {
event.preventDefault();
const form = event.target;
const txtUsername = form.querySelector('[name="Username"]');
const txtPassword = form.querySelector('[name="Password"]');
const txtPasswordConfirm = form.querySelector('[name="PasswordConfirm"]');
const chkUse2FA = form.querySelector('[name="Use2fa"]');
const registerSuccess = document.getElementById('registerSuccess');
const redirectButton = document.getElementById('redirectButton');
const totpMessage = document.querySelector('#totpMessage');
const totpImage = document.querySelector('#totpImage');
const formData = {
Username: txtUsername.value,
Password: txtPassword.value,
PasswordConfirm: txtPasswordConfirm.value,
Use2fa: chkUse2FA.checked,
RegistrationType: form.querySelector('[name="RegistrationType"]').value
};
const data = await callApiPostAsync('/account/register', formData);
if (data) {
txtUsername.value = '';
txtPassword.value = '';
txtPasswordConfirm.value = '';
form.classList.replace('inline', 'hidden');
registerSuccess.classList.replace('hidden', 'inline');
redirectButton.classList.replace('hidden', 'block');
if (chkUse2FA.checked) {
totpMessage.classList.remove('hidden');
totpMessage.classList.add('block');
totpImage.classList.remove('hidden');
totpImage.classList.add('block');
totpImage.setAttribute('src', data.totpSecret);
}
}
});
document.querySelector('[name="Use2fa"]').addEventListener('change', function () {
const isChecked = this.checked;
document.querySelector('#register2FaAttention').classList.replace(
isChecked ? 'inline' : 'hidden',
isChecked ? 'hidden' : 'inline'
);
document.querySelector('#hiddenUseTwoFa').value = isChecked.toString();
});
</script>
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.UsersManagement.Register;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Register.Fixture;
/// <summary>
/// Fixture class for the <see cref="RegisterCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterCommandFixture
{
/// <summary>
/// Creates a random valid command for a new account registration.
/// </summary>
/// <returns>The created command.</returns>
public static RegisterCommand CreateRegisterCommand()
{
string password = "Abcd123$";
return new Faker<RegisterCommand>()
.CustomInstantiator(f => new RegisterCommand(
default!,
default!,
default!,
true
))
.RuleFor(x => x.Username, f => f.Person.UserName)
.RuleFor(x => x.Password, password)
.RuleFor(x => x.PasswordConfirm, password);
}
}
@@ -0,0 +1,231 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.UsersManagement.Register;
using Lumina.Application.UnitTests.Core.UsersManagement.Register.Fixture;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Register;
/// <summary>
/// Contains unit tests for the <see cref="RegisterCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterCommandValidatorTests
{
private readonly RegisterCommandValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterCommandValidatorTests"/> class.
/// </summary>
public RegisterCommandValidatorTests()
{
_validator = new RegisterCommandValidator();
}
[Fact]
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { Username = null! };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Username)
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { Username = string.Empty };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Username)
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { Username = " " };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Username)
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { Password = null! };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Password)
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { Password = string.Empty };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Password)
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { Password = " " };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Password)
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { PasswordConfirm = null! };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm)
.WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { PasswordConfirm = string.Empty };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm)
.WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { PasswordConfirm = " " };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm)
.WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { PasswordConfirm = "$321Bcda" };
// Act
TestValidationResult<RegisterCommand> 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
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { Password = password, PasswordConfirm = password };
// Act
TestValidationResult<RegisterCommand> 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
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { Password = password, PasswordConfirm = password };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Password);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand();
command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" };
// Act
TestValidationResult<RegisterCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Username);
result.ShouldNotHaveValidationErrorFor(x => x.Password);
result.ShouldNotHaveValidationErrorFor(x => x.PasswordConfirm);
}
}