diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs
index e0160778..99629352 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.
@@ -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 537b96f9..f45bf2fd 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,15 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Users;
/// Interface for the repository for users.
///
public interface IUserRepository : IRepository,
- IInsertRepositoryAction
+ IGetAllRepositoryAction,
+ IInsertRepositoryAction,
+ IUpdateRepositoryAction
{
+ ///
+ /// 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..c8440c8c
--- /dev/null
+++ b/src/Lumina.Application/Common/Errors/Errors.Authentication.cs
@@ -0,0 +1,31 @@
+#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 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/Security/ICryptographyService.cs b/src/Lumina.Application/Common/Infrastructure/Security/ICryptographyService.cs
new file mode 100644
index 00000000..af3a41c8
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Security/ICryptographyService.cs
@@ -0,0 +1,27 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.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.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/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/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
new file mode 100644
index 00000000..9cef13b5
--- /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.Authentication.Commands.RegisterUser;
+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 RegisterUserCommand ToCommand(this RegistrationRequest request)
+ {
+ return new RegisterUserCommand(
+ request.Username,
+ request.Password,
+ request.PasswordConfirm,
+ request.Use2fa
+ );
+ }
+}
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/Authentication/Commands/RegisterUser/RegisterUserCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs
new file mode 100644
index 00000000..d9e29c05
--- /dev/null
+++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs
@@ -0,0 +1,21 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using Lumina.Contracts.Responses.Authentication;
+using Mediator;
+#endregion
+
+namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
+
+///
+/// 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 RegisterUserCommand(
+ string? Username,
+ string? Password,
+ string? PasswordConfirm,
+ bool Use2fa
+) : IRequest>;
diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs
new file mode 100644
index 00000000..af17ae55
--- /dev/null
+++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.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.Authentication.Commands.RegisterUser;
+
+///
+/// Handler for the command to register a new user account.
+///
+public class RegisterUserCommandHandler : 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 RegisterUserCommandHandler(
+ IUnitOfWork unitOfWork,
+ IHashService hashService,
+ ICryptographyService cryptographyService,
+ ITotpTokenGenerator totpTokenGenerator,
+ IQRCodeGenerator qRCodeGenerator)
+ {
+ _unitOfWork = unitOfWork;
+ _hashService = hashService;
+ _cryptographyService = cryptographyService;
+ _totpTokenGenerator = totpTokenGenerator;
+ _qRCodeGenerator = qRCodeGenerator;
+ }
+
+ public async ValueTask> Handle(RegisterUserCommand 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/Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs
new file mode 100644
index 00000000..527f8fbc
--- /dev/null
+++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using FluentValidation;
+using Lumina.Application.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
+
+///
+/// Validates the needed validation rules for .
+///
+public class RegisterUserCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public RegisterUserCommandValidator()
+ {
+ 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/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..7f05d206
--- /dev/null
+++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs
@@ -0,0 +1,103 @@
+#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 that the password is correct
+ if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
+ {
+ // if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too
+ if (resultSelectUser.Value.TempPassword is not null)
+ {
+ // the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error
+ if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) > 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
+ 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/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/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/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/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/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/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.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/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.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 77edf339..68b02bc1 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,39 @@ 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);
+ }
+
+ ///
+ /// 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
new file mode 100644
index 00000000..e2827ea1
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs
@@ -0,0 +1,18 @@
+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";
+ 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
new file mode 100644
index 00000000..cad0554d
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs
@@ -0,0 +1,60 @@
+#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
+
+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();
+ Options(x => x.RequireRateLimiting("authenticationPolicy"));
+ }
+
+ ///
+ /// 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.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/Authentication/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs
new file mode 100644
index 00000000..0f2c5498
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/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.Authentication.Register;
+
+///
+/// API endpoint for the /auth/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.Authentication.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/Authentication/Register/RegisterEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs
new file mode 100644
index 00000000..cb239aee
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs
@@ -0,0 +1,29 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.Authentication;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.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.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; buildtransitiveall
+ 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/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/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/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/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/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/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
new file mode 100644
index 00000000..082b8108
--- /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,
+ string? Password,
+ string? PasswordConfirm,
+ string? RegistrationType,
+ 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/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/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.Application/Common/Infrastructure/ICryptographyService.cs b/src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs
similarity index 96%
rename from src/Lumina.Application/Common/Infrastructure/ICryptographyService.cs
rename to src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs
index 197ee8c9..ecfdbccf 100644
--- a/src/Lumina.Application/Common/Infrastructure/ICryptographyService.cs
+++ b/src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs
@@ -2,7 +2,7 @@
using System;
#endregion
-namespace Lumina.Application.Common.Infrastructure;
+namespace Lumina.Presentation.Web.Common.Security;
///
/// Interface for the service for cryptographic concerns.
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);
+ }
+}
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..4845a986
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs
@@ -0,0 +1,218 @@
+#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();
+ }
+
+ ///
+ /// 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 changing the password of an account.
+ ///
+ [HttpGet("change-password")]
+ public IActionResult ChangePassword()
+ {
+ return View();
+ }
+
+ ///
+ /// Displays the view for registering a new account.
+ ///
+ [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 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;
+ }
+ }
+
+ ///
+ /// 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
+
+