mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 09:11:10 +00:00
Implements authentication system
This commit is contained in:
1 parent
38829d64ff
commit
a6dcf65d1c
103 files changed
+2983
-454
No files matched your search
@@ -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>
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
/// </summary>
|
||||
public interface IUserRepository : IRepository<UserEntity>,
|
||||
IGetAllRepositoryAction<UserEntity>,
|
||||
IInsertRepositoryAction<UserEntity>
|
||||
IInsertRepositoryAction<UserEntity>,
|
||||
IUpdateRepositoryAction<UserEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
|
||||
|
||||
@@ -12,12 +12,20 @@ public static partial class Errors
|
||||
public static class Authentication
|
||||
{
|
||||
public static Error UsernameAlreadyExists => Error.Conflict(description: nameof(UsernameAlreadyExists));
|
||||
public static Error UsernameDoesNotExist => Error.NotFound(description: nameof(UsernameDoesNotExist));
|
||||
public static Error UsernameCannotBeEmpty => Error.Validation(description: nameof(UsernameCannotBeEmpty));
|
||||
public static Error TotpCannotBeEmpty => Error.Validation(description: nameof(TotpCannotBeEmpty));
|
||||
public static Error PasswordCannotBeEmpty => Error.Validation(description: nameof(PasswordCannotBeEmpty));
|
||||
public static Error NewPasswordCannotBeEmpty => Error.Validation(description: nameof(NewPasswordCannotBeEmpty));
|
||||
public static Error CurrentPasswordCannotBeEmpty => Error.Validation(description: nameof(CurrentPasswordCannotBeEmpty));
|
||||
public static Error PasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(PasswordConfirmCannotBeEmpty));
|
||||
public static Error NewPasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(NewPasswordConfirmCannotBeEmpty));
|
||||
public static Error InvalidPassword => Error.Validation(description: nameof(InvalidPassword));
|
||||
public static Error PasswordsNotMatch => Error.Validation(description: nameof(PasswordsNotMatch));
|
||||
public static Error InvalidTotpCode => Error.Validation(description: nameof(InvalidTotpCode));
|
||||
public static Error InvalidUsernameOrPassword => Error.Failure(description: nameof(InvalidUsernameOrPassword));
|
||||
public static Error InvalidCurrentPassword => Error.Failure(description: nameof(InvalidCurrentPassword));
|
||||
public static Error TempPasswordExpired => Error.Failure(description: nameof(TempPasswordExpired));
|
||||
public static Error PasswordResetAlreadyRequested => Error.Failure(description: nameof(PasswordResetAlreadyRequested));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure;
|
||||
namespace Lumina.Application.Common.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for cryptographic concerns.
|
||||
+1
-1
@@ -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,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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
|
||||
using Lumina.Application.Core.UsersManagement.Register;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
#endregion
|
||||
|
||||
@@ -27,13 +27,13 @@ public static class RegistrationRequestMapping
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="RegisterCommand"/>.
|
||||
/// 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 RegisterCommand ToCommand(this RegistrationRequest request)
|
||||
public static RegisterUserCommand ToCommand(this RegistrationRequest request)
|
||||
{
|
||||
return new RegisterCommand(
|
||||
return new RegisterUserCommand(
|
||||
request.Username,
|
||||
request.Password,
|
||||
request.PasswordConfirm,
|
||||
|
||||
+21
@@ -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>>;
|
||||
+99
@@ -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);
|
||||
}
|
||||
}
|
||||
+24
@@ -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);
|
||||
}
|
||||
}
|
||||
+11
@@ -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>;
|
||||
+47
@@ -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);
|
||||
}
|
||||
}
|
||||
+21
@@ -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>>;
|
||||
+68
@@ -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);
|
||||
}
|
||||
}
|
||||
+26
@@ -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);
|
||||
}
|
||||
}
|
||||
+19
@@ -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>>;
|
||||
+85
@@ -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);
|
||||
}
|
||||
}
|
||||
+23
@@ -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);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -4,7 +4,7 @@ using Lumina.Contracts.Responses.Authentication;
|
||||
using Mediator;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Register;
|
||||
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||
|
||||
/// <summary>
|
||||
/// Command for registering a new account.
|
||||
@@ -13,7 +13,7 @@ namespace Lumina.Application.Core.UsersManagement.Register;
|
||||
/// <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 RegisterCommand(
|
||||
public record RegisterUserCommand(
|
||||
string? Username,
|
||||
string? Password,
|
||||
string? PasswordConfirm,
|
||||
+5
-5
@@ -13,12 +13,12 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Register;
|
||||
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to register a new user account.
|
||||
/// </summary>
|
||||
public class RegisterCommandHandler : IRequestHandler<RegisterCommand, ErrorOr<RegistrationResponse>>
|
||||
public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, ErrorOr<RegistrationResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IHashService _hashService;
|
||||
@@ -27,14 +27,14 @@ public class RegisterCommandHandler : IRequestHandler<RegisterCommand, ErrorOr<R
|
||||
private readonly IQRCodeGenerator _qRCodeGenerator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterCommandHandler"/> class.
|
||||
/// 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 RegisterCommandHandler(
|
||||
public RegisterUserCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
IHashService hashService,
|
||||
ICryptographyService cryptographyService,
|
||||
@@ -48,7 +48,7 @@ public class RegisterCommandHandler : IRequestHandler<RegisterCommand, ErrorOr<R
|
||||
_qRCodeGenerator = qRCodeGenerator;
|
||||
}
|
||||
|
||||
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(RegisterCommand request, CancellationToken cancellationToken)
|
||||
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>();
|
||||
+5
-5
@@ -3,17 +3,17 @@ using FluentValidation;
|
||||
using Lumina.Application.Common.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Register;
|
||||
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="RegisterCommand"/>.
|
||||
/// Validates the needed validation rules for <see cref="RegisterUserCommand"/>.
|
||||
/// </summary>
|
||||
public class RegisterCommandValidator : AbstractValidator<RegisterCommand>
|
||||
public class RegisterUserCommandValidator : AbstractValidator<RegisterUserCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterCommandValidator"/> class.
|
||||
/// Initializes a new instance of the <see cref="RegisterUserCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public RegisterCommandValidator()
|
||||
public RegisterUserCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||
RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description)
|
||||
+23
-2
@@ -65,9 +65,30 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
|
||||
return resultSelectUser.Errors;
|
||||
else if (resultSelectUser.Value is null)
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
// validate the password is correct
|
||||
// validate that the password is correct
|
||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
{
|
||||
// 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
|
||||
|
||||
Reference in new issue
Block a user