mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 12: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
+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