From 38829d64ff8280d8b17010a3db7a9b6d98444c6c Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 11 Nov 2024 15:19:50 +0200 Subject: [PATCH] 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": {