From bd97c2e8c1f3baa2efc6368695eebf6729cf059a Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sun, 10 Nov 2024 21:14:19 +0200 Subject: [PATCH 1/4] 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); + } +} From abc277735777785e9dba1a97d383bd357a2f708f Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 11 Nov 2024 15:13:59 +0200 Subject: [PATCH 2/4] Adds URL solving service based on action and controller names --- .../Common/Services/IUrlService.cs | 12 ++++++ .../Common/Services/UrlService.cs | 38 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/Lumina.Presentation.Web/Common/Services/IUrlService.cs create mode 100644 src/Lumina.Presentation.Web/Common/Services/UrlService.cs diff --git a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs new file mode 100644 index 00000000..f28f6696 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs @@ -0,0 +1,12 @@ +namespace Lumina.Presentation.Web.Common.Services; + +public interface IUrlService +{ + /// + /// Generates an absolute URL for the specified controller action. + /// + /// The action name within the controller. + /// The controller name. + /// An absolute URL to the specified action. + string? GetAbsoluteUrl(string action, string controller); +} diff --git a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs new file mode 100644 index 00000000..2f8ed3b5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +#endregion + +namespace Lumina.Presentation.Web.Common.Services; + +/// +/// Service for generating URLs from action and controller names. +/// +public class UrlService : IUrlService +{ + private readonly LinkGenerator _linkGenerator; + private readonly IHttpContextAccessor _httpContextAccessor; + + /// + /// Initializes a new instance of the class. + /// + /// The ASP.NET Core link generator service. + /// Provides access to the current HTTP context. + public UrlService(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor) + { + _linkGenerator = linkGenerator; + _httpContextAccessor = httpContextAccessor; + } + + /// + /// Generates an absolute URL for the specified controller action. + /// + /// The action name within the controller. + /// The controller name. + /// An absolute URL to the specified action. + public string? GetAbsoluteUrl(string action, string controller) + { + string? scheme = _httpContextAccessor.HttpContext?.Request.Scheme; + return _linkGenerator.GetUriByAction(_httpContextAccessor.HttpContext!, action: action, controller: controller, values: null, scheme: scheme); + } +} From 38829d64ff8280d8b17010a3db7a9b6d98444c6c Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 11 Nov 2024 15:19:50 +0200 Subject: [PATCH 3/4] Implements account login --- .../Entities/UsersManagement/UserEntity.cs | 2 +- .../Repositories/Users/IUserRepository.cs | 13 +- .../Common/Errors/Errors.Authentication.cs | 23 +++ .../Authentication/LoginRequestMapping.cs | 26 +++ .../Queries/LoginUser/LoginUserQuery.cs | 21 +++ .../LoginUser/LoginUserQueryHandler.cs | 82 +++++++++ .../LoginUser/LoginUserQueryValidator.cs | 33 ++++ .../Requests/Authentication/LoginRequest.cs | 18 ++ .../Responses/Authentication/LoginResponse.cs | 21 +++ .../Core/Repositories/Users/UserRepository.cs | 21 +++ .../ApiRoutes.Authentication.cs | 16 ++ .../Authentication/Login/LoginEndpoint.cs | 55 ++++++ .../PresentationWebLayerConfiguration.cs | 8 + .../PresentationWebLayerServices.cs | 21 ++- .../Configuration/EncryptionSettingsModel.cs | 19 ++ .../UsersManagement/LoginRequestModel.cs | 18 ++ .../UsersManagement/LoginResponseModel.cs | 21 +++ .../Common/Security/CryptographyService.cs | 102 +++++++++++ .../Common/Security/ICryptographyService.cs | 27 +++ .../EncryptionSettingsModelValidator.cs | 24 +++ .../UsersManagement/AuthController.cs | 170 ++++++++++++++++++ .../Views/Auth/Login.cshtml | 89 +++++++++ src/Lumina.Presentation.Web/appsettings.json | 3 + 23 files changed, 826 insertions(+), 7 deletions(-) create mode 100644 src/Lumina.Application/Common/Errors/Errors.Authentication.cs create mode 100644 src/Lumina.Application/Common/Mapping/Authentication/LoginRequestMapping.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidator.cs create mode 100644 src/Lumina.Contracts/Requests/Authentication/LoginRequest.cs create mode 100644 src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs create mode 100644 src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs create mode 100644 src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs create mode 100644 src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs create mode 100644 src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs create mode 100644 src/Lumina.Presentation.Web/Views/Auth/Login.cshtml diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs index e0160778..48927769 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs @@ -17,7 +17,7 @@ public class UserEntity : IStorageEntity /// /// Gets the Id of the user. /// - public required Guid Id { get; init; } + public Guid Id { get; init; } /// /// Gets or sets the username of the user. diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs index 537b96f9..36ce830e 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs @@ -1,7 +1,10 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using System.Threading; +using System.Threading.Tasks; #endregion namespace Lumina.Application.Common.DataAccess.Repositories.Users; @@ -10,6 +13,14 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Users; /// Interface for the repository for users. /// public interface IUserRepository : IRepository, + IGetAllRepositoryAction, IInsertRepositoryAction { + /// + /// Gets a username identified by from the repository, if it exists. + /// + /// The username of the user to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a if found, or an error. + Task> GetByUsernameAsync(string username, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/Errors/Errors.Authentication.cs b/src/Lumina.Application/Common/Errors/Errors.Authentication.cs new file mode 100644 index 00000000..78f3d3b4 --- /dev/null +++ b/src/Lumina.Application/Common/Errors/Errors.Authentication.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Application.Common.Errors; + +/// +/// Application authentication related error types. +/// +public static partial class Errors +{ + public static class Authentication + { + public static Error UsernameAlreadyExists => Error.Conflict(description: nameof(UsernameAlreadyExists)); + public static Error UsernameCannotBeEmpty => Error.Validation(description: nameof(UsernameCannotBeEmpty)); + public static Error PasswordCannotBeEmpty => Error.Validation(description: nameof(PasswordCannotBeEmpty)); + public static Error PasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(PasswordConfirmCannotBeEmpty)); + public static Error InvalidPassword => Error.Validation(description: nameof(InvalidPassword)); + public static Error PasswordsNotMatch => Error.Validation(description: nameof(PasswordsNotMatch)); + public static Error InvalidTotpCode => Error.Validation(description: nameof(InvalidTotpCode)); + public static Error InvalidUsernameOrPassword => Error.Failure(description: nameof(InvalidUsernameOrPassword)); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authentication/LoginRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/LoginRequestMapping.cs new file mode 100644 index 00000000..018488d0 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authentication/LoginRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Application.Common.Mapping.Authentication; + +/// +/// Extension methods for converting . +/// +public static class LoginRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static LoginUserQuery ToQuery(this LoginRequest request) + { + return new LoginUserQuery( + request.Username, + request.Password, + request.TotpCode + ); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs new file mode 100644 index 00000000..003e1fa1 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; + +/// +/// Query for authenticating an account. +/// +/// The username of the account to authenticate. +/// The password of the account to authenticate. +/// The TOTP (Time-Based One-Time Password) of the account to authenticate. +[DebuggerDisplay("Path: {Path}")] +public record LoginUserQuery( + string? Username, + string? Password, + string? TotpCode = null +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs new file mode 100644 index 00000000..97a7a40d --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -0,0 +1,82 @@ +#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.Authentication.Queries.LoginUser; + +/// +/// Handler for the query to authenticate an account. +/// +public class LoginUserQueryHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IHashService _hashService; + private readonly IJwtTokenGenerator _jwtTokenGenerator; + private readonly ITotpTokenGenerator _totpTokenGenerator; + private readonly ICryptographyService _cryptographyService; + + /// + /// 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 generating JWT tokens. + /// Injected service for generating and validating TOTP tokens. + /// Injected service for cryptographic functionality. + public LoginUserQueryHandler( + IUnitOfWork unitOfWork, + IHashService hashService, + IJwtTokenGenerator jwtTokenGenerator, + ITotpTokenGenerator totpTokenGenerator, + ICryptographyService cryptographyService) + { + _unitOfWork = unitOfWork; + _hashService = hashService; + _jwtTokenGenerator = jwtTokenGenerator; + _totpTokenGenerator = totpTokenGenerator; + _cryptographyService = cryptographyService; + } + + /// + /// Handles the query to authenticate an account. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(LoginUserQuery request, CancellationToken cancellationToken) + { + // check if any users already exists + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken); + if (resultSelectUser.IsError) + return resultSelectUser.Errors; + else if (resultSelectUser.Value is null) + return Errors.Authentication.InvalidUsernameOrPassword; + // validate the password is correct + if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!))) + return Errors.Authentication.InvalidUsernameOrPassword; + // create the JWT token + string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username); + // check if the user uses TOTP + bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret); + if (usesTotp && string.IsNullOrEmpty(request.TotpCode)) + return Errors.Authentication.InvalidTotpCode; + else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it + if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode)) + return Errors.Authentication.InvalidTotpCode; + return new LoginResponse(resultSelectUser.Value.Id, resultSelectUser.Value.Username, token, usesTotp); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidator.cs new file mode 100644 index 00000000..90e4e4de --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidator.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +using System.Linq; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; + +/// +/// Validates the needed validation rules for . +/// +public class LoginUserQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public LoginUserQueryValidator() + { + 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(m => m!.TotpCode) + .Custom((code, context) => + { + if (string.IsNullOrEmpty(code)) + return; + if (code.Length != 6) + context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description); + if (!code.All(char.IsDigit)) + context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description); + }); + } +} diff --git a/src/Lumina.Contracts/Requests/Authentication/LoginRequest.cs b/src/Lumina.Contracts/Requests/Authentication/LoginRequest.cs new file mode 100644 index 00000000..ac24be8b --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authentication/LoginRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authentication; + +/// +/// Represents the request model for user authentication. +/// +/// The username of the account to authenticate. +/// The password of the account to authenticate. +/// The TOTP (Time-Based One-Time Password) of the account to authenticate. +[DebuggerDisplay("Username: {Username}")] +public record LoginRequest( + string? Username, + string? Password, + string? TotpCode = null +); diff --git a/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs b/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs new file mode 100644 index 00000000..8fe6eef2 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Authentication; + +/// +/// Represents the response model for user authentication. +/// +/// The Id of the user to authenticate. +/// The username of the user to authenticate. +/// The authentication token used for subsequent requests. +/// Whether the user uses 2FA authentication, or not. +[DebuggerDisplay("Username: {Username}")] +public record LoginResponse( + Guid Id, + string Username, + string Token, + bool UsesTotp +); diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs index 77edf339..363219f7 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs @@ -7,6 +7,7 @@ using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; using System.Threading; using System.Threading.Tasks; +using System.Collections.Generic; #endregion namespace Lumina.DataAccess.Core.Repositories.Users; @@ -43,4 +44,24 @@ internal sealed class UserRepository : IUserRepository return Result.Created; } + /// + /// Gets all users. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) + { + return await _luminaDbContext.Users.ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets a username identified by from the repository, if it exists. + /// + /// The username of the user to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a if found, or an error. + public async Task> GetByUsernameAsync(string username, CancellationToken cancellationToken) + { + return await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == username, cancellationToken).ConfigureAwait(false); + } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs new file mode 100644 index 00000000..8c52e412 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs @@ -0,0 +1,16 @@ +namespace Lumina.Presentation.Api.Common.Routes.UsersManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Authentication route. + /// + public static class Authentication + { + public const string REGISTER_ACCOUNT = "/auth/register"; + public const string LOGIN_ACCOUNT = "/auth/login"; + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs new file mode 100644 index 00000000..dc9bc6da --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.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.Authentication.Login; + +/// +/// API endpoint for the /auth/login route. +/// +public class LoginEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public LoginEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Authentication.LOGIN_ACCOUNT); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Authenticates an account. + /// + /// The request containing the account to be authenticated. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(LoginRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs index a99da909..513b0223 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs @@ -1,7 +1,9 @@ +#region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Models.Configuration; using Lumina.Presentation.Web.Common.Utilities; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +#endregion namespace Lumina.Presentation.Web.Common.DependencyInjection; @@ -26,6 +28,12 @@ internal static class PresentationWebLayerConfiguration .Bind(configuration.GetRequiredSection(ServerConfigurationModel.SECTION_NAME)) .ValidateFluently() .ValidateOnStart(); + + serviceCollection.AddOptions() + .Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + return serviceCollection; } } diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index ea870dce..fb394a97 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -1,9 +1,13 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Filters; +using Lumina.Presentation.Web.Common.Security; +using Lumina.Presentation.Web.Common.Services; using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; @@ -34,7 +38,7 @@ public static class PresentationWebLayerServices public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services) { services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter))) - .AddJsonOptions(options => + .AddJsonOptions(options => { options.JsonSerializerOptions.MaxDepth = 256; options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures @@ -46,9 +50,9 @@ public static class PresentationWebLayerServices .AddCookie(options => { // basic path configuration - options.LoginPath = "/account/login"; - options.LogoutPath = "/account/logout"; - options.AccessDeniedPath = "/account/access-denied"; + options.LoginPath = "/auth/login"; + options.LogoutPath = "/auth/logout"; + options.AccessDeniedPath = "/auth/access-denied"; // Cookie configuration options.Cookie = new CookieBuilder @@ -67,7 +71,7 @@ public static class PresentationWebLayerServices // handle validation to support various deployment scenarios options.Events = new CookieAuthenticationEvents - { + { // handle redirects to work with different base paths OnRedirectToLogin = context => { @@ -81,6 +85,10 @@ public static class PresentationWebLayerServices }; }); + // add an authorization policy that ensures application is initialized with super admin account before allowing access + services.AddAuthorizationBuilder() + .AddPolicy("RequireInitialization", policy => policy.Requirements.Add(new InitializationRequirement())); + // add forwarded headers middleware to handle reverse proxy scenarios services.Configure(options => { @@ -126,6 +134,9 @@ public static class PresentationWebLayerServices services.AddHttpContextAccessor(); services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); return services; } diff --git a/src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs b/src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs new file mode 100644 index 00000000..7f8ebbbf --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Configuration; + +/// +/// Model for deserializing media settings. +/// +[DebuggerDisplay("{SECTION_NAME}")] +public class EncryptionSettingsModel +{ + public const string SECTION_NAME = "EncryptionSettings"; + + /// + /// Gets or sets the root directory where media files are stored. + /// + public required string SecretKey { get; init; } +} diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs new file mode 100644 index 00000000..d84581b9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the request model for user authentication. +/// +/// The username used to authenticate. +/// The password used to authenticate. +/// The TOTP (Time-Based One-Time Password) code used for two-factor authentication. +[DebuggerDisplay("Username: {Username}")] +public record LoginRequestModel( + string? Username = null, + string? Password = null, + string? TotpCode = null +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs new file mode 100644 index 00000000..a5662424 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the response model for a user authentication. +/// +/// The Id of the logged in user. +/// The username of the logged in user. +/// The JWT authentication token, if authentication failed or TOTP is required. +/// Indicates whether the user has Two-Factor Authentication enabled, or not. +[DebuggerDisplay("Username: {Username}")] +public record LoginResponseModel( + Guid Id, + string? Username, + string? Token, + bool UsesTotp +); diff --git a/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs b/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs new file mode 100644 index 00000000..b8480404 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Models.Configuration; +using Microsoft.Extensions.Options; +using System; +using System.Security.Cryptography; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.Common.Security; + +/// +/// Service for cryptographic concerns. +/// +public sealed class CryptographyService : ICryptographyService, IDisposable +{ + private readonly byte[] _key; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for retrieving . + public CryptographyService(IOptions encryptionSettingsModelOptions) + { + _key = Convert.FromBase64String(encryptionSettingsModelOptions.Value.SecretKey); + } + + /// + /// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV). + /// + /// The plaintext string to encrypt. + /// A Base64-encoded string of the combined IV and encrypted ciphertext. + /// Thrown when is or empty. + public string Encrypt(string plaintext) + { + if (string.IsNullOrEmpty(plaintext)) + throw new ArgumentException("Value cannot be null or empty", nameof(plaintext)); + + // generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts + byte[] iv = new byte[16]; + using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) + rng.GetBytes(iv); + + using Aes aes = Aes.Create(); + aes.Key = _key; + aes.IV = iv; + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + + using ICryptoTransform encryptor = aes.CreateEncryptor(); + byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); + byte[] ciphertext = encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length); + + // combine IV and ciphertext + byte[] combined = new byte[iv.Length + ciphertext.Length]; + Buffer.BlockCopy(iv, 0, combined, 0, iv.Length); + Buffer.BlockCopy(ciphertext, 0, combined, iv.Length, ciphertext.Length); + + return Convert.ToBase64String(combined); + } + + /// + /// Decrypts a Base64-encoded string that contains both the IV and ciphertext. + /// + /// The Base64-encoded string containing both IV and ciphertext. + /// The decrypted plaintext string. + /// Thrown when is , empty, or invalid. + public string Decrypt(string ciphertext) + { + if (string.IsNullOrEmpty(ciphertext)) + throw new ArgumentException("Value cannot be null or empty", nameof(ciphertext)); + + // decode the combined data (IV + ciphertext) from Base64 + byte[] combined = Convert.FromBase64String(ciphertext); + + if (combined.Length < 16) + throw new ArgumentException("Invalid ciphertext"); + + // extract IV and ciphertext + byte[] iv = new byte[16]; + byte[] encryptedData = new byte[combined.Length - 16]; + Buffer.BlockCopy(combined, 0, iv, 0, 16); + Buffer.BlockCopy(combined, 16, encryptedData, 0, encryptedData.Length); + + using Aes aes = Aes.Create(); + aes.Key = _key; + aes.IV = iv; + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + + using ICryptoTransform decryptor = aes.CreateDecryptor(); + byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length); + return Encoding.UTF8.GetString(decrypted); + } + + /// + /// Clears sensitive key data when the service is disposed. + /// + public void Dispose() + { + Array.Clear(_key, 0, _key.Length); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs b/src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs new file mode 100644 index 00000000..ecfdbccf --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Presentation.Web.Common.Security; + +/// +/// Interface for the service for cryptographic concerns. +/// +public interface ICryptographyService +{ + /// + /// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV). + /// + /// The plaintext string to encrypt. + /// A Base64-encoded string of the combined IV and encrypted ciphertext. + /// Thrown when is or empty. + string Encrypt(string plaintext); + + /// + /// Decrypts a Base64-encoded string that contains both the IV and ciphertext. + /// + /// The Base64-encoded string containing both IV and ciphertext. + /// The decrypted plaintext string. + /// Thrown when is , empty, or invalid. + string Decrypt(string ciphertext); +} diff --git a/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs b/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs new file mode 100644 index 00000000..b05311bc --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Presentation.Web.Common.Models.Configuration; +using System; +using System.Buffers.Text; +#endregion + +namespace Lumina.Presentation.Web.Common.Validators; + +/// +/// Validates the needed validation rules for the EncryptionSettings application configuration settings section. +/// +public class EncryptionSettingsModelValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public EncryptionSettingsModelValidator() + { + RuleFor(x => x.SecretKey) + .NotEmpty().WithMessage("Encryption secret key cannot be empty!") + .Must(value => Base64.IsValid(value.AsSpan())).WithMessage("Encryption secret key must be a base64 string!"); + } +} diff --git a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs new file mode 100644 index 00000000..af839ff7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs @@ -0,0 +1,170 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Filters; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Models.UsersManagement; +using Lumina.Presentation.Web.Common.Security; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Controllers.UsersManagement; + +/// +/// Controller for authentication related operations. +/// +[Authorize] +[Route("/auth/")] +public class AuthController : Controller +{ + private readonly IApiHttpClient _apiHttpClient; + private readonly ICryptographyService _cryptographyService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for cryptographic functionality. + public AuthController(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService) + { + _apiHttpClient = apiHttpClient; + _cryptographyService = cryptographyService; + } + + /// + /// Displays the view for registering a new account. + /// + [AllowAnonymous] + [InitializationCheck] + [HttpGet("register")] + public IActionResult Register() + { + // check if this is the initial super admin setup + string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); + ViewData["RegistrationType"] = isPendingSuperAdminSetup == "true" ? "Admin" : "User"; + return View(new RegisterRequestModel()); + } + + /// + /// Displays the view for logging in. + /// + /// The url to return to, after login (if any). + [AllowAnonymous] + [InitializationCheck] + [HttpGet("login/{returnUrl?}")] + public IActionResult Login(string? returnUrl = null) + { + ViewData["ReturnUrl"] = returnUrl; + // if the user is already logged in, redirect them to the home page + if (User?.Identity?.IsAuthenticated == true) + return RedirectToAction("Index", "Home"); + // check if the application is initialized (does contain at least the super user account); if it's not, redirect to registration view + string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); + if (isPendingSuperAdminSetup == "true") + // TODO: should be: + // return View("~/Views/Auth/Register", new RegisterRequestDto()); + // but doesn't work because of an ASP.NET bug: https://github.com/dotnet/AspNetCore.Docs/issues/25157 + return RedirectToAction("Register", "Auth"); + return View(new LoginRequestModel()); + } + + /// + /// Displays the view for recovering the password of an account. + /// + [AllowAnonymous] + [InitializationCheck] + [HttpGet("recover-password")] + public IActionResult RecoverPassword() + { + // if the user is already logged in, redirect them to the home page + if (User?.Identity?.IsAuthenticated == true) + return RedirectToAction("Index", "Home"); + return View(); + } + + /// + /// Displays the view for registering a new account. + /// + [InitializationCheck] + [HttpGet("profile")] + public IActionResult Profile() + { + return View(); + } + + /// + /// Registers a new account. + /// + /// User credentials used for registration. + [AllowAnonymous] + [ValidateAntiForgeryToken] + [HttpPost("register")] + public async Task Register([FromBody] RegisterRequestModel data) + { + // call different endpoints based on the view hidden field - registration for normal users, or initial application admin account setup + string endpoint = data.RegistrationType == "Admin" ? "initialization" : "auth/register"; + // attempt API registration + RegisterResponseModel response = await _apiHttpClient.PostAsync(endpoint, data); + return Json(new { success = true, data = response }); + } + + /// + /// Logs in an new account. + /// + /// User credentials used for login. + /// The url to return to, after login (if any). + [AllowAnonymous] + [ValidateAntiForgeryToken] + [HttpPost("login")] + public async Task Login([FromBody] LoginRequestModel data, string? returnUrl = null) + { + try + { + // attempt API registration + LoginResponseModel response = await _apiHttpClient.PostAsync("auth/login", data); + // store the received token in a secure cookie + Response.Cookies.Delete("Token"); + Response.Cookies.Append("Token", _cryptographyService.Encrypt(response.Token!), new CookieOptions + { + Expires = DateTimeOffset.UtcNow.AddMonths(1), + Path = "/", + HttpOnly = true, + Secure = true + }); + // tell asp.net we are logged in + List claims = + [ + new Claim(ClaimTypes.Name, response.Username!), + new Claim(ClaimTypes.NameIdentifier, response.Id.ToString()!), + new Claim("Token", response.Token!), + ]; + ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme); + await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); + // return success status and redirect URL + return Json(new { success = true, data = string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl) ? Url.Content("~/") : Url.Content(returnUrl) }); + } + catch (ApiException ex) + { + // in this particular case, we DO NOT want to let the ApiExceptionFilter take care of this exception, because when the user has 2FA enabled, the first auth step involves sending + // only the username and password, in which case the server API will respond with a validation error, that TOTP code is not valid (empty); it is then that we catch this error here + // and display the form that asks the user for the TOTP code + if (ex.ProblemDetails is not null && ex.ProblemDetails.Extensions?.Count > 0 && ex.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj)) + if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object) + foreach (JsonProperty error in jsonElement.EnumerateObject()) + if (error.Value.ValueKind == JsonValueKind.Array) + foreach (JsonElement errorValue in error.Value.EnumerateArray()) + if (errorValue.ValueKind == JsonValueKind.String && errorValue.GetString() == "InvalidTotpCode" && string.IsNullOrEmpty(data.TotpCode)) + return Json(new { success = true, data = new { isTotpRequired = true } }); // only get here when user did not enter a TOTP code at all, otherwise rethrow the validation error + throw; + } + } +} diff --git a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml new file mode 100644 index 00000000..27db4172 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml @@ -0,0 +1,89 @@ +@* +/auth/login/ +*@ + +@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Services + +@inject IUrlService _urlService + +@model LoginRequestModel + +
+
+
+ @Html.AntiForgeryToken() + +
+ +
+
+ : +
+
+ +
+
+ +
+
+ : +
+
+ +
+
+
+ + +
+ + +
+ +
+
+
+
+@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/appsettings.json b/src/Lumina.Presentation.Web/appsettings.json index 0254b2b9..fa4a93cd 100644 --- a/src/Lumina.Presentation.Web/appsettings.json +++ b/src/Lumina.Presentation.Web/appsettings.json @@ -1,4 +1,7 @@ { + "EncryptionSettings": { + "SecretKey": "" // base64 string + }, "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], "MinimumLevel": { From a6dcf65d1c7b9ed45af8e5523513d4f9e720d925 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 11 Nov 2024 22:57:33 +0200 Subject: [PATCH 4/4] Implements authentication system --- .../Entities/UsersManagement/UserEntity.cs | 10 + .../Repositories/Users/IUserRepository.cs | 3 +- .../Common/Errors/Errors.Authentication.cs | 8 + .../Common/Errors/Errors.Authorization.cs | 16 + .../Authentication/IJwtTokenGenerator.cs | 15 + .../Authentication/IQRCodeGenerator.cs | 15 + .../Authentication/ITokenGenerator.cs | 13 + .../Authentication/ITotpTokenGenerator.cs | 21 + .../{ => Security}/ICryptographyService.cs | 2 +- .../{ => Security}/IHashService.cs | 2 +- .../Infrastructure/Time/IDateTimeProvider.cs | 16 + .../ChangePasswordRequestMapping.cs | 27 ++ .../RecoverPasswordRequestMapping.cs | 25 + .../RegistrationRequestMapping.cs | 8 +- .../Commands/SetupApplicationCommand.cs | 21 + .../SetupApplicationCommandHandler.cs | 99 ++++ .../SetupApplicationCommandValidator.cs | 24 + .../Queries/CheckInitializationQuery.cs | 11 + .../CheckInitializationQueryHandler.cs | 47 ++ .../ChangePassword/ChangePasswordCommand.cs | 21 + .../ChangePasswordCommandHandler.cs | 68 +++ .../ChangePasswordCommandValidator.cs | 26 + .../RecoverPassword/RecoverPasswordCommand.cs | 19 + .../RecoverPasswordCommandHandler.cs | 85 ++++ .../RecoverPasswordCommandValidator.cs | 23 + .../RegisterUser/RegisterUserCommand.cs} | 4 +- .../RegisterUserCommandHandler.cs} | 10 +- .../RegisterUserCommandValidator.cs} | 10 +- .../LoginUser/LoginUserQueryHandler.cs | 25 +- .../Authentication/ChangePasswordRequest.cs | 15 + .../Authentication/RecoverPasswordRequest.cs | 16 + .../Authentication/ChangePasswordResponse.cs | 14 + .../Authentication/RecoverPasswordResponse.cs | 14 + .../UsersManagement/InitializationResponse.cs | 14 + .../Common/Configuration/UserConfiguration.cs | 12 +- ...421_AddUsersTempPasswordColumn.Designer.cs | 449 ++++++++++++++++++ ...241111183421_AddUsersTempPasswordColumn.cs | 106 +++++ .../LuminaDbContextModelSnapshot.cs | 14 +- .../Core/Repositories/Users/UserRepository.cs | 15 + .../Common/Errors/Errors.Users.cs | 1 + .../InfrastructureLayerServices.cs | 12 +- .../Core/Authentication/JwtTokenGenerator.cs | 57 +++ .../Core/Authentication/QRCodeGenerator.cs | 38 ++ .../Core/Authentication/TokenGenerator.cs | 27 ++ .../Core/Authentication/TotpTokenGenerator.cs | 34 ++ .../Core/Security/CryptographyService.cs | 2 +- .../Core/Security/HashService.cs | 2 +- .../Core/Time/DateTimeProvider.cs | 17 + .../Lumina.Infrastructure.csproj | 3 + .../PresentationApiLayerServices.cs | 81 +++- .../Common/Http/HttpContextItemKeys.cs | 4 +- .../Routes/Maintenance/ApiRoutes.Health.cs | 2 +- .../Maintenance/ApiRoutes.Initialization.cs | 16 + .../ApiRoutes.Authentication.cs | 2 + .../Routes/UsersManagement/ApiRoutes.Users.cs | 15 + .../Core/Endpoints/Common/BaseEndpoint.cs | 8 +- .../CheckInitializationEndpoint.cs | 52 ++ .../CheckInitializationEndpointSummary.cs | 23 + .../SetupApplicationEndpoint.cs | 55 +++ .../SetupApplicationEndpointSummary.cs | 29 ++ .../Maintenance/CheckHealthEndpoint.cs | 2 +- .../ChangePassword/ChangePasswordEndpoint.cs | 54 +++ .../ChangePasswordEndpointSummary.cs | 28 ++ .../Authentication/Login/LoginEndpoint.cs | 5 + .../Login/LoginEndpointSummary.cs | 28 ++ .../RecoverPasswordEndpoint.cs | 57 +++ .../RecoverPasswordEndpointSummary.cs | 27 ++ .../Register/RegisterEndpoint.cs | 6 +- .../Register/RegisterEndpointSummary.cs | 2 +- .../Lumina.Presentation.Api.csproj | 3 +- src/Lumina.Presentation.Api/Program.cs | 7 +- .../Properties/launchSettings.json | 10 - .../Common/Api/ApiHttpClient.cs | 68 ++- .../Common/Api/IApiHttpClient.cs | 22 +- .../Authorization/InitializationHandler.cs | 51 ++ .../InitializationRequirement.cs | 25 + .../Common/Filters/ApiExceptionFilter.cs | 2 +- .../Filters/InitializationCheckAttribute.cs | 26 + .../Common/Http/HttpContextItemKeys.cs | 10 + .../MediaContributorModel.cs | 3 +- .../Common/Models/UI/ComboboxItem.cs | 28 -- .../ChangePasswordRequestModel.cs | 15 + .../ChangePasswordResponseModel.cs | 14 + .../UsersManagement/InitializationModel.cs | 17 + .../RecoverPasswordRequestModel.cs | 16 + .../RecoverPasswordResponseModel.cs | 14 + .../UsersManagement/RegisterRequestModel.cs | 8 +- .../BookLibrary/AddBookRequest.cs | 100 ---- .../UsersManagement/AuthController.cs | 54 ++- .../Properties/launchSettings.json | 48 +- .../Views/Auth/ChangePassword.cshtml | 91 ++++ .../Views/Auth/Login.cshtml | 22 +- .../Views/Auth/RecoverPassword.cshtml | 84 ++++ .../Views/{Account => Auth}/Register.cshtml | 35 +- .../FileSystemBrowser/Default.cshtml | 1 - .../Views/Shared/_Layout.cshtml | 72 +-- .../Views/Shared/_NavMenu.cshtml | 188 +++++--- .../wwwroot/js/site.js | 32 +- .../SetupApplicationCommandFixture.cs | 33 ++ .../SetupApplicationCommandValidatorTests.cs | 233 +++++++++ .../Fixture/RegisterCommandFixture.cs | 10 +- .../Register/RegisterCommandValidatorTests.cs | 60 +-- .../Repositories/Books/BookRepositoryTests.cs | 3 +- 103 files changed, 2983 insertions(+), 454 deletions(-) create mode 100644 src/Lumina.Application/Common/Errors/Errors.Authorization.cs create mode 100644 src/Lumina.Application/Common/Infrastructure/Authentication/IJwtTokenGenerator.cs create mode 100644 src/Lumina.Application/Common/Infrastructure/Authentication/IQRCodeGenerator.cs create mode 100644 src/Lumina.Application/Common/Infrastructure/Authentication/ITokenGenerator.cs create mode 100644 src/Lumina.Application/Common/Infrastructure/Authentication/ITotpTokenGenerator.cs rename src/Lumina.Application/Common/Infrastructure/{ => Security}/ICryptographyService.cs (95%) rename src/Lumina.Application/Common/Infrastructure/{ => Security}/IHashService.cs (93%) create mode 100644 src/Lumina.Application/Common/Infrastructure/Time/IDateTimeProvider.cs create mode 100644 src/Lumina.Application/Common/Mapping/Authentication/ChangePasswordRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Authentication/RecoverPasswordRequestMapping.cs create mode 100644 src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommand.cs create mode 100644 src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQuery.cs create mode 100644 src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQueryHandler.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidator.cs rename src/Lumina.Application/Core/UsersManagement/{Register/RegisterCommand.cs => Authentication/Commands/RegisterUser/RegisterUserCommand.cs} (86%) rename src/Lumina.Application/Core/UsersManagement/{Register/RegisterCommandHandler.cs => Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs} (91%) rename src/Lumina.Application/Core/UsersManagement/{Register/RegisterCommandValidator.cs => Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs} (75%) create mode 100644 src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Authentication/RecoverPasswordRequest.cs create mode 100644 src/Lumina.Contracts/Responses/Authentication/ChangePasswordResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Authentication/RecoverPasswordResponse.cs create mode 100644 src/Lumina.Contracts/Responses/UsersManagement/InitializationResponse.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.cs create mode 100644 src/Lumina.Infrastructure/Core/Authentication/JwtTokenGenerator.cs create mode 100644 src/Lumina.Infrastructure/Core/Authentication/QRCodeGenerator.cs create mode 100644 src/Lumina.Infrastructure/Core/Authentication/TokenGenerator.cs create mode 100644 src/Lumina.Infrastructure/Core/Authentication/TotpTokenGenerator.cs create mode 100644 src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Initialization.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs rename src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/{ => Authentication}/Register/RegisterEndpoint.cs (93%) rename src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/{ => Authentication}/Register/RegisterEndpointSummary.cs (98%) create mode 100644 src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs create mode 100644 src/Lumina.Presentation.Web/Common/Authorization/InitializationRequirement.cs create mode 100644 src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs create mode 100644 src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs delete mode 100644 src/Lumina.Presentation.Web/Common/Models/UI/ComboboxItem.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs delete mode 100644 src/Lumina.Presentation.Web/Common/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs create mode 100644 src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml create mode 100644 src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml rename src/Lumina.Presentation.Web/Views/{Account => Auth}/Register.cshtml (78%) create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/Fixtures/SetupApplicationCommandFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidatorTests.cs diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs index 48927769..99629352 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs @@ -29,6 +29,11 @@ public class UserEntity : IStorageEntity /// public required string Password { get; set; } + /// + /// Gets or sets the temporary hashed password used in password recovery. + /// + public string? TempPassword { get; set; } + /// /// Gets or sets the optional Time-based One-Time Password (TOTP) secret for two-factor authentication. /// @@ -44,6 +49,11 @@ public class UserEntity : IStorageEntity /// public DateTime? VerificationTokenCreated { get; set; } + /// + /// Gets or sets the date and time when the temporary password used in password recovery was created. + /// + public DateTime? TempPasswordCreated { get; set; } + /// /// Gets the collection of libraries owned by this user. /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs index 36ce830e..f45bf2fd 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs @@ -14,7 +14,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Users; /// public interface IUserRepository : IRepository, IGetAllRepositoryAction, - IInsertRepositoryAction + IInsertRepositoryAction, + IUpdateRepositoryAction { /// /// Gets a username identified by from the repository, if it exists. diff --git a/src/Lumina.Application/Common/Errors/Errors.Authentication.cs b/src/Lumina.Application/Common/Errors/Errors.Authentication.cs index 78f3d3b4..c8440c8c 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Authentication.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Authentication.cs @@ -12,12 +12,20 @@ public static partial class Errors public static class Authentication { public static Error UsernameAlreadyExists => Error.Conflict(description: nameof(UsernameAlreadyExists)); + public static Error UsernameDoesNotExist => Error.NotFound(description: nameof(UsernameDoesNotExist)); public static Error UsernameCannotBeEmpty => Error.Validation(description: nameof(UsernameCannotBeEmpty)); + public static Error TotpCannotBeEmpty => Error.Validation(description: nameof(TotpCannotBeEmpty)); public static Error PasswordCannotBeEmpty => Error.Validation(description: nameof(PasswordCannotBeEmpty)); + public static Error NewPasswordCannotBeEmpty => Error.Validation(description: nameof(NewPasswordCannotBeEmpty)); + public static Error CurrentPasswordCannotBeEmpty => Error.Validation(description: nameof(CurrentPasswordCannotBeEmpty)); public static Error PasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(PasswordConfirmCannotBeEmpty)); + public static Error NewPasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(NewPasswordConfirmCannotBeEmpty)); public static Error InvalidPassword => Error.Validation(description: nameof(InvalidPassword)); public static Error PasswordsNotMatch => Error.Validation(description: nameof(PasswordsNotMatch)); public static Error InvalidTotpCode => Error.Validation(description: nameof(InvalidTotpCode)); public static Error InvalidUsernameOrPassword => Error.Failure(description: nameof(InvalidUsernameOrPassword)); + public static Error InvalidCurrentPassword => Error.Failure(description: nameof(InvalidCurrentPassword)); + public static Error TempPasswordExpired => Error.Failure(description: nameof(TempPasswordExpired)); + public static Error PasswordResetAlreadyRequested => Error.Failure(description: nameof(PasswordResetAlreadyRequested)); } } diff --git a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs new file mode 100644 index 00000000..842f394f --- /dev/null +++ b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Application.Common.Errors; + +/// +/// Application authorization related error types. +/// +public static partial class Errors +{ + public static class Authorization + { + public static Error AdminAccountAlreadyCreated => Error.Unauthorized(description: nameof(AdminAccountAlreadyCreated)); + } +} diff --git a/src/Lumina.Application/Common/Infrastructure/Authentication/IJwtTokenGenerator.cs b/src/Lumina.Application/Common/Infrastructure/Authentication/IJwtTokenGenerator.cs new file mode 100644 index 00000000..92bad1d3 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authentication/IJwtTokenGenerator.cs @@ -0,0 +1,15 @@ +namespace Lumina.Application.Common.Infrastructure.Authentication; + +/// +/// Interface for generating JWT tokens. +/// +public interface IJwtTokenGenerator +{ + /// + /// Generates a new JWT token. + /// + /// The id of the user for which to generate the token. + /// The username for which to generate the token. + /// The generated JWT token. + string GenerateToken(string id, string username); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Authentication/IQRCodeGenerator.cs b/src/Lumina.Application/Common/Infrastructure/Authentication/IQRCodeGenerator.cs new file mode 100644 index 00000000..43b3f53c --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authentication/IQRCodeGenerator.cs @@ -0,0 +1,15 @@ +namespace Lumina.Application.Common.Infrastructure.Authentication; + +/// +/// Interface for the service for generating QR codes for TOTP. +/// +public interface IQRCodeGenerator +{ + /// + /// Generates a QR code Data URI for the specified TOTP secret. + /// + /// User's username or unique identifier. + /// The TOTP secret for which the QR code should be generated. + /// Data URI for the QR code. + string GenerateQrCodeDataUri(string username, byte[] secret); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Authentication/ITokenGenerator.cs b/src/Lumina.Application/Common/Infrastructure/Authentication/ITokenGenerator.cs new file mode 100644 index 00000000..2ba0f687 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authentication/ITokenGenerator.cs @@ -0,0 +1,13 @@ +namespace Lumina.Application.Common.Infrastructure.Authentication; + +/// +/// Interface for the service for generating secure tokens for accounts confirmation or recovery. +/// +public interface ITokenGenerator +{ + /// + /// Generates a secure token. + /// + /// A secure token. + string GenerateToken(); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Authentication/ITotpTokenGenerator.cs b/src/Lumina.Application/Common/Infrastructure/Authentication/ITotpTokenGenerator.cs new file mode 100644 index 00000000..7f369c12 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authentication/ITotpTokenGenerator.cs @@ -0,0 +1,21 @@ +namespace Lumina.Application.Common.Infrastructure.Authentication; + +/// +/// Interface for the service for generating and validating TOTP tokens. +/// +public interface ITotpTokenGenerator +{ + /// + /// Generates a new TOTP secret for a user. + /// + /// The generated TOTP secret. + byte[] GenerateSecret(); + + /// + /// Validates a TOTP token against the stored secret. + /// + /// The user's TOTP secret. + /// The token to validate. + /// if valid, otherwise. + bool ValidateToken(byte[] secret, string token); +} diff --git a/src/Lumina.Application/Common/Infrastructure/ICryptographyService.cs b/src/Lumina.Application/Common/Infrastructure/Security/ICryptographyService.cs similarity index 95% rename from src/Lumina.Application/Common/Infrastructure/ICryptographyService.cs rename to src/Lumina.Application/Common/Infrastructure/Security/ICryptographyService.cs index 197ee8c9..af3a41c8 100644 --- a/src/Lumina.Application/Common/Infrastructure/ICryptographyService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Security/ICryptographyService.cs @@ -2,7 +2,7 @@ using System; #endregion -namespace Lumina.Application.Common.Infrastructure; +namespace Lumina.Application.Common.Infrastructure.Security; /// /// Interface for the service for cryptographic concerns. diff --git a/src/Lumina.Application/Common/Infrastructure/IHashService.cs b/src/Lumina.Application/Common/Infrastructure/Security/IHashService.cs similarity index 93% rename from src/Lumina.Application/Common/Infrastructure/IHashService.cs rename to src/Lumina.Application/Common/Infrastructure/Security/IHashService.cs index 8acbc1f3..77395c85 100644 --- a/src/Lumina.Application/Common/Infrastructure/IHashService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Security/IHashService.cs @@ -1,4 +1,4 @@ -namespace Lumina.Application.Common.Infrastructure; +namespace Lumina.Application.Common.Infrastructure.Security; /// /// Interface for the service for hashing passwords. diff --git a/src/Lumina.Application/Common/Infrastructure/Time/IDateTimeProvider.cs b/src/Lumina.Application/Common/Infrastructure/Time/IDateTimeProvider.cs new file mode 100644 index 00000000..407b41d8 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Time/IDateTimeProvider.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Time; + +/// +/// Interface for time related concerns. +/// +public interface IDateTimeProvider +{ + /// + /// The current UTC time. + /// + DateTime UtcNow { get; } +} diff --git a/src/Lumina.Application/Common/Mapping/Authentication/ChangePasswordRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/ChangePasswordRequestMapping.cs new file mode 100644 index 00000000..382a96a7 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authentication/ChangePasswordRequestMapping.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Application.Common.Mapping.Authentication; + +/// +/// Extension methods for converting . +/// +public static class ChangePasswordRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static ChangePasswordCommand ToCommand(this ChangePasswordRequest request) + { + return new ChangePasswordCommand( + request.Username, + request.CurrentPassword, + request.NewPassword, + request.NewPasswordConfirm + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authentication/RecoverPasswordRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/RecoverPasswordRequestMapping.cs new file mode 100644 index 00000000..24d58a75 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authentication/RecoverPasswordRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Application.Common.Mapping.Authentication; + +/// +/// Extension methods for converting . +/// +public static class RecoverPasswordRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static RecoverPasswordCommand ToCommand(this RecoverPasswordRequest request) + { + return new RecoverPasswordCommand( + request.Username, + request.TotpCode + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs index aedd1c67..9cef13b5 100644 --- a/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; -using Lumina.Application.Core.UsersManagement.Register; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Contracts.Requests.Authentication; #endregion @@ -27,13 +27,13 @@ public static class RegistrationRequestMapping } /// - /// Converts to . + /// Converts to . /// /// The request to be converted. /// The converted command. - public static RegisterCommand ToCommand(this RegistrationRequest request) + public static RegisterUserCommand ToCommand(this RegistrationRequest request) { - return new RegisterCommand( + return new RegisterUserCommand( request.Username, request.Password, request.PasswordConfirm, diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommand.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommand.cs new file mode 100644 index 00000000..b31989d5 --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; + +/// +/// Command for the initial application setup. +/// +/// The username for the Admin account. +/// The password for the Admin account. +/// Confirmation of the password. +/// Indicates whether to enable two-factor authentication for the Admin account. +public record SetupApplicationCommand( + string? Username, + string? Password, + string? PasswordConfirm, + bool Use2fa +) : IRequest>; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandHandler.cs new file mode 100644 index 00000000..64e2688e --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandHandler.cs @@ -0,0 +1,99 @@ +#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.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; + +/// +/// Handler for the command to perform the initial application setup. +/// +public class SetupApplicationCommandHandler : 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 SetupApplicationCommandHandler( + IUnitOfWork unitOfWork, + IHashService hashService, + ICryptographyService cryptographyService, + ITotpTokenGenerator totpTokenGenerator, + IQRCodeGenerator qRCodeGenerator) + { + _unitOfWork = unitOfWork; + _hashService = hashService; + _cryptographyService = cryptographyService; + _totpTokenGenerator = totpTokenGenerator; + _qRCodeGenerator = qRCodeGenerator; + } + + /// + /// Handles the command to perform the initial application setup. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(SetupApplicationCommand request, CancellationToken cancellationToken) + { + // check if any users already exists (admin account is only set once!) + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr> resultSelectUser = await userRepository.GetAllAsync(cancellationToken); + if (resultSelectUser.IsError) + return resultSelectUser.Errors; + else if (resultSelectUser.Value.Any()) + return Errors.Authorization.AdminAccountAlreadyCreated; + // no users are present, register the admin one + 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/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidator.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidator.cs new file mode 100644 index 00000000..d1def565 --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidator.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; + +/// +/// Validates the needed validation rules for . +/// +public class SetupApplicationCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public SetupApplicationCommandValidator() + { + 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.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQuery.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQuery.cs new file mode 100644 index 00000000..d2ef6026 --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQuery.cs @@ -0,0 +1,11 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.UsersManagement; +using Mediator; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries; + +/// +/// Query for checking the initialization of the application. +/// +public record CheckInitializationQuery() : IRequest; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQueryHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQueryHandler.cs new file mode 100644 index 00000000..01b554d6 --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQueryHandler.cs @@ -0,0 +1,47 @@ +#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.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Contracts.Responses.UsersManagement; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Mediator; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries; + +/// +/// Handler for the query to check the initialization of the application. +/// +public class CheckInitializationQueryHandler : IRequestHandler +{ + private readonly IUnitOfWork _unitOfWork; + + public CheckInitializationQueryHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Checks the initialization status of the application. + /// + /// The query containing the request. + /// Cancellation token that can be used to stop the execution. + /// + /// if the application is initialized (the admin account is created), otherwise. + /// + public async ValueTask Handle(CheckInitializationQuery request, CancellationToken cancellationToken) + { + IUserRepository userRepository = _unitOfWork.GetRepository(); + // if the repository reports an error, or there are no users, the application has not been initialized + ErrorOr> resultSelectUser = await userRepository.GetAllAsync(cancellationToken); + if (!resultSelectUser.IsError) + return new InitializationResponse(resultSelectUser.Value.Any()); + return new InitializationResponse(false); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs new file mode 100644 index 00000000..5bc40ef0 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Represents the request model for account password change. +/// +/// The username of the account for which to change the password. +/// The current password of the account for which to change the password. +/// The new password of the account for which to change the password. +/// The confirmation of the new password of the account for which to change the password. +public record ChangePasswordCommand( + string? Username, + string? CurrentPassword, + string? NewPassword, + string? NewPasswordConfirm +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs new file mode 100644 index 00000000..79cd59df --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs @@ -0,0 +1,68 @@ +#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.Security; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Handler for the command to change the password of a user account. +/// +public class ChangePasswordCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IHashService _hashService; + + /// + /// 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. + public ChangePasswordCommandHandler( + IUnitOfWork unitOfWork, + IHashService hashService) + { + _unitOfWork = unitOfWork; + _hashService = hashService; + } + + /// + /// Handles the command to change the password of an account. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(ChangePasswordCommand request, CancellationToken cancellationToken) + { + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken); + if (resultSelectUser.IsError) + return resultSelectUser.Errors; + else if (resultSelectUser.Value is null) + return Errors.Authentication.UsernameDoesNotExist; + // validate if the current password is correct + if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(resultSelectUser.Value.Password!))) + return Errors.Authentication.InvalidCurrentPassword; + resultSelectUser.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!)); + // if the password change was initiated via a password reset, remote the temporary password that was generated in the process + resultSelectUser.Value.TempPassword = null; + resultSelectUser.Value.TempPasswordCreated = null; + // update the user + ErrorOr resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken); + if (resultUpdateUser.IsError) + return resultUpdateUser.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return new ChangePasswordResponse(true); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs new file mode 100644 index 00000000..a1168e39 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Validates the needed validation rules for . +/// +public class ChangePasswordCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordCommandValidator() + { + RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + RuleFor(x => x.CurrentPassword).NotEmpty().WithMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); + RuleFor(x => x.NewPassword).NotEmpty().WithMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); + RuleFor(x => x.NewPasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + RuleFor(x => x.NewPassword).Equal(x => x.NewPasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs new file mode 100644 index 00000000..a4854a4e --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Represents the request model for account password recovery. +/// +/// The username of the account for which to recover the password. +/// The TOTP (Time-Based One-Time Password) of the account for which to recover the password. +[DebuggerDisplay("Username: {Username}")] +public record class RecoverPasswordCommand( + string? Username, + string? TotpCode +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs new file mode 100644 index 00000000..6030c904 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs @@ -0,0 +1,85 @@ +#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.Authentication.Commands.RecoverPassword; + +/// +/// Handler for the command to recover the password of an account. +/// +public class RecoverPasswordCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IHashService _hashService; + private readonly ITotpTokenGenerator _totpTokenGenerator; + private readonly ICryptographyService _cryptographyService; + + /// + /// 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 generating and validating TOTP tokens. + /// Injected service for cryptographic functionality. + public RecoverPasswordCommandHandler( + IUnitOfWork unitOfWork, + IHashService hashService, + ITotpTokenGenerator totpTokenGenerator, + ICryptographyService cryptographyService) + { + _unitOfWork = unitOfWork; + _hashService = hashService; + _totpTokenGenerator = totpTokenGenerator; + _cryptographyService = cryptographyService; + } + + /// + /// Handles the command to recover the password of an account. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(RecoverPasswordCommand request, CancellationToken cancellationToken) + { + // check if any users already exists + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken); + if (resultSelectUser.IsError) + return resultSelectUser.Errors; + else if (resultSelectUser.Value is null) + return Errors.Authentication.UsernameDoesNotExist; + else if (resultSelectUser.Value.TempPassword is not null) // if a temp password is present, a password request was already requested + return Errors.Authentication.PasswordResetAlreadyRequested; + // check if the user uses TOTP + bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret); + if (!usesTotp) + return Errors.Authentication.InvalidTotpCode; + if (usesTotp && string.IsNullOrEmpty(request.TotpCode)) + return Errors.Authentication.InvalidTotpCode; + else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it + if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode)) + return Errors.Authentication.InvalidTotpCode; + // hash the new password and assign it to a temporary password that will be valid 15 minutes + resultSelectUser.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator + resultSelectUser.Value.TempPasswordCreated = DateTime.UtcNow; + // update the user + ErrorOr resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken); + if (resultUpdateUser.IsError) + return resultUpdateUser.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return new RecoverPasswordResponse(true); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidator.cs new file mode 100644 index 00000000..cb82c95e --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Validates the needed validation rules for . +/// +public class RecoverPasswordCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordCommandValidator() + { + RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + RuleFor(x => x.TotpCode).NotEmpty().WithMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + RuleFor(x => x.TotpCode).Length(6).WithMessage(Errors.Authentication.InvalidTotpCode.Description); + RuleFor(x => x.TotpCode).Matches(@"^[0-9]{6}$").WithMessage(Errors.Authentication.InvalidTotpCode.Description); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs similarity index 86% rename from src/Lumina.Application/Core/UsersManagement/Register/RegisterCommand.cs rename to src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs index ac923602..d9e29c05 100644 --- a/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs @@ -4,7 +4,7 @@ using Lumina.Contracts.Responses.Authentication; using Mediator; #endregion -namespace Lumina.Application.Core.UsersManagement.Register; +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; /// /// Command for registering a new account. @@ -13,7 +13,7 @@ namespace Lumina.Application.Core.UsersManagement.Register; /// The password for the new account. /// Confirmation of the password. /// Indicates whether to enable two-factor authentication for the new account. -public record RegisterCommand( +public record RegisterUserCommand( string? Username, string? Password, string? PasswordConfirm, diff --git a/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs similarity index 91% rename from src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandHandler.cs rename to src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index 036160fc..af17ae55 100644 --- a/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -13,12 +13,12 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.UsersManagement.Register; +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; /// /// Handler for the command to register a new user account. /// -public class RegisterCommandHandler : IRequestHandler> +public class RegisterUserCommandHandler : IRequestHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IHashService _hashService; @@ -27,14 +27,14 @@ public class RegisterCommandHandler : IRequestHandler - /// Initializes a new instance of the class. + /// 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( + public RegisterUserCommandHandler( IUnitOfWork unitOfWork, IHashService hashService, ICryptographyService cryptographyService, @@ -48,7 +48,7 @@ public class RegisterCommandHandler : IRequestHandler> Handle(RegisterCommand request, CancellationToken cancellationToken) + public async ValueTask> Handle(RegisterUserCommand request, CancellationToken cancellationToken) { // check if any users already exists (admin account is only set once!) IUserRepository userRepository = _unitOfWork.GetRepository(); diff --git a/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs similarity index 75% rename from src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandValidator.cs rename to src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs index ff61c94e..527f8fbc 100644 --- a/src/Lumina.Application/Core/UsersManagement/Register/RegisterCommandValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs @@ -3,17 +3,17 @@ using FluentValidation; using Lumina.Application.Common.Errors; #endregion -namespace Lumina.Application.Core.UsersManagement.Register; +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; /// -/// Validates the needed validation rules for . +/// Validates the needed validation rules for . /// -public class RegisterCommandValidator : AbstractValidator +public class RegisterUserCommandValidator : AbstractValidator { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public RegisterCommandValidator() + public RegisterUserCommandValidator() { RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description) diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs index 97a7a40d..7f05d206 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -65,9 +65,30 @@ public class LoginUserQueryHandler : IRequestHandler DateTime.UtcNow) + { + resultSelectUser.Value.TempPassword = null; + resultSelectUser.Value.TempPasswordCreated = null; + await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken); + await _unitOfWork.SaveChangesAsync(cancellationToken); + return Errors.Authentication.TempPasswordExpired; + } + else // temporary password is still valid, validate password against it + { + if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.TempPassword!))) + return Errors.Authentication.InvalidUsernameOrPassword; + } + } + else + return Errors.Authentication.InvalidUsernameOrPassword; + } // create the JWT token string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username); // check if the user uses TOTP diff --git a/src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs b/src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs new file mode 100644 index 00000000..899092c8 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs @@ -0,0 +1,15 @@ +namespace Lumina.Contracts.Requests.Authentication; + +/// +/// Represents the request model for account password change. +/// +/// The username of the account. +/// The current password of the account. +/// The new password of the account. +/// The confirmation of the new password of the account. +public record ChangePasswordRequest( + string? Username, + string? CurrentPassword, + string? NewPassword, + string? NewPasswordConfirm +); diff --git a/src/Lumina.Contracts/Requests/Authentication/RecoverPasswordRequest.cs b/src/Lumina.Contracts/Requests/Authentication/RecoverPasswordRequest.cs new file mode 100644 index 00000000..be02df67 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authentication/RecoverPasswordRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authentication; + +/// +/// Represents the request model for account password recovery. +/// +/// The username of the account for which to recover the password. +/// The TOTP (Time-Based One-Time Password) of the account for which to recover the password. +[DebuggerDisplay("Username: {Username}")] +public record RecoverPasswordRequest( + string? Username, + string? TotpCode +); diff --git a/src/Lumina.Contracts/Responses/Authentication/ChangePasswordResponse.cs b/src/Lumina.Contracts/Responses/Authentication/ChangePasswordResponse.cs new file mode 100644 index 00000000..c530b669 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authentication/ChangePasswordResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Authentication; + +/// +/// Represents the response model for an account password change request. +/// +/// Whether the password was changed or not. +[DebuggerDisplay("IsPasswordChanged: {IsPasswordChanged}")] +public record ChangePasswordResponse( + bool IsPasswordChanged +); diff --git a/src/Lumina.Contracts/Responses/Authentication/RecoverPasswordResponse.cs b/src/Lumina.Contracts/Responses/Authentication/RecoverPasswordResponse.cs new file mode 100644 index 00000000..b85e7e61 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authentication/RecoverPasswordResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Authentication; + +/// +/// Represents the response model for an account password reset request. +/// +/// Whether the password was reset or not. +[DebuggerDisplay("IsPasswordReset: {IsPasswordReset}")] +public record RecoverPasswordResponse( + bool IsPasswordReset +); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/InitializationResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/InitializationResponse.cs new file mode 100644 index 00000000..d837321d --- /dev/null +++ b/src/Lumina.Contracts/Responses/UsersManagement/InitializationResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.UsersManagement; + +/// +/// Represents a response for verifying the initialization status of the application. +/// +/// Indicates whether the application has been run before, and the super admin account has been created. +[DebuggerDisplay("IsInitialized: {IsInitialized}")] +public record InitializationResponse( + bool IsInitialized +); diff --git a/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs index c18f0c0b..3cc33a73 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs @@ -32,15 +32,21 @@ public class UserConfiguration : IEntityTypeConfiguration .IsRequired() .HasColumnOrder(2); - builder.Property(user => user.TotpSecret) + builder.Property(user => user.TempPassword) .HasColumnOrder(3); - builder.Property(user => user.VerificationToken) + builder.Property(user => user.TotpSecret) .HasColumnOrder(4); - builder.Property(user => user.VerificationTokenCreated) + builder.Property(user => user.VerificationToken) .HasColumnOrder(5); + builder.Property(user => user.VerificationTokenCreated) + .HasColumnOrder(6); + + builder.Property(user => user.TempPasswordCreated) + .HasColumnOrder(7); + builder.HasMany(user => user.Libraries) .WithOne(library => library.User) .HasForeignKey(library => library.UserId) diff --git a/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.Designer.cs new file mode 100644 index 00000000..d142660a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.Designer.cs @@ -0,0 +1,449 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20241111183421_AddUsersTempPasswordColumn")] + partial class AddUsersTempPasswordColumn + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.10"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Created") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("VerificationToken") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("VerificationTokenCreated") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .IsRequired() + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.cs b/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.cs new file mode 100644 index 00000000..2b3f6fb8 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.cs @@ -0,0 +1,106 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class AddUsersTempPasswordColumn : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "VerificationTokenCreated", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 6) + .OldAnnotation("Relational:ColumnOrder", 5); + + migrationBuilder.AlterColumn( + name: "VerificationToken", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 5) + .OldAnnotation("Relational:ColumnOrder", 4); + + migrationBuilder.AlterColumn( + name: "TotpSecret", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 4) + .OldAnnotation("Relational:ColumnOrder", 3); + + migrationBuilder.AddColumn( + name: "TempPassword", + table: "Users", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 3); + + migrationBuilder.AddColumn( + name: "TempPasswordCreated", + table: "Users", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 7); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "TempPassword", + table: "Users"); + + migrationBuilder.DropColumn( + name: "TempPasswordCreated", + table: "Users"); + + migrationBuilder.AlterColumn( + name: "VerificationTokenCreated", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 5) + .OldAnnotation("Relational:ColumnOrder", 6); + + migrationBuilder.AlterColumn( + name: "VerificationToken", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 4) + .OldAnnotation("Relational:ColumnOrder", 5); + + migrationBuilder.AlterColumn( + name: "TotpSecret", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 3) + .OldAnnotation("Relational:ColumnOrder", 4); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 05130179..5c6ec318 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -262,10 +262,18 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(2); - b.Property("TotpSecret") + b.Property("TempPassword") .HasColumnType("TEXT") .HasColumnOrder(3); + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + b.Property("Updated") .HasColumnType("TEXT"); @@ -277,11 +285,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("VerificationToken") .HasColumnType("TEXT") - .HasColumnOrder(4); + .HasColumnOrder(5); b.Property("VerificationTokenCreated") .HasColumnType("TEXT") - .HasColumnOrder(5); + .HasColumnOrder(6); b.HasKey("Id"); diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs index 363219f7..68b02bc1 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs @@ -64,4 +64,19 @@ internal sealed class UserRepository : IUserRepository { return await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == username, cancellationToken).ConfigureAwait(false); } + + /// + /// Updates an user. + /// + /// Ther user to update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successfull operation, or an error. + public async Task> UpdateAsync(UserEntity data, CancellationToken cancellationToken) + { + UserEntity? foundUser = await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == data.Username, cancellationToken).ConfigureAwait(false); + if (foundUser is null) + return Errors.Users.UserDoesNotExist; + _luminaDbContext.Entry(foundUser).CurrentValues.SetValues(data); + return Result.Updated; + } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Users.cs b/src/Lumina.Domain/Common/Errors/Errors.Users.cs index d448682b..7e1da781 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Users.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Users.cs @@ -12,5 +12,6 @@ public static partial class Errors public static class Users { public static Error UserAlreadyExists => Error.Conflict(description: nameof(UserAlreadyExists)); + public static Error UserDoesNotExist => Error.Conflict(description: nameof(UserDoesNotExist)); } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index c08c6e2e..5de680f6 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -1,7 +1,11 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; -using Lumina.Application.Common.Infrastructure; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Infrastructure.Core.Authentication; using Lumina.Infrastructure.Core.Security; +using Lumina.Infrastructure.Core.Time; using Microsoft.Extensions.DependencyInjection; using System.Reflection; #endregion @@ -25,6 +29,12 @@ public static class InfrastructureLayerServices services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + return services; } } diff --git a/src/Lumina.Infrastructure/Core/Authentication/JwtTokenGenerator.cs b/src/Lumina.Infrastructure/Core/Authentication/JwtTokenGenerator.cs new file mode 100644 index 00000000..f50effc4 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Authentication/JwtTokenGenerator.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Infrastructure.Common.Models.Configuration; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +#endregion + +namespace Lumina.Infrastructure.Core.Authentication; + +/// +/// Class for generating JWT tokens. +/// +public class JwtTokenGenerator : IJwtTokenGenerator +{ + private readonly IDateTimeProvider _dateTimeProvider; + private readonly JwtSettingsModel _jwtSettingsModel; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for time related functionality. + /// Injected service for retrieving . + public JwtTokenGenerator(IDateTimeProvider dateTimeProvider, IOptions jwtSettingsModelOptions) + { + _dateTimeProvider = dateTimeProvider; + _jwtSettingsModel = jwtSettingsModelOptions.Value; + } + + /// + /// Generates a new JWT token. + /// + /// The id of the user for which to generate the token. + /// The username of the user for which to generate the token. + /// The generated JWT token. + public string GenerateToken(string id, string username) + { + // use a symmetric key approach + SigningCredentials signingCredentials = new(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettingsModel.SecretKey)), SecurityAlgorithms.HmacSha256); + Claim[] claims = + [ + new Claim(JwtRegisteredClaimNames.Sub, id), + new Claim(JwtRegisteredClaimNames.UniqueName, username), + new Claim(JwtRegisteredClaimNames.Jti, id.ToString()) + ]; + JwtSecurityToken securityToken = new( + issuer: _jwtSettingsModel.Issuer, + audience: _jwtSettingsModel.Audience, + expires: _dateTimeProvider.UtcNow.AddMinutes(_jwtSettingsModel.ExpiryMinutes), + claims: claims, + signingCredentials: signingCredentials); + return new JwtSecurityTokenHandler().WriteToken(securityToken); + } +} diff --git a/src/Lumina.Infrastructure/Core/Authentication/QRCodeGenerator.cs b/src/Lumina.Infrastructure/Core/Authentication/QRCodeGenerator.cs new file mode 100644 index 00000000..b192fbf7 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Authentication/QRCodeGenerator.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authentication; +using OtpNet; +using QRCoder; +using System; +#endregion + +namespace Lumina.Infrastructure.Core.Authentication; + +/// +/// Service for generating QR codes for TOTP. +/// +public class QRCodeGenerator : IQRCodeGenerator +{ + private const string ISSUER = "Lumina"; + + /// + /// Generates a QR code Data URI for the specified TOTP secret. + /// + /// User's username or unique identifier. + /// The TOTP secret for which the QR code should be generated. + /// Data URI for the QR code. + public string GenerateQrCodeDataUri(string username, byte[] secret) + { + // convert secret to Base32 + string base32Secret = Base32Encoding.ToString(secret); + // build the otpauth URI + string otpauthString = $"otpauth://totp/{ISSUER}:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer={ISSUER}"; + // generate QR Code + QRCoder.QRCodeGenerator qrGenerator = new(); + QRCodeData qrData = qrGenerator.CreateQrCode(otpauthString, QRCoder.QRCodeGenerator.ECCLevel.Q); + PngByteQRCode qrCode = new(qrData); + // convert QR Code to Data URI + byte[] pngBytes = qrCode.GetGraphic(20); // specify a pixel size if needed + string dataUri = "data:image/png;base64," + Convert.ToBase64String(pngBytes); + return dataUri; + } +} diff --git a/src/Lumina.Infrastructure/Core/Authentication/TokenGenerator.cs b/src/Lumina.Infrastructure/Core/Authentication/TokenGenerator.cs new file mode 100644 index 00000000..d3fb139a --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Authentication/TokenGenerator.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authentication; +using System; +using System.Security.Cryptography; +#endregion + +namespace Lumina.Infrastructure.Core.Authentication; + +/// +/// Service for the service for generating secure tokens for accounts confirmation or recovery. +/// +public class TokenGenerator : ITokenGenerator +{ + /// + /// Generates a secure token. + /// + /// A secure token. + public string GenerateToken() + { + // allocate an array for the token data + byte[] tokenData = new byte[32]; + // fill the array with a cryptographically strong sequence of random values + RandomNumberGenerator.Fill(tokenData); + // convert to a Base64 string, but replace URL-unsafe characters '+' and '/' with '-' and '_', and remove padding characters ('=') + return Convert.ToBase64String(tokenData).Replace('+', '-').Replace('/', '_').TrimEnd('='); + } +} diff --git a/src/Lumina.Infrastructure/Core/Authentication/TotpTokenGenerator.cs b/src/Lumina.Infrastructure/Core/Authentication/TotpTokenGenerator.cs new file mode 100644 index 00000000..4bc8e8cc --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Authentication/TotpTokenGenerator.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authentication; +using OtpNet; +#endregion + +namespace Lumina.Infrastructure.Core.Authentication; + +/// +/// Service for generating and validating TOTP tokens. +/// +public class TotpTokenGenerator : ITotpTokenGenerator +{ + /// + /// Generates a new TOTP secret for a user. + /// + /// The generated TOTP secret. + public byte[] GenerateSecret() + { + return KeyGeneration.GenerateRandomKey(); // generate a random key for TOTP + } + + /// + /// Validates a TOTP token against the stored secret. + /// + /// The user's TOTP secret. + /// The token to validate. + /// if valid, otherwise. + public bool ValidateToken(byte[] secret, string token) + { + Totp totp = new(secret); + // verify the TOTP token, allowing for slight time drifts between server and client + return totp.VerifyTotp(token, out _, VerificationWindow.RfcSpecifiedNetworkDelay); + } +} diff --git a/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs b/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs index f222f63c..c45c5c3b 100644 --- a/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs +++ b/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Infrastructure; +using Lumina.Application.Common.Infrastructure.Security; using Lumina.Infrastructure.Common.Models.Configuration; using Microsoft.Extensions.Options; using System; diff --git a/src/Lumina.Infrastructure/Core/Security/HashService.cs b/src/Lumina.Infrastructure/Core/Security/HashService.cs index fa6cbef9..e1079cf6 100644 --- a/src/Lumina.Infrastructure/Core/Security/HashService.cs +++ b/src/Lumina.Infrastructure/Core/Security/HashService.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Konscious.Security.Cryptography; -using Lumina.Application.Common.Infrastructure; +using Lumina.Application.Common.Infrastructure.Security; using System; using System.Security.Cryptography; using System.Text; diff --git a/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs b/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs new file mode 100644 index 00000000..d6d5a211 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Time; +using System; +#endregion + +namespace Lumina.Infrastructure.Core.Time; + +/// +/// Service for time related concerns +/// +public class DateTimeProvider : IDateTimeProvider +{ + /// + /// The current UTC time. + /// + public DateTime UtcNow => DateTime.UtcNow; +} diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 03357b57..6576d3a4 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -20,6 +20,9 @@ + + + diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index f2781b26..346ea65a 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -1,9 +1,20 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using FastEndpoints.Swagger; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Json; +using Microsoft.AspNetCore.Mvc.Infrastructure; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using System; +using System.Text; +using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading.RateLimiting; #endregion namespace Lumina.Presentation.Api.Common.DependencyInjection; @@ -17,9 +28,12 @@ public static class PresentationApiLayerServices /// Registers the services of the Presentation API layer into the dependency injection container. /// /// The service collection to add the services to. + /// Application configuration properties. /// The updated . - public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services) + public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services, IConfiguration configuration) { + services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting + services.AddProblemDetails(); services.Configure(jsonOptions => { @@ -28,6 +42,71 @@ public static class PresentationApiLayerServices jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures }); + services.AddRateLimiter(options => + { + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + options.OnRejected = async (context, cancellationToken) => + { + context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests; + context.HttpContext.Response.ContentType = "application/problem+json"; + + var problem = new + { + type = "https://tools.ietf.org/html/rfc7231#section-6.5.29", + title = "TooManyRequests", // TODO: implement translation? + status = StatusCodes.Status429TooManyRequests, + detail = "Too many attempts. Please try again later.", + retryAfter = "15" + }; + + await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken); + }; + options.AddFixedWindowLimiter("authenticationPolicy", config => + { + config.PermitLimit = 10; // allow 10 attempts + config.Window = TimeSpan.FromMinutes(15); // within 15 minute window + config.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; + config.QueueLimit = 0; // don't queue requests + }); + }); + + // add authentication and specify the JWT scheme to check tokens against + services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters() + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = configuration["JwtSettings:Issuer"], + ValidAudience = configuration["JwtSettings:Audience"], + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]!)), + }; + + options.Events = new JwtBearerEvents + { + OnChallenge = context => // event triggered when authentication is not successful for whatever reason + { + context.HandleResponse(); // prevent the default 401 response + // set the response status code to 401 Unauthorized + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + context.Response.ContentType = "application/problem+json"; + + IProblemDetailsService problemDetailsService = context.HttpContext.RequestServices.GetRequiredService(); + return context.Response.WriteAsJsonAsync(new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = StatusCodes.Status401Unauthorized, + title = "Unauthorized", + detail = "You are not authorized", + instance = context.HttpContext.Request.Path + }); + } + }; + }); + services.AddAuthorization(); services.AddFastEndpoints( diff --git a/src/Lumina.Presentation.Api/Common/Http/HttpContextItemKeys.cs b/src/Lumina.Presentation.Api/Common/Http/HttpContextItemKeys.cs index 1ce72009..bcc445d3 100644 --- a/src/Lumina.Presentation.Api/Common/Http/HttpContextItemKeys.cs +++ b/src/Lumina.Presentation.Api/Common/Http/HttpContextItemKeys.cs @@ -1,6 +1,4 @@ -#region ========================================================================= USING ===================================================================================== namespace Lumina.Presentation.Api.Common.Http; -#endregion /// /// Constants shared by HttpContext across a HTTP request (avoid magic strings). @@ -8,4 +6,4 @@ namespace Lumina.Presentation.Api.Common.Http; public static class HttpContextItemKeys { public const string ERRORS = "errors"; -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs index 42b3a4b5..bad03b91 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs @@ -1,4 +1,4 @@ -namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +namespace Lumina.Presentation.Api.Common.Routes.Maintenance; /// /// Class for the collection of routes defined in this API. diff --git a/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Initialization.cs b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Initialization.cs new file mode 100644 index 00000000..86e190c0 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Initialization.cs @@ -0,0 +1,16 @@ +namespace Lumina.Presentation.Api.Common.Routes.Maintenance; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Initialization route. + /// + public static class Initialization + { + public const string SETUP_APPLICATION = "/initialization"; + public const string CHECK_INITIALIZATION = "/initialization"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs index 8c52e412..e2827ea1 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs @@ -12,5 +12,7 @@ public static partial class ApiRoutes { public const string REGISTER_ACCOUNT = "/auth/register"; public const string LOGIN_ACCOUNT = "/auth/login"; + public const string RECOVER_PASSWORD = "/auth/recover-password"; + public const string CHANGE_PASSWORD = "/auth/change-password"; } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs new file mode 100644 index 00000000..c06527fd --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Api.Common.Routes.UsersManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Users route. + /// + public static class Users + { + public const string GET_USER_BY_ID = "/users/{id}"; + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs index 89fc9675..d6a33427 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs @@ -46,10 +46,12 @@ public abstract class BaseEndpoint : Endpoint extensionsDictionary = []; int statusCode = error.Type switch { - ErrorType.Conflict => StatusCodes.Status409Conflict, - ErrorType.NotFound => StatusCodes.Status404NotFound, ErrorType.Validation => StatusCodes.Status400BadRequest, + ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in) ErrorType.Failure => StatusCodes.Status403Forbidden, + ErrorType.Forbidden => StatusCodes.Status403Forbidden, + ErrorType.NotFound => StatusCodes.Status404NotFound, + ErrorType.Conflict => StatusCodes.Status409Conflict, _ => StatusCodes.Status500InternalServerError, }; @@ -92,7 +94,7 @@ public abstract class BaseEndpoint : Endpoint +/// API endpoint for the /initialization route. +/// +public class CheckInitializationEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public CheckInitializationEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Initialization.CHECK_INITIALIZATION); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Checks the initialization status of the application (if the Admin account exists). + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + InitializationResponse result = await _sender.Send(new CheckInitializationQuery(), cancellationToken).ConfigureAwait(false); + return await Task.FromResult(TypedResults.Ok(result)); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs new file mode 100644 index 00000000..e0287981 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.UsersManagement; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class CheckInitializationEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CheckInitializationEndpointSummary() + { + Summary = "Checks the initialization status of the application."; + Description = "Checks the initialization status of the application (if the Admin account exists)."; + + Response(200, "The application initialization status is returned."); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs new file mode 100644 index 00000000..22eaa48a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +using Lumina.Presentation.Api.Common.Routes.Maintenance; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// API endpoint for the /initialization route. +/// +public class SetupApplicationEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public SetupApplicationEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Initialization.SETUP_APPLICATION); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Performs the initial application setup, including creating the Admin account. + /// + /// The request containing the Admin user 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.ToSetupCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{Api.Common.Routes.UsersManagement.ApiRoutes.Users.GET_USER_BY_ID}/{result.Value.Id}", result.Value), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs new file mode 100644 index 00000000..dfe83f21 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class SetupApplicationEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetupApplicationEndpointSummary() + { + Summary = "Performs the initial application setup."; + Description = "Performs the initial application setup, including creating the Admin 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 Admin account of the application is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs index 78a7d211..fd622095 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs @@ -5,7 +5,7 @@ using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Contracts.Requests.FileSystemManagement.Directories; using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; using Lumina.Contracts.Responses.FileSystemManagement; -using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Common.Routes.Maintenance; using Lumina.Presentation.Api.Core.Endpoints.Common; using Mediator; using Microsoft.AspNetCore.Http; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs new file mode 100644 index 00000000..72eb7a55 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs @@ -0,0 +1,54 @@ +#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.Authentication.ChangePassword; + +/// +/// API endpoint for the /auth/change-password route. +/// +public class ChangePasswordEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public ChangePasswordEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Authentication.CHANGE_PASSWORD); + Version(1); + DontCatchExceptions(); + } + + /// + /// Changes the password of an account. + /// + /// The request containing the account for which to change the password. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ChangePasswordRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs new file mode 100644 index 00000000..6b340e79 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class ChangePasswordEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordEndpointSummary() + { + Summary = "Changes the password of an account."; + Description = "Changes the password of an account by reseting its password, after verifying TOTP code associated with the account."; + + RequestParam(r => r.CurrentPassword, "The current password of the account for which to change the password."); + RequestParam(r => r.NewPassword, "The new password of the account for which to change the password."); + RequestParam(r => r.NewPasswordConfirm, "The confirmation of the new password of the account for which to change the password."); + + Response(200, "The password of the account is changed."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs index dc9bc6da..cad0554d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs @@ -1,13 +1,17 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FastEndpoints; +using Lumina.Application.Common.Errors; 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.Builder; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Memory; +using System; using System.Threading; using System.Threading.Tasks; #endregion @@ -40,6 +44,7 @@ public class LoginEndpoint : BaseEndpoint Version(1); AllowAnonymous(); DontCatchExceptions(); + Options(x => x.RequireRateLimiting("authenticationPolicy")); } /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs new file mode 100644 index 00000000..c211da62 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class LoginEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public LoginEndpointSummary() + { + Summary = "Authenticates an account."; + Description = "Authenticates an application account."; + + RequestParam(r => r.Username, "The username of the account to authenticate."); + RequestParam(r => r.Password, "The password of the account to authenticate."); + RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) of the account to authenticate."); + + Response(200, "The JWT authentication token is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs new file mode 100644 index 00000000..4686e25e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs @@ -0,0 +1,57 @@ +#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.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// API endpoint for the /auth/recover-password route. +/// +public class RecoverPasswordEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public RecoverPasswordEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Authentication.RECOVER_PASSWORD); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + Options(x => x.RequireRateLimiting("authenticationPolicy")); + } + + /// + /// Recovers the password of an account. + /// + /// The request containing the account for which to recover the password. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RecoverPasswordRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs new file mode 100644 index 00000000..9488321d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class RecoverPasswordEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordEndpointSummary() + { + Summary = "Recovers the password of an account."; + Description = "Recovers the password of an account by reseting its password, after verifying TOTP code associated with the account."; + + RequestParam(r => r.Username, "The username of the account for which to recover the password."); + RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) of the account for which to recover the password."); + + Response(200, "The password of the account is reset."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs similarity index 93% rename from src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpoint.cs rename to src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs index 59ab21f2..0f2c5498 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs @@ -12,10 +12,10 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Register; +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; /// -/// API endpoint for the /account/register route. +/// API endpoint for the /auth/register route. /// public class RegisterEndpoint : BaseEndpoint { @@ -36,7 +36,7 @@ public class RegisterEndpoint : BaseEndpoint public override void Configure() { Verbs(Http.POST); - Routes(ApiRoutes.Account.REGISTER_ACCOUNT); + Routes(ApiRoutes.Authentication.REGISTER_ACCOUNT); Version(1); AllowAnonymous(); DontCatchExceptions(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs similarity index 98% rename from src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpointSummary.cs rename to src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs index 84aac3aa..cb239aee 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Register/RegisterEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs @@ -3,7 +3,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.Authentication; #endregion -namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Register; +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; /// /// Class used for providing a textual description for the API endpoint, for Swagger. diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index d278535c..ed912969 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -25,6 +25,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all + all @@ -55,7 +56,7 @@ - + $(NoWarn);CS0436 diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index eae291ce..6bfc0cf3 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -37,7 +37,7 @@ public class Program builder.Services.BindSharedConfiguration(builder.Configuration); builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration); - builder.Services.AddPresentationApiLayerServices(); + builder.Services.AddPresentationApiLayerServices(builder.Configuration); builder.Services.AddApplicationLayerServices(); builder.Services.AddInfrastructureLayerServices(); builder.Services.AddDataAccessLayerServices(); @@ -68,7 +68,7 @@ public class Program .Enrich.FromLogContext(); }); WebApplication app = builder.Build(); - + app.UseSerilogRequestLogging(); // apply any pending migrations @@ -77,7 +77,7 @@ public class Program IServiceProvider services = scope.ServiceProvider; try { - LuminaDbContext context = services.GetRequiredService(); + LuminaDbContext context = services.GetRequiredService(); await context.Database.MigrateAsync(); } catch (Exception ex) @@ -94,6 +94,7 @@ public class Program //app.UseHttpsRedirection(); app.UseAuthorization(); + app.UseRateLimiter(); app.UseFastEndpoints(config => { diff --git a/src/Lumina.Presentation.Api/Properties/launchSettings.json b/src/Lumina.Presentation.Api/Properties/launchSettings.json index 103d664d..76a5b1d5 100644 --- a/src/Lumina.Presentation.Api/Properties/launchSettings.json +++ b/src/Lumina.Presentation.Api/Properties/launchSettings.json @@ -17,16 +17,6 @@ }, "dotnetRunMessages": true, "applicationUrl": "https://localhost:7057;http://localhost:5214" - }, - "Container (Dockerfile)": { - "commandName": "Docker", - "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", - "environmentVariables": { - "ASPNETCORE_HTTPS_PORTS": "7057", - "ASPNETCORE_HTTP_PORTS": "5214" - }, - "publishAllPorts": true, - "useSSL": true } }, "$schema": "http://json.schemastore.org/launchsettings.json" diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index 1ca1551c..2805fd39 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Models.Common; using Lumina.Presentation.Web.Common.Models.Configuration; using Lumina.Presentation.Web.Common.Models.FileSystemManagement; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; @@ -25,16 +26,19 @@ namespace Lumina.Presentation.Web.Common.Api; public class ApiHttpClient : IApiHttpClient { private readonly HttpClient _httpClient; + private readonly HttpContext? _httpContext; private readonly JsonSerializerOptions _jsonOptions; /// /// Initializes a new instance of the class. /// /// Injected HttpClient for interacting with the API. + /// Injected service for providing the current HTTP context. /// Injected server configuration application settings. - public ApiHttpClient(HttpClient httpClient, IOptionsSnapshot serverConfigurationOptions) + public ApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot serverConfigurationOptions) { _httpClient = httpClient; + _httpContext = httpContextAccessor.HttpContext; // read the API server configuration values from the configuration, and assign them to the injected client ServerConfigurationModel serverConfigurationModel = serverConfigurationOptions.Value; httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/"); @@ -52,14 +56,14 @@ public class ApiHttpClient : IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the GET request. - public async Task GetAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) + public async Task GetAsync(string endpoint, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Get, endpoint); - if (!string.IsNullOrEmpty(token)) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -68,14 +72,14 @@ public class ApiHttpClient : IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// An object, which allows for asynchronous iteration over the deserialized items. - public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, string? token = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, [EnumeratorCancellation] CancellationToken cancellationToken = default) { - using HttpRequestMessage request = new(HttpMethod.Get, endpoint); - if (!string.IsNullOrEmpty(token)) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + using HttpRequestMessage request = new(HttpMethod.Get, endpoint); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; // send the request and expect only headers initially - this prevents the client from buffering the entire response using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); @@ -93,14 +97,14 @@ public class ApiHttpClient : IApiHttpClient /// Sends a GET request to the specified as an asynchronous operation and returns the result. /// /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// A model containing the deserialized blob. - public async Task GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) + public async Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Get, endpoint); - if (!string.IsNullOrEmpty(token)) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { @@ -125,14 +129,14 @@ public class ApiHttpClient : IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the DELETE request. - public async Task DeleteAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) + public async Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Delete, endpoint); - if (!string.IsNullOrEmpty(token)) - _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -143,14 +147,14 @@ public class ApiHttpClient : IApiHttpClient /// The expected type of the payload content. /// The API endpoint where the request is being sent. /// The data to be serialized and send to the API. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. - public async Task PutAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) + public async Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Put, endpoint); - if (!string.IsNullOrEmpty(token)) - _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -162,14 +166,14 @@ public class ApiHttpClient : IApiHttpClient /// The expected type of the payload content. /// The API endpoint where the request is being sent. /// The data to be serialized and sent to the API. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the POST request. - public async Task PostAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) + public async Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Post, endpoint); - if (!string.IsNullOrEmpty(token)) - _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -203,4 +207,16 @@ public class ApiHttpClient : IApiHttpClient throw new ApiException(problemDetails, response.StatusCode); } } + + /// + /// Retrieves the authentication header for the current user, if available. + /// + /// + /// An with a Bearer token if the user's token is found, otherwise. + /// + private AuthenticationHeaderValue? GetAuthenticationHeader() + { + string? token = _httpContext?.User?.FindFirst("Token")?.Value; + return !string.IsNullOrEmpty(token) ? new AuthenticationHeaderValue("Bearer", token) : null; + } } diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index 4ac6642f..a5d8f3c7 100644 --- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using System.Collections.Generic; using System.Threading; @@ -17,39 +17,35 @@ public interface IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the GET request. - Task GetAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default); + Task GetAsync(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a GET request to the specified as an asynchronous operation and returns the result as a streamable response. /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// An object, which allows for asynchronous iteration over the deserialized items. - IAsyncEnumerable GetAsyncEnumerable(string endpoint, string? token = null, CancellationToken cancellationToken = default); + IAsyncEnumerable GetAsyncEnumerable(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a GET request to the specified as an asynchronous operation and returns the result. /// /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// A model containing the deserialized blob. - Task GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default); + Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a DELETE request to the specified as an asynchronous operation and returns the result. /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the DELETE request. - Task DeleteAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default); + Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a PUT request to the specified as an asynchronous operation and returns the result. @@ -58,10 +54,9 @@ public interface IApiHttpClient /// The expected type of the payload content. /// The API endpoint where the request is being sent. /// The data to be serialized and send to the API. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. - Task PutAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default); + Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); /// /// Sends a POST request to the specified as an asynchronous operation and returns the result. @@ -70,8 +65,7 @@ public interface IApiHttpClient /// The expected type of the payload content. /// The API endpoint where the request is being sent. /// The data to be serialized and sent to the API. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the POST request. - Task PostAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default); -} \ No newline at end of file + Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); +} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs new file mode 100644 index 00000000..8e15a798 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Models.UsersManagement; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Memory; +using System; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Handles the to ensure that the application is initialized before allowing authorization. +/// +public class InitializationHandler : AuthorizationHandler +{ + private readonly IApiHttpClient _apiHttpClient; + private readonly IMemoryCache _cache; + + /// + /// Initializes a new instance of the class. + /// + /// Injected HTTP typed client for interactions with the API. + /// Cache for storing the initialization status. + public InitializationHandler(IApiHttpClient apiHttpClient, IMemoryCache cache) + { + _apiHttpClient = apiHttpClient; + _cache = cache; + } + + /// + /// Checks the application initialization status and authorizes the requirement if initialized. + /// + /// The authorization context. + /// The initialization requirement to be evaluated. + protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, InitializationRequirement requirement) + { + InitializationModel result = await _apiHttpClient.GetAsync("initialization/"); + HttpContext? httpContext = context.Resource as HttpContext; + if (result.IsInitialized) + { + // admin account was registered, remove this requirement from the session + httpContext?.Session.Remove(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); + context.Succeed(requirement); + } + else // store in session that super admin setup is needed + httpContext?.Session.SetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, "true"); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/InitializationRequirement.cs b/src/Lumina.Presentation.Web/Common/Authorization/InitializationRequirement.cs new file mode 100644 index 00000000..78a0f6d9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/InitializationRequirement.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Authorization; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Defines a requirement for initialization status in the authorization process. +/// +public class InitializationRequirement : IAuthorizationRequirement +{ + /// + /// Gets the timeout duration, in minutes, for caching the initialization check. + /// + public int CacheTimeoutMinutes { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The cache timeout in minutes for the initialization status. + public InitializationRequirement(int cacheTimeoutMinutes = 5) + { + CacheTimeoutMinutes = cacheTimeoutMinutes; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs index 9014c48d..307d933d 100644 --- a/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs +++ b/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs @@ -31,7 +31,7 @@ public class ApiExceptionFilter : IExceptionFilter if (context.Exception is ApiException apiException) { // handle unauthorized errors by prompting the user to re-login - if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) + if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in) { SignOutSynchronously(context.HttpContext); string currentUrl = context.HttpContext.Request.GetDisplayUrl(); diff --git a/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs b/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs new file mode 100644 index 00000000..f7543734 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Filters; + +/// +/// Attribute that enforces application initialization checks on controller actions. +/// +public class InitializationCheckAttribute : ActionFilterAttribute +{ + /// + /// Asynchronously executes the initialization check before the action executes. + /// + /// The context for the action being executed. + /// Delegate to execute the next action filter in the pipeline. + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + IAuthorizationService authorizationService = context.HttpContext.RequestServices.GetRequiredService(); + await authorizationService.AuthorizeAsync(context.HttpContext.User, context.HttpContext, "RequireInitialization"); + await next(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs b/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs new file mode 100644 index 00000000..f47a0ec7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs @@ -0,0 +1,10 @@ +namespace Lumina.Presentation.Web.Common.Http; + +/// +/// Constants shared by HttpContext across a HTTP request (avoid magic strings). +/// +public static class HttpContextItemKeys +{ + public const string ERRORS = "errors"; + public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup"; +} diff --git a/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs b/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs index ef1c9c38..c1e3a418 100644 --- a/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using System.Diagnostics; - #endregion namespace Lumina.Presentation.Web.Common.Models.MediaContributors; @@ -20,4 +19,4 @@ public class MediaContributorModel /// Gets the role of the contributor. /// public MediaContributorRoleModel? Role { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/UI/ComboboxItem.cs b/src/Lumina.Presentation.Web/Common/Models/UI/ComboboxItem.cs deleted file mode 100644 index 0168e431..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/UI/ComboboxItem.cs +++ /dev/null @@ -1,28 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.UI; - -/// -/// Represents an item in a combobox. -/// -/// The type used for the property of the item. -[DebuggerDisplay("{Text}")] -public class ComboboxItem -{ - /// - /// Gets or sets the text of the item, that is visible to the user. - /// - public string? Text { get; set; } - - /// - /// Gets or sets the value of the item, that is used by the application. - /// - public TValue? Value { get; set; } - - /// - /// Gets or sets the property indicating whether this element can be selected or not. - /// - public bool IsEnabled { get; set; } = true; -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs new file mode 100644 index 00000000..85b51598 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the request model for account password change. +/// +/// The username of the account. +/// The current password of the account. +/// The new password of the account. +/// The confirmation of the new password of the account. +public record ChangePasswordRequestModel( + string? Username, + string? CurrentPassword, + string? NewPassword, + string? NewPasswordConfirm +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs new file mode 100644 index 00000000..4befdb83 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the response model for an account password change request. +/// +/// Whether the password was changed or not. +[DebuggerDisplay("IsPasswordChanged: {IsPasswordChanged}")] +public record ChangePasswordResponseModel( + bool IsPasswordChanged +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs new file mode 100644 index 00000000..68a0dc52 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Model for verifying the initialization status of the application. +/// +[DebuggerDisplay("IsInitialized: {IsInitialized}")] +public class InitializationModel +{ + /// + /// Gets or sets a value indicating whether the application has been run before, and the super admin account has been created. + /// + public bool IsInitialized { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs new file mode 100644 index 00000000..1668a464 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the request model for account password recovery. +/// +/// The username of the account for which to recover the password. +/// The TOTP (Time-Based One-Time Password) code used to recover the password. +[DebuggerDisplay("Username: {Username}")] +public record RecoverPasswordRequestModel( + string? Username, + string? TotpCode +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs new file mode 100644 index 00000000..4a5703f1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the response model for an account password reset request. +/// +/// Whether the password was reset or not. +[DebuggerDisplay("IsPasswordReset: {IsPasswordReset}")] +public record RecoverPasswordResponseModel( + bool IsPasswordReset +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs index 65c3c658..082b8108 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs @@ -14,9 +14,9 @@ namespace Lumina.Presentation.Web.Common.Models.UsersManagement; /// 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, + string? Username, + string? Password, + string? PasswordConfirm, + string? RegistrationType, bool Use2fa = true ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs deleted file mode 100644 index 8af7c595..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs +++ /dev/null @@ -1,100 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.BookLibrary; -using Lumina.Presentation.Web.Common.Models.MediaContributors; -using Lumina.Presentation.Web.Common.Models.WrittenContentLibrary; -using Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; -using System.Collections.Generic; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.WrittenContentLibrary.BookLibrary; - -/// -/// Represents a request to add a book. -/// -public class AddBookRequest -{ - /// - /// Gets or sets the written content metadata of the book. - /// - public WrittenContentMetadataModel? Metadata { get; set; } - - /// - /// Gets or sets the format of the book (e.g., Hardcover, Paperback), if applicable. - /// - public BookFormat? Format { get; set; } - - /// - /// Gets or sets the edition of the book, if applicable. - /// - public string? Edition { get; set; } - - /// - /// Gets or sets the volume or book number in the series, if applicable. - /// - public int? VolumeNumber { get; set; } - - /// - /// Gets or sets the series name, if the book is part of a series. - /// - public BookSeriesModel? Series { get; set; } - - /// - /// Gets or sets the ASIN (Amazon Standard Identification Number) of the book, if applicable. - /// - public string? ASIN { get; set; } - - /// - /// Gets or sets the Goodreads ID of the book, if applicable. - /// - public string? GoodreadsId { get; set; } - - /// - /// Gets or sets the Library of Congress Control Number (LCCN) of the book, if applicable. - /// - public string? LCCN { get; set; } - - /// - /// Gets or sets the OCLC Number (WorldCat identifier) of the book, if applicable. - /// - public string? OCLCNumber { get; set; } - - /// - /// Gets or sets the Open Library ID of the book, if applicable. - /// - public string? OpenLibraryId { get; set; } - - /// - /// Gets or sets the LibraryThing ID of the book, if applicable. - /// - public string? LibraryThingId { get; set; } - - /// - /// Gets or sets the Google Books ID of the book, if applicable. - /// - public string? GoogleBooksId { get; set; } - - /// - /// Gets or sets the Barnes & Noble ID of the book, if applicable. - /// - public string? BarnesAndNobleId { get; set; } - - /// - /// Gets or sets the Apple Books ID of the book, if applicable. - /// - public string? AppleBooksId { get; set; } - - /// - /// Gets or sets the list of ISBN (International Standard Book Number) of the book. - /// - public List? ISBNs { get; set; } - - /// - /// Gets or sets the list of media contributors (actors, directors, etc) starring in this book. - /// - public List? Contributors { get; set; } - - /// - /// Gets or sets the list of ratings for this book. - /// - public List? Ratings { get; set; } -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs index af839ff7..4845a986 100644 --- a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs +++ b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs @@ -51,7 +51,7 @@ public class AuthController : Controller // check if this is the initial super admin setup string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); ViewData["RegistrationType"] = isPendingSuperAdminSetup == "true" ? "Admin" : "User"; - return View(new RegisterRequestModel()); + return View(); } /// @@ -91,10 +91,18 @@ public class AuthController : Controller return View(); } + /// + /// Displays the view for changing the password of an account. + /// + [HttpGet("change-password")] + public IActionResult ChangePassword() + { + return View(); + } + /// /// Displays the view for registering a new account. /// - [InitializationCheck] [HttpGet("profile")] public IActionResult Profile() { @@ -118,7 +126,7 @@ public class AuthController : Controller } /// - /// Logs in an new account. + /// Logs in an account. /// /// User credentials used for login. /// The url to return to, after login (if any). @@ -167,4 +175,44 @@ public class AuthController : Controller throw; } } + + /// + /// Logs out an account and redirects to the login page. + /// + [HttpGet("logout")] + public async Task Logout() + { + // if the user is not logged in, redirect them to the home page + if (User?.Identity?.IsAuthenticated == false) + return RedirectToAction("Index", "Home"); + Response.Cookies.Delete("Token"); + await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + return RedirectToAction("Login", "Auth"); + } + + /// + /// Recovers the password of an account. + /// + /// User credentials used for password recovery. + [AllowAnonymous] + [ValidateAntiForgeryToken] + [HttpPost("recover-password")] + public async Task RecoverPassword([FromBody] RecoverPasswordRequestModel data) + { + RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync("auth/recover-password", data); + return Json(new { success = true, data = response }); + } + + /// + /// Changes the password of an account. + /// + /// User credentials used for password change. + [ValidateAntiForgeryToken] + [HttpPost("change-password")] + public async Task ChangePassword([FromBody] ChangePasswordRequestModel data) + { + data = data with { Username = User?.Identity?.Name }; // assign the currently logged in user as the user for which to change the password + ChangePasswordResponseModel response = await _apiHttpClient.PostAsync("auth/change-password", data); + return Json(new { success = true, data = response }); + } } diff --git a/src/Lumina.Presentation.Web/Properties/launchSettings.json b/src/Lumina.Presentation.Web/Properties/launchSettings.json index 780c8f09..9cf83bc0 100644 --- a/src/Lumina.Presentation.Web/Properties/launchSettings.json +++ b/src/Lumina.Presentation.Web/Properties/launchSettings.json @@ -1,31 +1,21 @@ { - "profiles": { - "http": { - "commandName": "Project", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "dotnetRunMessages": true, - "applicationUrl": "http://localhost:5012" + "profiles": { + "http": { + "commandName": "Project", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5012" + }, + "https": { + "commandName": "Project", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5012;https://localhost:7112" + } }, - "https": { - "commandName": "Project", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "dotnetRunMessages": true, - "applicationUrl": "http://localhost:5012;https://localhost:7112" - }, - "Container (Dockerfile)": { - "commandName": "Docker", - "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", - "environmentVariables": { - "ASPNETCORE_HTTPS_PORTS": "8081", - "ASPNETCORE_HTTP_PORTS": "8080" - }, - "publishAllPorts": true, - "useSSL": true - } - }, - "$schema": "http://json.schemastore.org/launchsettings.json" -} \ No newline at end of file + "$schema": "http://json.schemastore.org/launchsettings.json" +} diff --git a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml new file mode 100644 index 00000000..a927e388 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml @@ -0,0 +1,91 @@ +@* +/auth/change-password/ +*@ + +@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Services + +@inject IUrlService _urlService + +@model ChangePasswordRequestModel + +
+
+
+ @Html.AntiForgeryToken() + +
+ +
+
+ + *: +
+
+ +
+ DescriptionCurrentPassword +
+ +
+
+ + *: +
+
+ +
+ DescriptionNewPassword +
+ +
+
+ + *: +
+
+ +
+ DescriptionNewPasswordConfirm +
+
+ +
+
+
+ +
+ +
+
+@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml index 27db4172..ebfe6d3f 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml @@ -34,11 +34,11 @@
- - + +
-
- +
@@ -60,17 +60,17 @@ const txtUsername = form.querySelector('[name="Username"]'); const txtPassword = form.querySelector('[name="Password"]'); const txtTotpCode = form.querySelector('[name="TotpCode"]'); - const divTotpCode = document.getElementById('divTotpCode'); - const btnLogin = document.getElementById('btnLogin'); - const btnRecoverPassword = document.getElementById('btnRecoverPassword'); - const btnValidateTotp = document.getElementById('btnValidateTotp'); + const divTotpCode = document.getElementById('div-totp-code'); + const btnLogin = document.getElementById('btn-login'); + const btnRecoverPassword = document.getElementById('btn-recover-password'); + const btnValidateTotp = document.getElementById('btn-validate-totp'); const formData = { Username: txtUsername.value, Password: txtPassword.value, TotpCode: txtTotpCode.value }; - const data = await callApiPostAsync('/auth/login', formData); - if (data && data.isTotpRequired) { + const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("Login", "Auth")', formData); + if (data && data.isTotpRequired === true) { txtUsername.disabled = true; txtPassword.disabled = true; btnLogin.disabled = true; @@ -82,7 +82,7 @@ else if (data) window.location.href = data; }); - document.getElementById('btnRecoverPassword').addEventListener('click', () => { + document.getElementById('btn-recover-password').addEventListener('click', () => { window.location.href = '@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")'; }); diff --git a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml new file mode 100644 index 00000000..4b7f2ab3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml @@ -0,0 +1,84 @@ +@* +/auth/recover-password/ +*@ + +@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Services + +@inject IUrlService _urlService + +@model RecoverPasswordRequestModel + +
+
+
+ @Html.AntiForgeryToken() +
+ +
+
+ + *: +
+
+ +
+
+ +
+
+ + *: +
+
+ +
+
+
+ + +
+
+
+ +
+ + +
+
+@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Views/Account/Register.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml similarity index 78% rename from src/Lumina.Presentation.Web/Views/Account/Register.cshtml rename to src/Lumina.Presentation.Web/Views/Auth/Register.cshtml index c8a9c47a..946594d2 100644 --- a/src/Lumina.Presentation.Web/Views/Account/Register.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml @@ -1,18 +1,21 @@ @* -/account/register/ +/auth/register/ *@ @using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Services @{ string? registrationType = ViewData["RegistrationType"] as string; } +@inject IUrlService _urlService + @model RegisterRequestModel
-
+ @Html.AntiForgeryToken() @@ -57,7 +60,7 @@ DescriptionPasswordConfirm
- +
- +
@@ -78,10 +81,10 @@
- - - - + + + +
@section Scripts { @@ -93,10 +96,10 @@ 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 registerSuccess = document.getElementById('register-success'); + const btnLogin = document.getElementById('btn-login'); + const totpMessage = document.querySelector('#totp-message'); + const totpImage = document.querySelector('#totp-image'); const formData = { Username: txtUsername.value, Password: txtPassword.value, @@ -104,14 +107,14 @@ Use2fa: chkUse2FA.checked, RegistrationType: form.querySelector('[name="RegistrationType"]').value }; - const data = await callApiPostAsync('/account/register', formData); + const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("Register", "Auth")', formData); if (data) { txtUsername.value = ''; txtPassword.value = ''; txtPasswordConfirm.value = ''; form.classList.replace('inline', 'hidden'); registerSuccess.classList.replace('hidden', 'inline'); - redirectButton.classList.replace('hidden', 'block'); + btnLogin.classList.replace('hidden', 'block'); if (chkUse2FA.checked) { totpMessage.classList.remove('hidden'); totpMessage.classList.add('block'); @@ -124,11 +127,11 @@ }); document.querySelector('[name="Use2fa"]').addEventListener('change', function () { const isChecked = this.checked; - document.querySelector('#register2FaAttention').classList.replace( + document.getElementById('#register-two-fa-attention').classList.replace( isChecked ? 'inline' : 'hidden', isChecked ? 'hidden' : 'inline' ); - document.querySelector('#hiddenUseTwoFa').value = isChecked.toString(); + document.getElementById('#hidden-use-two-fa').value = isChecked.toString(); }); } diff --git a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml index 3c0bbfc1..2d519483 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml @@ -4,7 +4,6 @@ @using Lumina.Presentation.Web.Common.Enums.Notifications @using Lumina.Presentation.Web.Common.Exceptions @using Lumina.Presentation.Web.Common.Models.FileSystemManagement -@using Lumina.Presentation.Web.Common.Models.UI @using Microsoft.AspNetCore.Components @using System.Text.Json @using System.Text diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml index afcddf6c..6cf12cbf 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml @@ -1,31 +1,34 @@ - - - - @ViewData["Title"] - Lumina - - - - - - - - - - - - -
-
- @await Html.PartialAsync("_NavMenu") -
-
-
- @RenderBody() + + + + @ViewData["Title"] - Lumina + + + + + + + + + + + + +
+
+ @await Html.PartialAsync("_NavMenu") +
+
+
+ @RenderBody()
-
-
+
+
+ @if (User?.Identity?.IsAuthenticated == true) + + { -
- - + } +
+ + - - - @await RenderSectionAsync("Scripts", required: false) - + + + @await RenderSectionAsync("Scripts", required: false) + diff --git a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml index 4cca95af..09d5b8e8 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml @@ -1,3 +1,7 @@ +@using Lumina.Presentation.Web.Common.Services + +@inject IUrlService _urlService +
/// The created command. - public static RegisterCommand CreateRegisterCommand() + public static RegisterUserCommand CreateRegisterCommand() { string password = "Abcd123$"; - return new Faker() - .CustomInstantiator(f => new RegisterCommand( + return new Faker() + .CustomInstantiator(f => new RegisterUserCommand( default!, default!, default!, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs index 7f710027..7c262421 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; using Lumina.Application.Common.Errors; -using Lumina.Application.Core.UsersManagement.Register; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Application.UnitTests.Core.UsersManagement.Register.Fixture; using System.Diagnostics.CodeAnalysis; #endregion @@ -9,30 +9,30 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Application.UnitTests.Core.UsersManagement.Register; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] public class RegisterCommandValidatorTests { - private readonly RegisterCommandValidator _validator; + private readonly RegisterUserCommandValidator _validator; /// /// Initializes a new instance of the class. /// public RegisterCommandValidatorTests() { - _validator = new RegisterCommandValidator(); + _validator = new RegisterUserCommandValidator(); } [Fact] public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { Username = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.Username) @@ -43,11 +43,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { Username = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.Username) @@ -58,11 +58,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { Username = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.Username) @@ -73,11 +73,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { Password = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.Password) @@ -88,11 +88,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { Password = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.Password) @@ -103,11 +103,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { Password = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.Password) @@ -118,11 +118,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { PasswordConfirm = null! }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) @@ -133,11 +133,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { PasswordConfirm = string.Empty }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) @@ -148,11 +148,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { PasswordConfirm = " " }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) @@ -163,11 +163,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { PasswordConfirm = "$321Bcda" }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.Password) @@ -184,11 +184,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { Password = password, PasswordConfirm = password }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldHaveValidationErrorFor(x => x.Password) @@ -203,11 +203,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { Password = password, PasswordConfirm = password }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Password); @@ -217,11 +217,11 @@ public class RegisterCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - RegisterCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" }; // Act - TestValidationResult result = _validator.TestValidate(command); + TestValidationResult result = _validator.TestValidate(command); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Username); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index 5a9707a1..4936bdda 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -4,10 +4,10 @@ using ErrorOr; using FluentAssertions; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -16,7 +16,6 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Lumina.Contracts.DTO.Common; #endregion namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books;