Implements authentication system

This commit is contained in:
BinaryAlley committed 2024-11-11 22:57:33 +02:00
1 parent 38829d64ff
commit a6dcf65d1c
103 files changed
+2983 -454

No files matched your search

@@ -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);
}
}
@@ -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,
@@ -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>();
@@ -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)
@@ -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