Merge pull request #57 from BinaryAlley/feature/implement-authentication-system

Feature/implement authentication system
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-11-11 23:01:43 +02:00
commit bb3ac8038d
122 files changed
+4504 -370

No files matched your search

@@ -17,7 +17,7 @@ public class UserEntity : IStorageEntity
/// <summary>
/// Gets the Id of the user.
/// </summary>
public required Guid Id { get; init; }
public Guid Id { get; init; }
/// <summary>
/// Gets or sets the username of the user.
@@ -29,6 +29,11 @@ public class UserEntity : IStorageEntity
/// </summary>
public required string Password { get; set; }
/// <summary>
/// Gets or sets the temporary hashed password used in password recovery.
/// </summary>
public string? TempPassword { get; set; }
/// <summary>
/// Gets or sets the optional Time-based One-Time Password (TOTP) secret for two-factor authentication.
/// </summary>
@@ -44,6 +49,11 @@ public class UserEntity : IStorageEntity
/// </summary>
public DateTime? VerificationTokenCreated { get; set; }
/// <summary>
/// Gets or sets the date and time when the temporary password used in password recovery was created.
/// </summary>
public DateTime? TempPasswordCreated { get; set; }
/// <summary>
/// Gets the collection of libraries owned by this user.
/// </summary>
@@ -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.
/// </summary>
public interface IUserRepository : IRepository<UserEntity>,
IInsertRepositoryAction<UserEntity>
IGetAllRepositoryAction<UserEntity>,
IInsertRepositoryAction<UserEntity>,
IUpdateRepositoryAction<UserEntity>
{
/// <summary>
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
/// </summary>
/// <param name="username">The username of the user to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="UserEntity"/> if found, or an error.</returns>
Task<ErrorOr<UserEntity?>> GetByUsernameAsync(string username, CancellationToken cancellationToken);
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
#endregion
namespace Lumina.Application.Common.Errors;
/// <summary>
/// Application authentication related error types.
/// </summary>
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));
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
#endregion
namespace Lumina.Application.Common.Errors;
/// <summary>
/// Application authorization related error types.
/// </summary>
public static partial class Errors
{
public static class Authorization
{
public static Error AdminAccountAlreadyCreated => Error.Unauthorized(description: nameof(AdminAccountAlreadyCreated));
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Application.Common.Infrastructure.Authentication;
/// <summary>
/// Interface for generating JWT tokens.
/// </summary>
public interface IJwtTokenGenerator
{
/// <summary>
/// Generates a new JWT token.
/// </summary>
/// <param name="id">The id of the user for which to generate the token.</param>
/// <param name="username">The username for which to generate the token.</param>
/// <returns>The generated JWT token.</returns>
string GenerateToken(string id, string username);
}
@@ -0,0 +1,15 @@
namespace Lumina.Application.Common.Infrastructure.Authentication;
/// <summary>
/// Interface for the service for generating QR codes for TOTP.
/// </summary>
public interface IQRCodeGenerator
{
/// <summary>
/// Generates a QR code Data URI for the specified TOTP secret.
/// </summary>
/// <param name="username">User's username or unique identifier.</param>
/// <param name="secret">The TOTP secret for which the QR code should be generated.</param>
/// <returns>Data URI for the QR code.</returns>
string GenerateQrCodeDataUri(string username, byte[] secret);
}
@@ -0,0 +1,13 @@
namespace Lumina.Application.Common.Infrastructure.Authentication;
/// <summary>
/// Interface for the service for generating secure tokens for accounts confirmation or recovery.
/// </summary>
public interface ITokenGenerator
{
/// <summary>
/// Generates a secure token.
/// </summary>
/// <returns>A secure token.</returns>
string GenerateToken();
}
@@ -0,0 +1,21 @@
namespace Lumina.Application.Common.Infrastructure.Authentication;
/// <summary>
/// Interface for the service for generating and validating TOTP tokens.
/// </summary>
public interface ITotpTokenGenerator
{
/// <summary>
/// Generates a new TOTP secret for a user.
/// </summary>
/// <returns>The generated TOTP secret.</returns>
byte[] GenerateSecret();
/// <summary>
/// Validates a TOTP token against the stored secret.
/// </summary>
/// <param name="secret">The user's TOTP secret.</param>
/// <param name="token">The token to validate.</param>
/// <returns><see langword="true"/> if valid, <see langword="false"/> otherwise.</returns>
bool ValidateToken(byte[] secret, string token);
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.Infrastructure.Security;
/// <summary>
/// Interface for the service for cryptographic concerns.
/// </summary>
public interface ICryptographyService
{
/// <summary>
/// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
/// </summary>
/// <param name="plaintext">The plaintext string to encrypt.</param>
/// <returns>A Base64-encoded string of the combined IV and encrypted ciphertext.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="plaintext"/> is <see langword="null"/> or empty.</exception>
string Encrypt(string plaintext);
/// <summary>
/// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
/// </summary>
/// <param name="ciphertext">The Base64-encoded string containing both IV and ciphertext.</param>
/// <returns>The decrypted plaintext string.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="ciphertext"/> is <see langword="null"/>, empty, or invalid.</exception>
string Decrypt(string ciphertext);
}
@@ -1,4 +1,4 @@
namespace Lumina.Application.Common.Infrastructure;
namespace Lumina.Application.Common.Infrastructure.Security;
/// <summary>
/// Interface for the service for hashing passwords.
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.Infrastructure.Time;
/// <summary>
/// Interface for time related concerns.
/// </summary>
public interface IDateTimeProvider
{
/// <summary>
/// The current UTC time.
/// </summary>
DateTime UtcNow { get; }
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="ChangePasswordRequest"/>.
/// </summary>
public static class ChangePasswordRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="ChangePasswordCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static ChangePasswordCommand ToCommand(this ChangePasswordRequest request)
{
return new ChangePasswordCommand(
request.Username,
request.CurrentPassword,
request.NewPassword,
request.NewPasswordConfirm
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="LoginRequest"/>.
/// </summary>
public static class LoginRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="LoginUserQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static LoginUserQuery ToQuery(this LoginRequest request)
{
return new LoginUserQuery(
request.Username,
request.Password,
request.TotpCode
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="RecoverPasswordRequest"/>.
/// </summary>
public static class RecoverPasswordRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="RecoverPasswordCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static RecoverPasswordCommand ToCommand(this RecoverPasswordRequest request)
{
return new RecoverPasswordCommand(
request.Username,
request.TotpCode
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="RegistrationRequest"/>.
/// </summary>
public static class RegistrationRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="SetupApplicationCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static SetupApplicationCommand ToSetupCommand(this RegistrationRequest request)
{
return new SetupApplicationCommand(
request.Username,
request.Password,
request.PasswordConfirm,
request.Use2fa
);
}
/// <summary>
/// Converts <paramref name="request"/> to <see cref="RegisterUserCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static RegisterUserCommand ToCommand(this RegistrationRequest request)
{
return new RegisterUserCommand(
request.Username,
request.Password,
request.PasswordConfirm,
request.Use2fa
);
}
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
#endregion
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
/// <summary>
/// Command for the initial application setup.
/// </summary>
/// <param name="Username">The username for the Admin account.</param>
/// <param name="Password">The password for the Admin account.</param>
/// <param name="PasswordConfirm">Confirmation of the password.</param>
/// <param name="Use2fa">Indicates whether to enable two-factor authentication for the Admin account.</param>
public record SetupApplicationCommand(
string? Username,
string? Password,
string? PasswordConfirm,
bool Use2fa
) : IRequest<ErrorOr<RegistrationResponse>>;
@@ -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;
/// <summary>
/// Handler for the command to perform the initial application setup.
/// </summary>
public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCommand, ErrorOr<RegistrationResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IHashService _hashService;
private readonly ICryptographyService _cryptographyService;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly IQRCodeGenerator _qRCodeGenerator;
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="hashService">Injected service for password hashing functionality.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
public SetupApplicationCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_cryptographyService = cryptographyService;
_totpTokenGenerator = totpTokenGenerator;
_qRCodeGenerator = qRCodeGenerator;
}
/// <summary>
/// Handles the command to perform the initial application setup.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="RegistrationResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(SetupApplicationCommand request, CancellationToken cancellationToken)
{
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<IEnumerable<UserEntity>> 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<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken);
if (resultInsertUser.IsError)
return resultInsertUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// TODO: insert the default admin profile preferences when they are implemented
// if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
return new RegistrationResponse(user.Id, user.Username, totpSecret);
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
#endregion
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
/// <summary>
/// Validates the needed validation rules for <see cref="SetupApplicationCommand"/>.
/// </summary>
public class SetupApplicationCommandValidator : AbstractValidator<SetupApplicationCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -0,0 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.UsersManagement;
using Mediator;
#endregion
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries;
/// <summary>
/// Query for checking the initialization of the application.
/// </summary>
public record CheckInitializationQuery() : IRequest<InitializationResponse>;
@@ -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;
/// <summary>
/// Handler for the query to check the initialization of the application.
/// </summary>
public class CheckInitializationQueryHandler : IRequestHandler<CheckInitializationQuery, InitializationResponse>
{
private readonly IUnitOfWork _unitOfWork;
public CheckInitializationQueryHandler(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Checks the initialization status of the application.
/// </summary>
/// <param name="request">The query containing the request.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// <see langword="true"/> if the application is initialized (the admin account is created), <see langword="false"/> otherwise.
/// </returns>
public async ValueTask<InitializationResponse> Handle(CheckInitializationQuery request, CancellationToken cancellationToken)
{
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
// if the repository reports an error, or there are no users, the application has not been initialized
ErrorOr<IEnumerable<UserEntity>> resultSelectUser = await userRepository.GetAllAsync(cancellationToken);
if (!resultSelectUser.IsError)
return new InitializationResponse(resultSelectUser.Value.Any());
return new InitializationResponse(false);
}
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
/// <summary>
/// Represents the request model for account password change.
/// </summary>
/// <param name="Username">The username of the account for which to change the password.</param>
/// <param name="CurrentPassword">The current password of the account for which to change the password.</param>
/// <param name="NewPassword">The new password of the account for which to change the password.</param>
/// <param name="NewPasswordConfirm">The confirmation of the new password of the account for which to change the password.</param>
public record ChangePasswordCommand(
string? Username,
string? CurrentPassword,
string? NewPassword,
string? NewPasswordConfirm
) : IRequest<ErrorOr<ChangePasswordResponse>>;
@@ -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;
/// <summary>
/// Handler for the command to change the password of a user account.
/// </summary>
public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordCommand, ErrorOr<ChangePasswordResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IHashService _hashService;
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="hashService">Injected service for password hashing functionality.</param>
public ChangePasswordCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
}
/// <summary>
/// Handles the command to change the password of an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="ChangePasswordResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<ChangePasswordResponse>> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
{
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is 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<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
if (resultUpdateUser.IsError)
return resultUpdateUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return new ChangePasswordResponse(true);
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
/// <summary>
/// Validates the needed validation rules for <see cref="ChangePasswordCommand"/>.
/// </summary>
public class ChangePasswordCommandValidator : AbstractValidator<ChangePasswordCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -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;
/// <summary>
/// Represents the request model for account password recovery.
/// </summary>
/// <param name="Username">The username of the account for which to recover the password.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) of the account for which to recover the password.</param>
[DebuggerDisplay("Username: {Username}")]
public record class RecoverPasswordCommand(
string? Username,
string? TotpCode
) : IRequest<ErrorOr<RecoverPasswordResponse>>;
@@ -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;
/// <summary>
/// Handler for the command to recover the password of an account.
/// </summary>
public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordCommand, ErrorOr<RecoverPasswordResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IHashService _hashService;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly ICryptographyService _cryptographyService;
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="hashService">Injected service for password hashing functionality.</param>
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
public RecoverPasswordCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
ITotpTokenGenerator totpTokenGenerator,
ICryptographyService cryptographyService)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_totpTokenGenerator = totpTokenGenerator;
_cryptographyService = cryptographyService;
}
/// <summary>
/// Handles the command to recover the password of an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="RecoverPasswordResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RecoverPasswordResponse>> Handle(RecoverPasswordCommand request, CancellationToken cancellationToken)
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is 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<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
if (resultUpdateUser.IsError)
return resultUpdateUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return new RecoverPasswordResponse(true);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
/// <summary>
/// Validates the needed validation rules for <see cref="RecoverPasswordCommand"/>.
/// </summary>
public class RecoverPasswordCommandValidator : AbstractValidator<RecoverPasswordCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
/// <summary>
/// Command for registering a new account.
/// </summary>
/// <param name="Username">The username for the new account.</param>
/// <param name="Password">The password for the new account.</param>
/// <param name="PasswordConfirm">Confirmation of the password.</param>
/// <param name="Use2fa">Indicates whether to enable two-factor authentication for the new account.</param>
public record RegisterUserCommand(
string? Username,
string? Password,
string? PasswordConfirm,
bool Use2fa
) : IRequest<ErrorOr<RegistrationResponse>>;
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
/// <summary>
/// Handler for the command to register a new user account.
/// </summary>
public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, ErrorOr<RegistrationResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IHashService _hashService;
private readonly ICryptographyService _cryptographyService;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly IQRCodeGenerator _qRCodeGenerator;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterUserCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="hashService">Injected service for password hashing functionality.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
public RegisterUserCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_cryptographyService = cryptographyService;
_totpTokenGenerator = totpTokenGenerator;
_qRCodeGenerator = qRCodeGenerator;
}
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
{
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is not null)
return Errors.Authentication.UsernameAlreadyExists;
string? totpSecret = null;
UserEntity user = new()
{
Id = Guid.NewGuid(),
Username = request.Username!,
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
Created = DateTime.UtcNow,
Libraries = []
};
// if the user enabled two factor auth, include a QR with the totp secret
if (request.Use2fa)
{
// generate a TOTP secret
byte[] secret = _totpTokenGenerator.GenerateSecret();
// convert the secret into a QR code for the user to scan
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(request.Username!, secret);
// store the TOTP secret in the repository, encrypted
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken);
if (resultInsertUser.IsError)
return resultInsertUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// TODO: insert the default admin profile preferences when they are implemented
// if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
return new RegistrationResponse(user.Id, user.Username, totpSecret);
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
/// <summary>
/// Validates the needed validation rules for <see cref="RegisterUserCommand"/>.
/// </summary>
public class RegisterUserCommandValidator : AbstractValidator<RegisterUserCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RegisterUserCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -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;
/// <summary>
/// Query for authenticating an account.
/// </summary>
/// <param name="Username">The username of the account to authenticate.</param>
/// <param name="Password">The password of the account to authenticate.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) of the account to authenticate.</param>
[DebuggerDisplay("Path: {Path}")]
public record LoginUserQuery(
string? Username,
string? Password,
string? TotpCode = null
) : IRequest<ErrorOr<LoginResponse>>;
@@ -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;
/// <summary>
/// Handler for the query to authenticate an account.
/// </summary>
public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<LoginResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IHashService _hashService;
private readonly IJwtTokenGenerator _jwtTokenGenerator;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly ICryptographyService _cryptographyService;
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="hashService">Injected service for password hashing functionality.</param>
/// <param name="jwtTokenGenerator">Injected service for generating JWT tokens.</param>
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
public LoginUserQueryHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
IJwtTokenGenerator jwtTokenGenerator,
ITotpTokenGenerator totpTokenGenerator,
ICryptographyService cryptographyService)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_jwtTokenGenerator = jwtTokenGenerator;
_totpTokenGenerator = totpTokenGenerator;
_cryptographyService = cryptographyService;
}
/// <summary>
/// Handles the query to authenticate an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LoginResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LoginResponse>> Handle(LoginUserQuery request, CancellationToken cancellationToken)
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is 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);
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="LoginUserQuery"/>.
/// </summary>
public class LoginUserQueryValidator : AbstractValidator<LoginUserQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryValidator"/> class.
/// </summary>
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);
});
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Contracts.Requests.Authentication;
/// <summary>
/// Represents the request model for account password change.
/// </summary>
/// <param name="CurrentPassword">The username of the account.</param>
/// <param name="CurrentPassword">The current password of the account.</param>
/// <param name="NewPassword">The new password of the account.</param>
/// <param name="NewPasswordConfirm">The confirmation of the new password of the account.</param>
public record ChangePasswordRequest(
string? Username,
string? CurrentPassword,
string? NewPassword,
string? NewPasswordConfirm
);
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Authentication;
/// <summary>
/// Represents the request model for user authentication.
/// </summary>
/// <param name="Username">The username of the account to authenticate.</param>
/// <param name="Password">The password of the account to authenticate.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) of the account to authenticate.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginRequest(
string? Username,
string? Password,
string? TotpCode = null
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Authentication;
/// <summary>
/// Represents the request model for account password recovery.
/// </summary>
/// <param name="Username">The username of the account for which to recover the password.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) of the account for which to recover the password.</param>
[DebuggerDisplay("Username: {Username}")]
public record RecoverPasswordRequest(
string? Username,
string? TotpCode
);
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Authentication;
/// <summary>
/// Represents the request model for user registration.
/// </summary>
/// <param name="Username">The desired username for the new account.</param>
/// <param name="Password">The password for the new account.</param>
/// <param name="PasswordConfirm">The confirmation of the entered password, used to ensure consistency.</param>
/// <param name="Use2fa">Indicates whether two-factor authentication (2FA) should be enabled for the new account.</param>
[DebuggerDisplay("Username: {Username}")]
public record RegistrationRequest(
string? Username = null,
string? Password = null,
string? PasswordConfirm = null,
bool Use2fa = true
);
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Authentication;
/// <summary>
/// Represents the response model for an account password change request.
/// </summary>
/// <param name="IsPasswordChanged">Whether the password was changed or not.</param>
[DebuggerDisplay("IsPasswordChanged: {IsPasswordChanged}")]
public record ChangePasswordResponse(
bool IsPasswordChanged
);
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Authentication;
/// <summary>
/// Represents the response model for user authentication.
/// </summary>
/// <param name="Id">The Id of the user to authenticate.</param>
/// <param name="Username">The username of the user to authenticate.</param>
/// <param name="Token">The authentication token used for subsequent requests.</param>
/// <param name="UsesTotp">Whether the user uses 2FA authentication, or not.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginResponse(
Guid Id,
string Username,
string Token,
bool UsesTotp
);
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Authentication;
/// <summary>
/// Represents the response model for an account password reset request.
/// </summary>
/// <param name="IsPasswordReset">Whether the password was reset or not.</param>
[DebuggerDisplay("IsPasswordReset: {IsPasswordReset}")]
public record RecoverPasswordResponse(
bool IsPasswordReset
);
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Authentication;
/// <summary>
/// Represents the response model for user registration.
/// </summary>
/// <param name="Id">The Id of the user.</param>
/// <param name="Username">The username of the user.</param>
/// <param name="TotpSecret">The TOTP (Time-Based One-Time Password) secret used for two-factor authentication.</param>
[DebuggerDisplay("Username: {Username}")]
public record RegistrationResponse(
Guid Id,
string Username,
string? TotpSecret
);
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.UsersManagement;
/// </summary>
/// Represents a response for verifying the initialization status of the application.
/// </summary>
/// <param name="IsInitialized">Indicates whether the application has been run before, and the super admin account has been created.</param>
[DebuggerDisplay("IsInitialized: {IsInitialized}")]
public record InitializationResponse(
bool IsInitialized
);
@@ -32,15 +32,21 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
.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)
@@ -0,0 +1,449 @@
// <auto-generated />
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
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.10");
modelBuilder.Entity("BookGenres", b =>
{
b.Property<Guid>("BookId")
.HasColumnType("TEXT");
b.Property<string>("GenreId")
.HasColumnType("TEXT");
b.HasKey("BookId", "GenreId");
b.HasIndex("GenreId");
b.ToTable("BookGenres", (string)null);
});
modelBuilder.Entity("BookTags", b =>
{
b.Property<Guid>("BookId")
.HasColumnType("TEXT");
b.Property<string>("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<string>("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<string>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<DateTime>("Created")
.HasColumnType("TEXT");
b.Property<string>("LibraryType")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<DateTime?>("Updated")
.HasColumnType("TEXT");
b.Property<Guid>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<string>("ASIN")
.HasMaxLength(10)
.HasColumnType("TEXT")
.HasColumnOrder(21);
b.Property<string>("AppleBooksId")
.HasColumnType("TEXT")
.HasColumnOrder(29);
b.Property<string>("BarnesAndNobleId")
.HasMaxLength(10)
.HasColumnType("TEXT")
.HasColumnOrder(28);
b.Property<DateTime>("Created")
.HasColumnType("TEXT")
.HasColumnOrder(30);
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("Edition")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(19);
b.Property<string>("Format")
.HasColumnType("TEXT")
.HasColumnOrder(18);
b.Property<string>("GoodreadsId")
.HasColumnType("TEXT")
.HasColumnOrder(22);
b.Property<string>("GoogleBooksId")
.HasMaxLength(12)
.HasColumnType("TEXT")
.HasColumnOrder(27);
b.Property<string>("LCCN")
.HasColumnType("TEXT")
.HasColumnOrder(23);
b.Property<string>("LanguageCode")
.HasColumnType("TEXT")
.HasColumnOrder(10);
b.Property<string>("LanguageName")
.HasColumnType("TEXT")
.HasColumnOrder(11);
b.Property<string>("LanguageNativeName")
.HasColumnType("TEXT")
.HasColumnOrder(12);
b.Property<string>("LibraryThingId")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(26);
b.Property<string>("OCLCNumber")
.HasColumnType("TEXT")
.HasColumnOrder(24);
b.Property<string>("OpenLibraryId")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(25);
b.Property<string>("OriginalLanguageCode")
.HasColumnType("TEXT")
.HasColumnOrder(13);
b.Property<string>("OriginalLanguageName")
.HasColumnType("TEXT")
.HasColumnOrder(14);
b.Property<string>("OriginalLanguageNativeName")
.HasColumnType("TEXT")
.HasColumnOrder(15);
b.Property<DateOnly?>("OriginalReleaseDate")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<int?>("OriginalReleaseYear")
.HasColumnType("INTEGER")
.HasColumnOrder(5);
b.Property<string>("OriginalTitle")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<int?>("PageCount")
.HasColumnType("INTEGER")
.HasColumnOrder(17);
b.Property<string>("Publisher")
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(16);
b.Property<DateOnly?>("ReReleaseDate")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<int?>("ReReleaseYear")
.HasColumnType("INTEGER")
.HasColumnOrder(7);
b.Property<string>("ReleaseCountry")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<string>("ReleaseVersion")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<DateTime?>("Updated")
.HasColumnType("TEXT")
.HasColumnOrder(31);
b.Property<int?>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<DateTime>("Created")
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("TempPassword")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<DateTime?>("TempPasswordCreated")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<string>("TotpSecret")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime?>("Updated")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<string>("VerificationToken")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<DateTime?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b1.Property<Guid>("LibraryId")
.HasColumnType("TEXT");
b1.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b1.Property<Guid>("BookId")
.HasColumnType("TEXT");
b1.Property<decimal?>("MaxValue")
.IsRequired()
.HasColumnType("decimal(3,2)");
b1.Property<string>("Source")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b1.Property<decimal?>("Value")
.IsRequired()
.HasColumnType("decimal(3,2)");
b1.Property<int?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b1.Property<Guid>("BookId")
.HasColumnType("TEXT");
b1.Property<string>("Format")
.IsRequired()
.HasMaxLength(6)
.HasColumnType("TEXT");
b1.Property<string>("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
}
}
}
@@ -0,0 +1,106 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations;
/// <inheritdoc />
public partial class AddUsersTempPasswordColumn : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<DateTime>(
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<string>(
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<string>(
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<string>(
name: "TempPassword",
table: "Users",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 3);
migrationBuilder.AddColumn<DateTime>(
name: "TempPasswordCreated",
table: "Users",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 7);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "TempPassword",
table: "Users");
migrationBuilder.DropColumn(
name: "TempPasswordCreated",
table: "Users");
migrationBuilder.AlterColumn<DateTime>(
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<string>(
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<string>(
name: "TotpSecret",
table: "Users",
type: "TEXT",
nullable: true,
oldClrType: typeof(string),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 3)
.OldAnnotation("Relational:ColumnOrder", 4);
}
}
@@ -262,10 +262,18 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("TotpSecret")
b.Property<string>("TempPassword")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<DateTime?>("TempPasswordCreated")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<string>("TotpSecret")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime?>("Updated")
.HasColumnType("TEXT");
@@ -277,11 +285,11 @@ namespace Lumina.DataAccess.Common.Migrations
b.Property<string>("VerificationToken")
.HasColumnType("TEXT")
.HasColumnOrder(4);
.HasColumnOrder(5);
b.Property<DateTime?>("VerificationTokenCreated")
.HasColumnType("TEXT")
.HasColumnOrder(5);
.HasColumnOrder(6);
b.HasKey("Id");
@@ -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;
}
/// <summary>
/// Gets all users.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="UserEntity"/>, or an error.</returns>
public async Task<ErrorOr<IEnumerable<UserEntity>>> GetAllAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.Users.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
/// </summary>
/// <param name="username">The username of the user to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="UserEntity"/> if found, or an error.</returns>
public async Task<ErrorOr<UserEntity?>> GetByUsernameAsync(string username, CancellationToken cancellationToken)
{
return await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == username, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates an user.
/// </summary>
/// <param name="data">Ther user to update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public async Task<ErrorOr<Updated>> 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;
}
}
@@ -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));
}
}
@@ -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<IHashService, HashService>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IJwtTokenGenerator, JwtTokenGenerator>();
services.AddSingleton<IQRCodeGenerator, QRCodeGenerator>();
services.AddSingleton<ITokenGenerator, TokenGenerator>();
services.AddSingleton<ITotpTokenGenerator, TotpTokenGenerator>();
services.AddSingleton<IDateTimeProvider, DateTimeProvider>();
return services;
}
}
@@ -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;
/// <summary>
/// Class for generating JWT tokens.
/// </summary>
public class JwtTokenGenerator : IJwtTokenGenerator
{
private readonly IDateTimeProvider _dateTimeProvider;
private readonly JwtSettingsModel _jwtSettingsModel;
/// <summary>
/// Initializes a new instance of the <see cref="JwtTokenGenerator"/> class.
/// </summary>
/// <param name="dateTimeProvider">Injected service for time related functionality.</param>
/// <param name="jwtSettingsModelOptions">Injected service for retrieving <see cref="JwtSettingsModel"/>.</param>
public JwtTokenGenerator(IDateTimeProvider dateTimeProvider, IOptions<JwtSettingsModel> jwtSettingsModelOptions)
{
_dateTimeProvider = dateTimeProvider;
_jwtSettingsModel = jwtSettingsModelOptions.Value;
}
/// <summary>
/// Generates a new JWT token.
/// </summary>
/// <param name="id">The id of the user for which to generate the token.</param>
/// <param name="username">The username of the user for which to generate the token.</param>
/// <returns>The generated JWT token.</returns>
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);
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using OtpNet;
using QRCoder;
using System;
#endregion
namespace Lumina.Infrastructure.Core.Authentication;
/// <summary>
/// Service for generating QR codes for TOTP.
/// </summary>
public class QRCodeGenerator : IQRCodeGenerator
{
private const string ISSUER = "Lumina";
/// <summary>
/// Generates a QR code Data URI for the specified TOTP secret.
/// </summary>
/// <param name="username">User's username or unique identifier.</param>
/// <param name="secret">The TOTP secret for which the QR code should be generated.</param>
/// <returns>Data URI for the QR code.</returns>
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;
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using System;
using System.Security.Cryptography;
#endregion
namespace Lumina.Infrastructure.Core.Authentication;
/// <summary>
/// Service for the service for generating secure tokens for accounts confirmation or recovery.
/// </summary>
public class TokenGenerator : ITokenGenerator
{
/// <summary>
/// Generates a secure token.
/// </summary>
/// <returns>A secure token.</returns>
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('=');
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using OtpNet;
#endregion
namespace Lumina.Infrastructure.Core.Authentication;
/// <summary>
/// Service for generating and validating TOTP tokens.
/// </summary>
public class TotpTokenGenerator : ITotpTokenGenerator
{
/// <summary>
/// Generates a new TOTP secret for a user.
/// </summary>
/// <returns>The generated TOTP secret.</returns>
public byte[] GenerateSecret()
{
return KeyGeneration.GenerateRandomKey(); // generate a random key for TOTP
}
/// <summary>
/// Validates a TOTP token against the stored secret.
/// </summary>
/// <param name="secret">The user's TOTP secret.</param>
/// <param name="token">The token to validate.</param>
/// <returns><see langword="true"/> if valid, <see langword="false"/> otherwise.</returns>
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);
}
}
@@ -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;
@@ -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;
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Time;
using System;
#endregion
namespace Lumina.Infrastructure.Core.Time;
/// <summary>
/// Service for time related concerns
/// </summary>
public class DateTimeProvider : IDateTimeProvider
{
/// <summary>
/// The current UTC time.
/// </summary>
public DateTime UtcNow => DateTime.UtcNow;
}
@@ -20,6 +20,9 @@
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="Otp.NET" Version="1.4.0" />
<PackageReference Include="QRCoder" Version="1.6.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.2.0" />
</ItemGroup>
<ItemGroup>
@@ -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.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="configuration">Application configuration properties.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
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>(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<IProblemDetailsService>();
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(
@@ -1,6 +1,4 @@
#region ========================================================================= USING =====================================================================================
namespace Lumina.Presentation.Api.Common.Http;
#endregion
/// <summary>
/// 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";
}
}
@@ -1,4 +1,4 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
namespace Lumina.Presentation.Api.Common.Routes.Maintenance;
/// <summary>
/// Class for the collection of routes defined in this API.
@@ -0,0 +1,16 @@
namespace Lumina.Presentation.Api.Common.Routes.Maintenance;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Initialization route.
/// </summary>
public static class Initialization
{
public const string SETUP_APPLICATION = "/initialization";
public const string CHECK_INITIALIZATION = "/initialization";
}
}
@@ -0,0 +1,18 @@
namespace Lumina.Presentation.Api.Common.Routes.UsersManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Authentication route.
/// </summary>
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";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.UsersManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Users route.
/// </summary>
public static class Users
{
public const string GET_USER_BY_ID = "/users/{id}";
}
}
@@ -46,10 +46,12 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
Dictionary<string, object?> 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<TRequest, TResponse> : Endpoint<TRequest, TRe
// return a validation problem result with the constructed error details
return Results.ValidationProblem(
errorsDictionary,
detail: "One or more validation errors occurred.",
detail: "One or more validation errors occurred.", // TODO: implement translation?
instance: HttpContext.Request.Path,
statusCode: 422,
title: "Validation Error",
@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries;
using Lumina.Contracts.Responses.UsersManagement;
using Lumina.Presentation.Api.Common.Routes.Maintenance;
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.Maintenance.ApplicationSetup;
/// <summary>
/// API endpoint for the <c>/initialization</c> route.
/// </summary>
public class CheckInitializationEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CheckInitializationEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Initialization.CHECK_INITIALIZATION);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Checks the initialization status of the application (if the Admin account exists).
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
InitializationResponse result = await _sender.Send(new CheckInitializationQuery(), cancellationToken).ConfigureAwait(false);
return await Task.FromResult(TypedResults.Ok(result));
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.UsersManagement;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// Class used for providing a textual description for the <see cref="CheckInitializationEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class CheckInitializationEndpointSummary : Summary<CheckInitializationEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationEndpointSummary"/> class.
/// </summary>
public CheckInitializationEndpointSummary()
{
Summary = "Checks the initialization status of the application.";
Description = "Checks the initialization status of the application (if the Admin account exists).";
Response<InitializationResponse>(200, "The application initialization status is returned.");
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/initialization</c> route.
/// </summary>
public class SetupApplicationEndpoint : BaseEndpoint<RegistrationRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public SetupApplicationEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Initialization.SETUP_APPLICATION);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Performs the initial application setup, including creating the Admin account.
/// </summary>
/// <param name="request">The request containing the Admin user to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken)
{
ErrorOr<RegistrationResponse> result = await _sender.Send(request.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);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// Class used for providing a textual description for the <see cref="SetupApplicationEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class SetupApplicationEndpointSummary : Summary<SetupApplicationEndpoint, RegistrationRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationEndpointSummary"/> class.
/// </summary>
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<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -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;
@@ -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;
/// <summary>
/// API endpoint for the <c>/auth/change-password</c> route.
/// </summary>
public class ChangePasswordEndpoint : BaseEndpoint<ChangePasswordRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public ChangePasswordEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.CHANGE_PASSWORD);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Changes the password of an account.
/// </summary>
/// <param name="request">The request containing the account for which to change the password.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ChangePasswordRequest request, CancellationToken cancellationToken)
{
ErrorOr<ChangePasswordResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword;
/// <summary>
/// Class used for providing a textual description for the <see cref="ChangePasswordEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class ChangePasswordEndpointSummary : Summary<ChangePasswordEndpoint, ChangePasswordRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordEndpointSummary"/> class.
/// </summary>
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<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/auth/login</c> route.
/// </summary>
public class LoginEndpoint : BaseEndpoint<LoginRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="LoginEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public LoginEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.LOGIN_ACCOUNT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
Options(x => x.RequireRateLimiting("authenticationPolicy"));
}
/// <summary>
/// Authenticates an account.
/// </summary>
/// <param name="request">The request containing the account to be authenticated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(LoginRequest request, CancellationToken cancellationToken)
{
ErrorOr<LoginResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login;
/// <summary>
/// Class used for providing a textual description for the <see cref="LoginEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class LoginEndpointSummary : Summary<LoginEndpoint, LoginRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="LoginEndpointSummary"/> class.
/// </summary>
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<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/auth/recover-password</c> route.
/// </summary>
public class RecoverPasswordEndpoint : BaseEndpoint<RecoverPasswordRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public RecoverPasswordEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.RECOVER_PASSWORD);
Version(1);
AllowAnonymous();
DontCatchExceptions();
Options(x => x.RequireRateLimiting("authenticationPolicy"));
}
/// <summary>
/// Recovers the password of an account.
/// </summary>
/// <param name="request">The request containing the account for which to recover the password.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RecoverPasswordRequest request, CancellationToken cancellationToken)
{
ErrorOr<RecoverPasswordResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword;
/// <summary>
/// Class used for providing a textual description for the <see cref="RecoverPasswordEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class RecoverPasswordEndpointSummary : Summary<RecoverPasswordEndpoint, RecoverPasswordRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointSummary"/> class.
/// </summary>
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<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/auth/register</c> route.
/// </summary>
public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public RegisterEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.REGISTER_ACCOUNT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Registers a new account.
/// </summary>
/// <param name="request">The request containing the account to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken)
{
ErrorOr<RegistrationResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Users.GET_USER_BY_ID}/{result.Value.Id}", result.Value), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register;
/// <summary>
/// Class used for providing a textual description for the <see cref="RegisterEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class RegisterEndpointSummary : Summary<RegisterEndpoint, RegistrationRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEndpointSummary"/> class.
/// </summary>
public RegisterEndpointSummary()
{
Summary = "Registers a new account.";
Description = "Registes a new application account.";
RequestParam(r => r.Username, "The desired username for the new account.");
RequestParam(r => r.Password, "The password for the new account.");
RequestParam(r => r.PasswordConfirm, "The confirmation of the entered password, used to ensure consistency.");
RequestParam(r => r.Use2fa, "Indicates whether two-factor authentication (2FA) should be enabled for the new account.");
Response(200, "The new account of the application is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -25,6 +25,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.8">
<PrivateAssets>all</PrivateAssets>
@@ -55,7 +56,7 @@
<ProjectReference Include="..\Lumina.Infrastructure\Lumina.Infrastructure.csproj" />
<ProjectReference Include="..\Lumina.DataAccess\Lumina.DataAccess.csproj" />
</ItemGroup>
<!--disable warnings generated by Mediator source generator-->
<PropertyGroup>
<NoWarn>$(NoWarn);CS0436</NoWarn>
+4 -3
View File
@@ -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>();
LuminaDbContext context = services.GetRequiredService<LuminaDbContext>();
await context.Database.MigrateAsync();
}
catch (Exception ex)
@@ -94,6 +94,7 @@ public class Program
//app.UseHttpsRedirection();
app.UseAuthorization();
app.UseRateLimiter();
app.UseFastEndpoints(config =>
{
@@ -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"
@@ -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;
/// <summary>
/// Initializes a new instance of the <see cref="ApiHttpClient"/> class.
/// </summary>
/// <param name="httpClient">Injected HttpClient for interacting with the API.</param>
/// <param name="httpContextAccessor">Injected service for providing the current HTTP context.</param>
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
public ApiHttpClient(HttpClient httpClient, IOptionsSnapshot<ServerConfigurationModel> serverConfigurationOptions)
public ApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot<ServerConfigurationModel> 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
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the GET request.</returns>
public async Task<TResponse> GetAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default)
public async Task<TResponse> GetAsync<TResponse>(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<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
@@ -68,14 +72,14 @@ public class ApiHttpClient : IApiHttpClient
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
public async IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, string? token = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
public async IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(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 <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A model containing the deserialized blob.</returns>
public async Task<BlobDataModel> GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default)
public async Task<BlobDataModel> 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
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the DELETE request.</returns>
public async Task<TResponse> DeleteAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default)
public async Task<TResponse> DeleteAsync<TResponse>(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<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
@@ -143,14 +147,14 @@ public class ApiHttpClient : IApiHttpClient
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and send to the API.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the PUT request.</returns>
public async Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default)
public async Task<TResponse> PutAsync<TResponse, TModel>(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<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
@@ -162,14 +166,14 @@ public class ApiHttpClient : IApiHttpClient
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
public async Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default)
public async Task<TResponse> PostAsync<TResponse, TModel>(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<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
@@ -203,4 +207,16 @@ public class ApiHttpClient : IApiHttpClient
throw new ApiException(problemDetails, response.StatusCode);
}
}
/// <summary>
/// Retrieves the authentication header for the current user, if available.
/// </summary>
/// <returns>
/// An <see cref="AuthenticationHeaderValue"/> with a Bearer token if the user's token is found, <see langword="null"/> otherwise.
/// </returns>
private AuthenticationHeaderValue? GetAuthenticationHeader()
{
string? token = _httpContext?.User?.FindFirst("Token")?.Value;
return !string.IsNullOrEmpty(token) ? new AuthenticationHeaderValue("Bearer", token) : null;
}
}
@@ -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
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the GET request.</returns>
Task<TResponse> GetAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default);
Task<TResponse> GetAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result as a streamable response.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default);
IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A model containing the deserialized blob.</returns>
Task<BlobDataModel> GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default);
Task<BlobDataModel> GetBlobAsync(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the DELETE request.</returns>
Task<TResponse> DeleteAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default);
Task<TResponse> DeleteAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
@@ -58,10 +54,9 @@ public interface IApiHttpClient
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and send to the API.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the PUT request.</returns>
Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default);
Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
@@ -70,8 +65,7 @@ public interface IApiHttpClient
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="token">The token used for authentication with the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default);
}
Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
}
@@ -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;
/// <summary>
/// Handles the <see cref="InitializationRequirement"/> to ensure that the application is initialized before allowing authorization.
/// </summary>
public class InitializationHandler : AuthorizationHandler<InitializationRequirement>
{
private readonly IApiHttpClient _apiHttpClient;
private readonly IMemoryCache _cache;
/// <summary>
/// Initializes a new instance of the <see cref="InitializationHandler"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected HTTP typed client for interactions with the API.</param>
/// <param name="cache">Cache for storing the initialization status.</param>
public InitializationHandler(IApiHttpClient apiHttpClient, IMemoryCache cache)
{
_apiHttpClient = apiHttpClient;
_cache = cache;
}
/// <summary>
/// Checks the application initialization status and authorizes the requirement if initialized.
/// </summary>
/// <param name="context">The authorization context.</param>
/// <param name="requirement">The initialization requirement to be evaluated.</param>
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, InitializationRequirement requirement)
{
InitializationModel result = await _apiHttpClient.GetAsync<InitializationModel>("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");
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.AspNetCore.Authorization;
#endregion
namespace Lumina.Presentation.Web.Common.Authorization;
/// <summary>
/// Defines a requirement for initialization status in the authorization process.
/// </summary>
public class InitializationRequirement : IAuthorizationRequirement
{
/// <summary>
/// Gets the timeout duration, in minutes, for caching the initialization check.
/// </summary>
public int CacheTimeoutMinutes { get; }
/// <summary>
/// Initializes a new instance of the <see cref="InitializationRequirement"/> class.
/// </summary>
/// <param name="cacheTimeoutMinutes">The cache timeout in minutes for the initialization status.</param>
public InitializationRequirement(int cacheTimeoutMinutes = 5)
{
CacheTimeoutMinutes = cacheTimeoutMinutes;
}
}
@@ -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<EncryptionSettingsModel>()
.Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
return serviceCollection;
}
}
@@ -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<ForwardedHeadersOptions>(options =>
{
@@ -126,6 +134,9 @@ public static class PresentationWebLayerServices
services.AddHttpContextAccessor();
services.AddScoped<ApiExceptionFilter>();
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IUrlService, UrlService>();
return services;
}
@@ -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();
@@ -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;
/// <summary>
/// Attribute that enforces application initialization checks on controller actions.
/// </summary>
public class InitializationCheckAttribute : ActionFilterAttribute
{
/// <summary>
/// Asynchronously executes the initialization check before the action executes.
/// </summary>
/// <param name="context">The context for the action being executed.</param>
/// <param name="next">Delegate to execute the next action filter in the pipeline.</param>
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
IAuthorizationService authorizationService = context.HttpContext.RequestServices.GetRequiredService<IAuthorizationService>();
await authorizationService.AuthorizeAsync(context.HttpContext.User, context.HttpContext, "RequireInitialization");
await next();
}
}
@@ -0,0 +1,10 @@
namespace Lumina.Presentation.Web.Common.Http;
/// <summary>
/// Constants shared by HttpContext across a HTTP request (avoid magic strings).
/// </summary>
public static class HttpContextItemKeys
{
public const string ERRORS = "errors";
public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup";
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Configuration;
/// <summary>
/// Model for deserializing media settings.
/// </summary>
[DebuggerDisplay("{SECTION_NAME}")]
public class EncryptionSettingsModel
{
public const string SECTION_NAME = "EncryptionSettings";
/// <summary>
/// Gets or sets the root directory where media files are stored.
/// </summary>
public required string SecretKey { get; init; }
}
@@ -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.
/// </summary>
public MediaContributorRoleModel? Role { get; set; }
}
}
@@ -1,28 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UI;
/// <summary>
/// Represents an item in a combobox.
/// </summary>
/// <typeparam name="TValue">The type used for the <see cref="Value"/> property of the item.</typeparam>
[DebuggerDisplay("{Text}")]
public class ComboboxItem<TValue>
{
/// <summary>
/// Gets or sets the text of the item, that is visible to the user.
/// </summary>
public string? Text { get; set; }
/// <summary>
/// Gets or sets the value of the item, that is used by the application.
/// </summary>
public TValue? Value { get; set; }
/// <summary>
/// Gets or sets the property indicating whether this element can be selected or not.
/// </summary>
public bool IsEnabled { get; set; } = true;
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the request model for account password change.
/// </summary>
/// <param name="Username">The username of the account.</param>
/// <param name="CurrentPassword">The current password of the account.</param>
/// <param name="NewPassword">The new password of the account.</param>
/// <param name="NewPasswordConfirm">The confirmation of the new password of the account.</param>
public record ChangePasswordRequestModel(
string? Username,
string? CurrentPassword,
string? NewPassword,
string? NewPasswordConfirm
);
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the response model for an account password change request.
/// </summary>
/// <param name="IsPasswordChanged">Whether the password was changed or not.</param>
[DebuggerDisplay("IsPasswordChanged: {IsPasswordChanged}")]
public record ChangePasswordResponseModel(
bool IsPasswordChanged
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Model for verifying the initialization status of the application.
/// </summary>
[DebuggerDisplay("IsInitialized: {IsInitialized}")]
public class InitializationModel
{
/// <summary>
/// Gets or sets a value indicating whether the application has been run before, and the super admin account has been created.
/// </summary>
public bool IsInitialized { get; set; }
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the request model for user authentication.
/// </summary>
/// <param name="Username">The username used to authenticate.</param>
/// <param name="Password">The password used to authenticate.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) code used for two-factor authentication.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginRequestModel(
string? Username = null,
string? Password = null,
string? TotpCode = null
);
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the response model for a user authentication.
/// </summary>
/// <param name="Id">The Id of the logged in user.</param>
/// <param name="Username">The username of the logged in user.</param>
/// <param name="Token">The JWT authentication token, <see langword="null"/> if authentication failed or TOTP is required.</param>
/// <param name="UsesTotp">Indicates whether the user has Two-Factor Authentication enabled, or not.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginResponseModel(
Guid Id,
string? Username,
string? Token,
bool UsesTotp
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the request model for account password recovery.
/// </summary>
/// <param name="Username">The username of the account for which to recover the password.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) code used to recover the password.</param>
[DebuggerDisplay("Username: {Username}")]
public record RecoverPasswordRequestModel(
string? Username,
string? TotpCode
);
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the response model for an account password reset request.
/// </summary>
/// <param name="IsPasswordReset">Whether the password was reset or not.</param>
[DebuggerDisplay("IsPasswordReset: {IsPasswordReset}")]
public record RecoverPasswordResponseModel(
bool IsPasswordReset
);
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the request model for user registration.
/// </summary>
/// <param name="Username">The desired username for the new account.</param>
/// <param name="Password">The password for the new account.</param>
/// <param name="PasswordConfirm">The confirmation of the entered password, used to ensure consistency.</param>
/// <param name="RegistrationType">Specifies the type of registration, e.g., "Admin" or "User".</param>
/// <param name="Use2fa">Indicates whether two-factor authentication (2FA) should be enabled for the new account.</param>
[DebuggerDisplay("Username: {Username}")]
public record RegisterRequestModel(
string? Username,
string? Password,
string? PasswordConfirm,
string? RegistrationType,
bool Use2fa = true
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the response model for a successful registration.
/// </summary>
/// <param name="Username">The username of the registered user.</param>
/// <param name="TotpSecret">The TOTP (Time-Based One-Time Password) secret used for two-factor authentication.</param>
[DebuggerDisplay("Username: {Username}")]
public record RegisterResponseModel(
string? Username,
string? TotpSecret
);
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more