Replaces FluentValidation and Mediator command/queries handling with custom implementations.

This commit is contained in:
BinaryAlley committed 2026-08-13 08:53:06 -07:00
1 parent 9a5c7473f9
commit 2d1c6b1ab8
297 files changed
+3619 -3045

No files matched your search

@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
@@ -18,4 +16,4 @@ public record ChangePasswordCommand(
string? CurrentPassword,
string? NewPassword,
string? NewPasswordConfirm
) : IRequest<ErrorOr<ChangePasswordResponse>>;
) : ICommand;
@@ -1,13 +1,15 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -17,44 +19,52 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Change
/// <summary>
/// Handler for the command to change the password of a user account.
/// </summary>
public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordCommand, ErrorOr<ChangePasswordResponse>>
public class ChangePasswordCommandHandler : ICommandHandler<ChangePasswordCommand, ErrorOr<ChangePasswordResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IPasswordHashService _hashService;
private readonly IValidator<ChangePasswordCommand> _validator;
/// <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>
/// <param name="validator">Injected validator for application validation rules.</param>
public ChangePasswordCommandHandler(
IUnitOfWork unitOfWork,
IPasswordHashService hashService)
IPasswordHashService hashService,
IValidator<ChangePasswordCommand> validator)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_validator = validator;
}
/// <summary>
/// Handles the command to change the password of an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">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)
public async Task<ErrorOr<ChangePasswordResponse>> HandleAsync(ChangePasswordCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError)
return getUserResult.Errors;
else if (getUserResult.Value is null)
return Errors.Authentication.UsernameDoesNotExist;
// validate if the current password is correct
if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
if (!_hashService.CheckStringAgainstHash(command.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
return Errors.Authentication.InvalidCurrentPassword;
getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!));
getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(command.NewPassword!));
// if the password change was initiated via a password reset, remote the temporary password that was generated in the process
getUserResult.Value.TempPassword = null;
getUserResult.Value.TempPasswordCreated = null;
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
@@ -15,12 +16,28 @@ public class ChangePasswordCommandValidator : AbstractValidator<ChangePasswordCo
/// </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);
RuleFor(command => command.Username)
.NotEmpty()
.WithError(Errors.Authentication.UsernameCannotBeEmpty);
RuleFor(command => command.CurrentPassword)
.NotEmpty()
.WithError(Errors.Authentication.CurrentPasswordCannotBeEmpty)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$")
.WithError(Errors.Authentication.InvalidPassword);
RuleFor(command => command.NewPassword)
.NotEmpty()
.WithError(Errors.Authentication.NewPasswordCannotBeEmpty)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$")
.WithError(Errors.Authentication.InvalidPassword);
RuleFor(command => command.NewPasswordConfirm)
.NotEmpty()
.WithError(Errors.Authentication.NewPasswordConfirmCannotBeEmpty);
RuleFor(command => command.NewPassword)
.Equal(command => command.NewPasswordConfirm)
.WithError(Errors.Authentication.PasswordsNotMatch);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -16,4 +14,4 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Recove
public record class RecoverPasswordCommand(
string? Username,
string? TotpCode
) : IRequest<ErrorOr<RecoverPasswordResponse>>;
) : ICommand;
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -18,12 +20,13 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Recove
/// <summary>
/// Handler for the command to recover the password of an account.
/// </summary>
public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordCommand, ErrorOr<RecoverPasswordResponse>>
public class RecoverPasswordCommandHandler : ICommandHandler<RecoverPasswordCommand, ErrorOr<RecoverPasswordResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IPasswordHashService _hashService;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly ICryptographyService _cryptographyService;
private readonly IValidator<RecoverPasswordCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordCommandHandler"/> class.
@@ -32,31 +35,38 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
/// <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>
/// <param name="validator">Injected validator for application validation rules.</param>
public RecoverPasswordCommandHandler(
IUnitOfWork unitOfWork,
IPasswordHashService hashService,
ITotpTokenGenerator totpTokenGenerator,
ICryptographyService cryptographyService)
ICryptographyService cryptographyService,
IValidator<RecoverPasswordCommand> validator)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_totpTokenGenerator = totpTokenGenerator;
_cryptographyService = cryptographyService;
_validator = validator;
}
/// <summary>
/// Handles the command to recover the password of an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">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)
public async Task<ErrorOr<RecoverPasswordResponse>> HandleAsync(RecoverPasswordCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError)
return getUserResult.Errors;
else if (getUserResult.Value is null)
@@ -67,10 +77,10 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
if (!usesTotp)
return Errors.Authentication.InvalidTotpCode;
if (usesTotp && string.IsNullOrEmpty(request.TotpCode))
if (usesTotp && string.IsNullOrEmpty(command.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(getUserResult.Value.TotpSecret!)), request.TotpCode))
else if (usesTotp && !string.IsNullOrEmpty(command.TotpCode)) // and if they do, validate it
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), command.TotpCode))
return Errors.Authentication.InvalidTotpCode;
// hash the new password and assign it to a temporary password that will be valid 15 minutes
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
@@ -15,9 +16,20 @@ public class RecoverPasswordCommandValidator : AbstractValidator<RecoverPassword
/// </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);
RuleFor(command => command.Username)
.NotEmpty()
.WithError(Errors.Authentication.UsernameCannotBeEmpty);
RuleFor(command => command.TotpCode)
.NotEmpty()
.WithError(Errors.Authentication.TotpCannotBeEmpty);
RuleFor(command => command.TotpCode)
.Length(6)
.WithError(Errors.Authentication.InvalidTotpCode);
RuleFor(command => command.TotpCode)
.Matches(@"^[0-9]{6}$")
.WithError(Errors.Authentication.InvalidTotpCode);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
@@ -18,4 +16,4 @@ public record RegisterUserCommand(
string? Password,
string? PasswordConfirm,
bool Use2fa
) : IRequest<ErrorOr<RegistrationResponse>>;
) : ICommand;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
@@ -7,9 +8,10 @@ using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -19,7 +21,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.Regist
/// <summary>
/// Handler for the command to register a new user account.
/// </summary>
public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, ErrorOr<RegistrationResponse>>
public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, ErrorOr<RegistrationResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IPasswordHashService _hashService;
@@ -27,6 +29,7 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly IQRCodeGenerator _qRCodeGenerator;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IValidator<RegisterUserCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterUserCommandHandler"/> class.
@@ -37,13 +40,15 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public RegisterUserCommandHandler(
IUnitOfWork unitOfWork,
IPasswordHashService hashService,
ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator,
IDateTimeProvider dateTimeProvider)
IDateTimeProvider dateTimeProvider,
IValidator<RegisterUserCommand> validator)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
@@ -51,21 +56,26 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
_totpTokenGenerator = totpTokenGenerator;
_qRCodeGenerator = qRCodeGenerator;
_dateTimeProvider = dateTimeProvider;
_validator = validator;
}
/// <summary>
/// Handles the command to register an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">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(RegisterUserCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<RegistrationResponse>> HandleAsync(RegisterUserCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError)
return getUserResult.Errors;
else if (getUserResult.Value is not null)
@@ -75,8 +85,8 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
UserEntity user = new()
{
Id = id,
Username = request.Username!,
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
Username = command.Username!,
Password = Uri.EscapeDataString(_hashService.HashString(command.Password!)),
CreatedOnUtc = _dateTimeProvider.UtcNow,
Libraries = [],
UserPermissions = [],
@@ -85,12 +95,12 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
LibraryScans = [],
};
// if the user enabled two factor auth, include a QR with the totp secret
if (request.Use2fa)
if (command.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);
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(command.Username!, secret);
// store the TOTP secret in the repository, encrypted
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
@@ -15,13 +16,26 @@ public class RegisterUserCommandValidator : AbstractValidator<RegisterUserComman
/// </summary>
public RegisterUserCommandValidator()
{
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description)
.Length(3, 255).WithMessage(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong.Description)
RuleFor(command => command.Username)
.NotEmpty()
.WithError(Errors.Authentication.UsernameCannotBeEmpty)
.Length(3, 255)
.WithError(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong)
.Matches("^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$") // only allow letters, numbers, dots, underscores and hyphens, and must start and end with letter or number
.WithMessage(Errors.Authentication.InvalidUsername.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);
.WithError(Errors.Authentication.InvalidUsername);
RuleFor(command => command.Password)
.NotEmpty()
.WithError(Errors.Authentication.PasswordCannotBeEmpty)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$")
.WithError(Errors.Authentication.InvalidPassword);
RuleFor(command => command.PasswordConfirm)
.NotEmpty()
.WithError(Errors.Authentication.PasswordConfirmCannotBeEmpty);
RuleFor(command => command.Password)
.Equal(command => command.PasswordConfirm)
.WithError(Errors.Authentication.PasswordsNotMatch);
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.UsersManagement.Users;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUser
/// <summary>
/// Query for retrieving the list of users.
/// </summary>
public record GetUsersQuery() : IRequest<ErrorOr<IEnumerable<UserResponse>>>;
public record GetUsersQuery() : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
@@ -9,7 +10,6 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Application.Common.Mapping.UsersManagement.Users;
using Lumina.Contracts.Responses.UsersManagement.Users;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -20,7 +20,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUser
/// <summary>
/// Handler for the query to retrieve the list of users.
/// </summary>
public class GetUsersQueryHandler : IRequestHandler<GetUsersQuery, ErrorOr<IEnumerable<UserResponse>>>
public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, ErrorOr<IEnumerable<UserResponse>>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
@@ -42,12 +42,12 @@ public class GetUsersQueryHandler : IRequestHandler<GetUsersQuery, ErrorOr<IEnum
/// <summary>
/// Handles the query to retrieve the list of users.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">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 collection of <see cref="UserResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<UserResponse>>> Handle(GetUsersQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<UserResponse>>> HandleAsync(GetUsersQuery query, CancellationToken cancellationToken)
{
// only admins can see the list of users
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -18,4 +16,4 @@ public record LoginUserQuery(
string? Username,
string? Password,
string? TotpCode = null
) : IRequest<ErrorOr<LoginResponse>>;
) : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
@@ -7,9 +8,10 @@ using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -19,7 +21,7 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUs
/// <summary>
/// Handler for the query to authenticate an account.
/// </summary>
public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<LoginResponse>>
public class LoginUserQueryHandler : IQueryHandler<LoginUserQuery, ErrorOr<LoginResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IPasswordHashService _hashService;
@@ -27,6 +29,7 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly ICryptographyService _cryptographyService;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IValidator<LoginUserQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryHandler"/> class.
@@ -37,13 +40,15 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public LoginUserQueryHandler(
IUnitOfWork unitOfWork,
IPasswordHashService hashService,
IJwtTokenGenerator jwtTokenGenerator,
ITotpTokenGenerator totpTokenGenerator,
ICryptographyService cryptographyService,
IDateTimeProvider dateTimeProvider)
IDateTimeProvider dateTimeProvider,
IValidator<LoginUserQuery> validator)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
@@ -51,27 +56,32 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
_totpTokenGenerator = totpTokenGenerator;
_cryptographyService = cryptographyService;
_dateTimeProvider = dateTimeProvider;
_validator = validator;
}
/// <summary>
/// Handles the query to authenticate an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LoginResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LoginResponse>> Handle(LoginUserQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<LoginResponse>> HandleAsync(LoginUserQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError)
return getUserResult.Errors;
else if (getUserResult.Value is null)
return Errors.Authentication.InvalidUsernameOrPassword;
// validate that the password is correct
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
{
// if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too
if (getUserResult.Value.TempPassword is not null)
@@ -87,7 +97,7 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
}
else // temporary password is still valid, validate password against it
{
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(getUserResult.Value.TempPassword!)))
if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.TempPassword!)))
return Errors.Authentication.InvalidUsernameOrPassword;
}
}
@@ -98,10 +108,10 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
string token = _jwtTokenGenerator.GenerateToken(getUserResult.Value.Id.ToString(), getUserResult.Value.Username);
// check if the user uses TOTP
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
if (usesTotp && string.IsNullOrEmpty(request.TotpCode))
if (usesTotp && string.IsNullOrEmpty(query.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(getUserResult.Value.TotpSecret!)), request.TotpCode))
else if (usesTotp && !string.IsNullOrEmpty(query.TotpCode)) // and if they do, validate it
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), query.TotpCode))
return Errors.Authentication.InvalidTotpCode;
return new LoginResponse(getUserResult.Value.Id, getUserResult.Value.Username, token, usesTotp);
}
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
using System.Linq;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
@@ -16,18 +16,19 @@ public class LoginUserQueryValidator : AbstractValidator<LoginUserQuery>
/// </summary>
public LoginUserQueryValidator()
{
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description);
RuleFor(m => m!.TotpCode)
.Custom((code, context) =>
{
if (string.IsNullOrEmpty(code))
return;
if (code.Length != 6)
context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description);
if (!code.All(char.IsDigit))
context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description);
});
RuleFor(query => query.Username)
.NotEmpty()
.WithError(Errors.Authentication.UsernameCannotBeEmpty);
RuleFor(query => query.Password)
.NotEmpty()
.WithError(Errors.Authentication.PasswordCannotBeEmpty)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$")
.WithError(Errors.Authentication.InvalidPassword);
RuleFor(query => query.TotpCode)
.Matches("^[0-9]{6}$")
.When(query => !string.IsNullOrEmpty(query.TotpCode))
.WithError(Errors.Authentication.InvalidTotpCode);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -20,4 +18,4 @@ public record UpdateUserRoleAndPermissionsCommand(
Guid UserId,
Guid? RoleId,
List<Guid> Permissions
) : IRequest<ErrorOr<AuthorizationResponse>>;
) : ICommand;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
@@ -7,8 +8,8 @@ using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -23,11 +24,12 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateU
/// <summary>
/// Handler for the command to update an authorization role.
/// </summary>
public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler<UpdateUserRoleAndPermissionsCommand, ErrorOr<AuthorizationResponse>>
public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<UpdateUserRoleAndPermissionsCommand, ErrorOr<AuthorizationResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateUserRoleAndPermissionsCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateUserRoleAndPermissionsCommandHandler"/> class.
@@ -35,23 +37,29 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler<Update
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public UpdateUserRoleAndPermissionsCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateUserRoleAndPermissionsCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<UpdateUserRoleAndPermissionsCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update an authorization role.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">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 updated <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<AuthorizationResponse>> Handle(UpdateUserRoleAndPermissionsCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<AuthorizationResponse>> HandleAsync(UpdateUserRoleAndPermissionsCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// only admins can update user authorizations
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
@@ -63,15 +71,15 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler<Update
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
// get the user to update
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByIdAsync(request.UserId, cancellationToken).ConfigureAwait(false);
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError || getUserResult.Value is null)
return DomainErrors.Users.UserDoesNotExist;
ErrorOr<RoleEntity?> getRoleResult = default;
if (request.RoleId is not null)
if (command.RoleId is not null)
{
// get the new role
getRoleResult = await roleRepository.GetByIdAsync(request.RoleId!.Value, cancellationToken).ConfigureAwait(false);
getRoleResult = await roleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsError || getRoleResult.Value is null)
return ApplicationErrors.Authorization.RoleNotFound;
@@ -90,7 +98,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler<Update
}
// get the permissions to assign
ErrorOr<IEnumerable<PermissionEntity>> getPermissionsResult =
await permissionRepository.GetByIdsAsync(request.Permissions, cancellationToken).ConfigureAwait(false);
await permissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false);
if (getPermissionsResult.IsError)
return getPermissionsResult.Errors;
@@ -98,12 +106,12 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler<Update
UserEntity userToUpdate = getUserResult.Value;
UserRoleEntity? userRole = default!;
if (request.RoleId is not null)
if (command.RoleId is not null)
{
userRole = new()
{
UserId = userToUpdate.Id,
RoleId = request.RoleId.Value,
RoleId = command.RoleId.Value,
Role = getRoleResult.Value!,
User = userToUpdate
};
@@ -119,7 +127,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler<Update
TempPasswordCreated = userToUpdate.TempPasswordCreated,
Libraries = userToUpdate.Libraries,
UserRole = userRole,
UserPermissions = request.Permissions.Select(permissionId => new UserPermissionEntity
UserPermissions = command.Permissions.Select(permissionId => new UserPermissionEntity
{
UserId = userToUpdate.Id,
PermissionId = permissionId,
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using System;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors;
@@ -17,16 +18,17 @@ public class UpdateUserRoleAndPermissionsCommandValidator : AbstractValidator<Up
/// </summary>
public UpdateUserRoleAndPermissionsCommandValidator()
{
RuleFor(x => x.UserId)
.NotEmpty().WithMessage(DomainErrors.Users.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(DomainErrors.Users.UserIdCannotBeEmpty.Description);
RuleFor(command => command.UserId)
.NotEmpty()
.WithError(DomainErrors.Users.UserIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(DomainErrors.Users.UserIdCannotBeEmpty);
// validate Permissions only if provided
When(x => x.Permissions != null && x.Permissions.Count != 0, () =>
{
RuleForEach(x => x.Permissions)
.NotEmpty().WithMessage(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty.Description);
});
// validate each permission Id when the list is provided
RuleForEach(command => command.Permissions)
.NotEmpty()
.WithError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -15,4 +13,4 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho
[DebuggerDisplay("UserId: {UserId}")]
public record GetAuthorizationQuery(
Guid? UserId
) : IRequest<ErrorOr<AuthorizationResponse>>;
) : IQuery;
@@ -1,12 +1,14 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -17,34 +19,41 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho
/// <summary>
/// Handler for the query to retrieve the authorization roles and permissions of an account.
/// </summary>
public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuery, ErrorOr<AuthorizationResponse>>
public class GetAuthorizationQueryHandler : IQueryHandler<GetAuthorizationQuery, ErrorOr<AuthorizationResponse>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetAuthorizationQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
public GetAuthorizationQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService)
/// <param name="validator">Injected validator for application validation rules.</param>
public GetAuthorizationQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetAuthorizationQuery> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to retrieve the authorization roles and permissions of an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">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 <see cref="AuthorizationResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<AuthorizationResponse>> Handle(GetAuthorizationQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<AuthorizationResponse>> HandleAsync(GetAuthorizationQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// first, check if the Id of the user for whom to get the permission list is different from the Id currently making the request
if (_currentUserService.UserId != request.UserId)
if (_currentUserService.UserId != query.UserId)
{
// if it is, get the role of the current user, and see if they are Admin
ErrorOr<UserAuthorizationEntity> getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false);
@@ -54,7 +63,7 @@ public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuer
if (getCurrentUserPermissionResult.Value.Role != "Admin")
return Errors.Authorization.NotAuthorized;
}
ErrorOr<UserAuthorizationEntity> getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
ErrorOr<UserAuthorizationEntity> getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
return getUserPermissionResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors);
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,8 +17,10 @@ public class GetAuthorizationQueryValidator : AbstractValidator<GetAuthorization
/// </summary>
public GetAuthorizationQueryValidator()
{
RuleFor(x => x.UserId)
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
RuleFor(query => query.UserId)
.NotEmpty()
.WithError(Errors.Users.UserIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Users.UserIdCannotBeEmpty);
}
}
@@ -1,9 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
@@ -16,4 +13,4 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserP
[DebuggerDisplay("UserId: {UserId}")]
public record GetUserPermissionsQuery(
Guid? UserId
) : IRequest<ErrorOr<IEnumerable<PermissionResponse>>>;
) : IQuery;
@@ -1,14 +1,15 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -20,11 +21,12 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserP
/// <summary>
/// Handler for the query to retrieve the authorization permissions of a user.
/// </summary>
public class GetUserPermissionsQueryHandler : IRequestHandler<GetUserPermissionsQuery, ErrorOr<IEnumerable<PermissionResponse>>>
public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQuery, ErrorOr<IEnumerable<PermissionResponse>>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IUserRepository _userRepository;
private readonly IValidator<GetUserPermissionsQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetUserPermissionsQueryHandler"/> class.
@@ -32,29 +34,35 @@ public class GetUserPermissionsQueryHandler : IRequestHandler<GetUserPermissions
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetUserPermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
/// <param name="validator">Injected validator for application validation rules.</param>
public GetUserPermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<GetUserPermissionsQuery> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_userRepository = unitOfWork.GetRepository<IUserRepository>();
_validator = validator;
}
/// <summary>
/// Handles the query to retrieve the authorization permissions of a user.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">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 collection of <see cref="PermissionResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<PermissionResponse>>> Handle(GetUserPermissionsQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<PermissionResponse>>> HandleAsync(GetUserPermissionsQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// only admins can see the list of authorization permissions
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
// get the user from the repository and return its permissions
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError)
return getUserResult.Errors;
else if (getUserResult.Value is null)
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,8 +17,10 @@ public class GetUserPermissionsQueryValidator : AbstractValidator<GetUserPermiss
/// </summary>
public GetUserPermissionsQueryValidator()
{
RuleFor(x => x.UserId)
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
RuleFor(query => query.UserId)
.NotEmpty()
.WithError(Errors.Users.UserIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Users.UserIdCannotBeEmpty);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -15,4 +13,4 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserR
[DebuggerDisplay("UserId: {UserId}")]
public record GetUserRoleQuery(
Guid? UserId
) : IRequest<ErrorOr<RoleResponse?>>;
) : IQuery;
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -18,11 +20,12 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserR
/// <summary>
/// Handler for the query to retrieve the authorization role of a user.
/// </summary>
public class GetUserRoleQueryHandler : IRequestHandler<GetUserRoleQuery, ErrorOr<RoleResponse?>>
public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, ErrorOr<RoleResponse?>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IUserRepository _userRepository;
private readonly IValidator<GetUserRoleQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetUserRoleQueryHandler"/> class.
@@ -30,29 +33,35 @@ public class GetUserRoleQueryHandler : IRequestHandler<GetUserRoleQuery, ErrorOr
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetUserRoleQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
/// <param name="validator">Injected validator for application validation rules.</param>
public GetUserRoleQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<GetUserRoleQuery> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_userRepository = unitOfWork.GetRepository<IUserRepository>();
_validator = validator;
}
/// <summary>
/// Handles the query to retrieve the authorization role of a user.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">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 <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RoleResponse?>> Handle(GetUserRoleQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<RoleResponse?>> HandleAsync(GetUserRoleQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// only admins can see the authorization role
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
// get the user from the repository and return its roles
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError)
return getUserResult.Errors;
else if (getUserResult.Value is null)
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,8 +17,10 @@ public class GetUserRoleQueryValidator : AbstractValidator<GetUserRoleQuery>
/// </summary>
public GetUserRoleQueryValidator()
{
RuleFor(x => x.UserId)
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
RuleFor(query => query.UserId)
.NotEmpty()
.WithError(Errors.Users.UserIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Users.UserIdCannotBeEmpty);
}
}