From bd97c2e8c1f3baa2efc6368695eebf6729cf059a Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sun, 10 Nov 2024 21:14:19 +0200 Subject: [PATCH] Implements account registration --- .../RegistrationRequestMapping.cs | 43 ++++ .../Register/RegisterCommand.cs | 21 ++ .../Register/RegisterCommandHandler.cs | 88 +++++++ .../Register/RegisterCommandValidator.cs | 24 ++ .../Authentication/RegistrationRequest.cs | 20 ++ .../Authentication/RegistrationResponse.cs | 19 ++ .../Register/RegisterEndpoint.cs | 55 +++++ .../Register/RegisterEndpointSummary.cs | 29 +++ .../UsersManagement/RegisterRequestModel.cs | 22 ++ .../UsersManagement/RegisterResponseModel.cs | 17 ++ .../Views/Account/Register.cshtml | 134 ++++++++++ .../Fixture/RegisterCommandFixture.cs | 33 +++ .../Register/RegisterCommandValidatorTests.cs | 231 ++++++++++++++++++ 13 files changed, 736 insertions(+) create mode 100644 src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Register/RegisterCommand.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandHandler.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandValidator.cs create mode 100644 src/Lumina.Contracts/Requests/Authentication/RegistrationRequest.cs create mode 100644 src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs create mode 100644 src/Lumina.Presentation.Web/Views/Account/Register.cshtml create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/Fixture/RegisterCommandFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs diff --git a/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs new file mode 100644 index 00000000..aedd1c67 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class RegistrationRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static SetupApplicationCommand ToSetupCommand(this RegistrationRequest request) + { + return new SetupApplicationCommand( + request.Username, + request.Password, + request.PasswordConfirm, + request.Use2fa + ); + } + + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static RegisterCommand ToCommand(this RegistrationRequest request) + { + return new RegisterCommand( + request.Username, + request.Password, + request.PasswordConfirm, + request.Use2fa + ); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommand.cs b/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommand.cs new file mode 100644 index 00000000..ac923602 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Register; + +/// +/// Command for registering a new account. +/// +/// The username for the new account. +/// The password for the new account. +/// Confirmation of the password. +/// Indicates whether to enable two-factor authentication for the new account. +public record RegisterCommand( + string? Username, + string? Password, + string? PasswordConfirm, + bool Use2fa +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandHandler.cs new file mode 100644 index 00000000..036160fc --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandHandler.cs @@ -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; + +/// +/// Handler for the command to register a new user account. +/// +public class RegisterCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IHashService _hashService; + private readonly ICryptographyService _cryptographyService; + private readonly ITotpTokenGenerator _totpTokenGenerator; + private readonly IQRCodeGenerator _qRCodeGenerator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for password hashing functionality. + /// Injected service for cryptographic functionality. + /// Injected service for generating and validating TOTP tokens. + /// Injected service for generating QR codes. + 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> Handle(RegisterCommand request, CancellationToken cancellationToken) + { + // check if any users already exists (admin account is only set once!) + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr 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 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); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandValidator.cs new file mode 100644 index 00000000..ff61c94e --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandValidator.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Register; + +/// +/// Validates the needed validation rules for . +/// +public class RegisterCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + 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); + } +} diff --git a/src/Lumina.Contracts/Requests/Authentication/RegistrationRequest.cs b/src/Lumina.Contracts/Requests/Authentication/RegistrationRequest.cs new file mode 100644 index 00000000..f30762e4 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authentication/RegistrationRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authentication; + +/// +/// Represents the request model for user registration. +/// +/// The desired username for the new account. +/// The password for the new account. +/// The confirmation of the entered password, used to ensure consistency. +/// Indicates whether two-factor authentication (2FA) should be enabled for the new account. +[DebuggerDisplay("Username: {Username}")] +public record RegistrationRequest( + string? Username = null, + string? Password = null, + string? PasswordConfirm = null, + bool Use2fa = true +); diff --git a/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs b/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs new file mode 100644 index 00000000..46f1b394 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Authentication; + +/// +/// Represents the response model for user registration. +/// +/// The Id of the user. +/// The username of the user. +/// The TOTP (Time-Based One-Time Password) secret used for two-factor authentication. +[DebuggerDisplay("Username: {Username}")] +public record RegistrationResponse( + Guid Id, + string Username, + string? TotpSecret +); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpoint.cs new file mode 100644 index 00000000..59ab21f2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpoint.cs @@ -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; + +/// +/// API endpoint for the /account/register route. +/// +public class RegisterEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public RegisterEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Account.REGISTER_ACCOUNT); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Registers a new account. + /// + /// The request containing the account to be added. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken) + { + ErrorOr 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); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpointSummary.cs new file mode 100644 index 00000000..84aac3aa --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Register; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class RegisterEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs new file mode 100644 index 00000000..65c3c658 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the request model for user registration. +/// +/// The desired username for the new account. +/// The password for the new account. +/// The confirmation of the entered password, used to ensure consistency. +/// Specifies the type of registration, e.g., "Admin" or "User". +/// Indicates whether two-factor authentication (2FA) should be enabled for the new account. +[DebuggerDisplay("Username: {Username}")] +public record RegisterRequestModel( + string? Username = null, + string? Password = null, + string? PasswordConfirm = null, + string? RegistrationType = null, + bool Use2fa = true +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs new file mode 100644 index 00000000..7a43ba88 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the response model for a successful registration. +/// +/// The username of the registered user. +/// The TOTP (Time-Based One-Time Password) secret used for two-factor authentication. +[DebuggerDisplay("Username: {Username}")] +public record RegisterResponseModel( + string? Username, + string? TotpSecret +); diff --git a/src/Lumina.Presentation.Web/Views/Account/Register.cshtml b/src/Lumina.Presentation.Web/Views/Account/Register.cshtml new file mode 100644 index 00000000..c8a9c47a --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Account/Register.cshtml @@ -0,0 +1,134 @@ +@* +/account/register/ +*@ + +@using Lumina.Presentation.Web.Common.Models.UsersManagement + +@{ + string? registrationType = ViewData["RegistrationType"] as string; +} + +@model RegisterRequestModel + +
+
+
+ @Html.AntiForgeryToken() + + +
+ @if (registrationType == "Admin") + { +
+

Admin account registration

+
+ } + +
+
+ + *: +
+
+ +
+ DescriptionUsername +
+ +
+
+ + *: +
+
+ +
+ DescriptionPassword +
+ +
+
+ + *: +
+
+ +
+ DescriptionPasswordConfirm +
+ + +
+
+ +
+ Description2Fa +
+
+ +
+
+ +
+
+
+ +
+ + + + +
+
+@section Scripts { + +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/Fixture/RegisterCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/Fixture/RegisterCommandFixture.cs new file mode 100644 index 00000000..8119ea80 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/Fixture/RegisterCommandFixture.cs @@ -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; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterCommandFixture +{ + /// + /// Creates a random valid command for a new account registration. + /// + /// The created command. + public static RegisterCommand CreateRegisterCommand() + { + string password = "Abcd123$"; + return new Faker() + .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); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs new file mode 100644 index 00000000..7f710027 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterCommandValidatorTests +{ + private readonly RegisterCommandValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + public RegisterCommandValidatorTests() + { + _validator = new RegisterCommandValidator(); + } + + [Fact] + public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() + { + // Arrange + RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + command = command with { Username = null! }; + + // Act + TestValidationResult 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 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 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 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 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 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 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 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 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 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 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 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 result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + result.ShouldNotHaveValidationErrorFor(x => x.Password); + result.ShouldNotHaveValidationErrorFor(x => x.PasswordConfirm); + } +}