Returns the unit of work save changes result

This commit is contained in:
BinaryAlley committed 2026-09-26 12:59:17 +03:00
1 parent f3e465255e
commit 64ef3a1e22
141 files changed
+1388 -1151

No files matched your search

@@ -55,23 +55,32 @@ public class ChangePasswordCommandHandler : ICommandHandler<ChangePasswordComman
if (validationResult.Count > 0)
return validationResult;
// Load the account by its username, so the current password can be verified before it is replaced.
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure)
return getUserResult.Errors;
else if (getUserResult.Value is null)
return Errors.Authentication.UsernameDoesNotExist;
// validate if the current password is correct
// Validate that the provided current password matches the stored hash, so a request with only a valid username cannot overwrite the password.
if (!_hashService.CheckStringAgainstHash(command.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
return Errors.Authentication.InvalidCurrentPassword;
// The stored hash is URI escaped, so the new hash is escaped the same way before it is stored.
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
// If the password change was initiated via a password reset, remove the temporary password that was generated in the process.
getUserResult.Value.TempPassword = null;
getUserResult.Value.TempPasswordCreated = null;
// update the user
// Update the user and persist the change.
Result<Updated> updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
if (updateUserResult.IsFailure)
return updateUserResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return new ChangePasswordResponse(true);
}
}
@@ -64,31 +64,37 @@ public class RecoverPasswordCommandHandler : ICommandHandler<RecoverPasswordComm
if (validationResult.Count > 0)
return validationResult;
// check if any users already exists
// Load the account by its username, so its existing recovery state and TOTP configuration can be checked.
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure)
return getUserResult.Errors;
else if (getUserResult.Value is null)
return Errors.Authentication.UsernameDoesNotExist;
else if (getUserResult.Value.TempPassword is not null) // if a temp password is present, a password request was already requested
else if (getUserResult.Value.TempPassword is not null) // If a temporary password is present, a password reset was already requested.
return Errors.Authentication.PasswordResetAlreadyRequested;
// check if the user uses TOTP
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
if (!usesTotp)
// Check if the user uses TOTP.
bool doesUseTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
if (!doesUseTotp)
return Errors.Authentication.InvalidTotpCode;
if (usesTotp && string.IsNullOrEmpty(command.TotpCode))
if (doesUseTotp && string.IsNullOrEmpty(command.TotpCode))
return Errors.Authentication.InvalidTotpCode;
else if (usesTotp && !string.IsNullOrEmpty(command.TotpCode)) // and if they do, validate it
else if (doesUseTotp && !string.IsNullOrEmpty(command.TotpCode)) // When the user uses TOTP, validate the provided code before allowing the reset.
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
// Generate the hash of a temporary password and record when it was created, so that the reset flow can expire it after 15 minutes.
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: Replace the hardcoded password with a randomly generated one.
getUserResult.Value.TempPasswordCreated = DateTime.UtcNow;
// update the user
// Update the user and persist the temporary password.
Result<Updated> updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
if (updateUserResult.IsFailure)
return updateUserResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return new RecoverPasswordResponse(true);
}
}
@@ -73,12 +73,14 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
if (validationResult.Count > 0)
return validationResult;
// check if any users already exists (admin account is only set once!)
// Check if a user with this username already exists, since the admin account can only be created once.
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure)
return getUserResult.Errors;
else if (getUserResult.Value is not null)
return Errors.Authentication.UsernameAlreadyExists;
// Build the account, hashing the password and URI escaping it the same way as the stored form.
string? totpSecret = null;
Guid id = Guid.NewGuid();
UserEntity user = new()
@@ -93,23 +95,29 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
CreatedBy = id,
LibraryScans = [],
};
// if the user enabled two factor auth, include a QR with the totp secret
// If the user enabled two factor authentication, include a QR code with the TOTP secret.
if (command.Use2fa)
{
// generate a TOTP secret
// Generate a TOTP secret.
byte[] secret = _totpTokenGenerator.GenerateSecret();
// convert the secret into a QR code for the user to scan
// Convert the secret into a QR code for the user to scan.
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(command.Username!, secret);
// store the TOTP secret in the repository, encrypted
// Store the TOTP secret in the repository, encrypted.
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
// Insert the user and persist the change.
Result<Created> insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
if (insertUserResult.IsFailure)
return insertUserResult.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
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// 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 unencrypted, so it can be displayed.
return new RegistrationResponse(user.Id, user.Username, totpSecret);
}
}
@@ -73,28 +73,31 @@ public class LoginUserQueryHandler : IQueryHandler<LoginUserQuery, Result<LoginR
if (validationResult.Count > 0)
return validationResult;
// check if any users already exists
// Load the account by its username, so the password and two factor state can be verified.
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure)
return getUserResult.Errors;
else if (getUserResult.Value is null)
return Errors.Authentication.InvalidUsernameOrPassword;
// validate that the password is correct
// Validate that the password matches the stored hash.
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 a password reset was requested, a temporary password is in use; when the check against the regular password failed, try the temporary one too.
if (getUserResult.Value.TempPassword is not null)
{
// the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error
// The temporary password is only valid for 15 minutes; when it is obsolete, remove it and return an error.
if (getUserResult.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow)
{
getUserResult.Value.TempPassword = null;
getUserResult.Value.TempPasswordCreated = null;
await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Errors.Authentication.TempPasswordExpired;
}
else // temporary password is still valid, validate password against it
else // The temporary password is still valid, so validate the password against it.
{
if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.TempPassword!)))
return Errors.Authentication.InvalidUsernameOrPassword;
@@ -103,15 +106,17 @@ public class LoginUserQueryHandler : IQueryHandler<LoginUserQuery, Result<LoginR
else
return Errors.Authentication.InvalidUsernameOrPassword;
}
// create the JWT token
// Create the JWT token.
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(query.TotpCode))
// Check if the user uses TOTP.
bool doesUseTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
if (doesUseTotp && string.IsNullOrEmpty(query.TotpCode))
return Errors.Authentication.InvalidTotpCode;
else if (usesTotp && !string.IsNullOrEmpty(query.TotpCode)) // and if they do, validate it
else if (doesUseTotp && !string.IsNullOrEmpty(query.TotpCode)) // When the user uses TOTP, validate the provided code.
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);
return new LoginResponse(getUserResult.Value.Id, getUserResult.Value.Username, token, doesUseTotp);
}
}
@@ -6,6 +6,8 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
@@ -60,52 +62,54 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can update user authorizations
// Only admins can update user authorizations.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return ApplicationErrors.Authorization.NotAuthorized;
// get the user to update
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false);
// Get the user to update.
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure || getUserResult.Value is null)
return DomainErrors.Users.UserDoesNotExist;
Result<RoleEntity?> getRoleResult = default;
if (command.RoleId is not null)
{
// get the new role
getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false);
// Get the new role.
getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsFailure || getRoleResult.Value is null)
return ApplicationErrors.Authorization.RoleNotFound;
// check if we're changing an admin's role and if this would leave us without admins
// Check if changing the role of an admin would leave the application without any admin.
if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin")
{
// count how many admins we have
Result<IEnumerable<UserEntity>> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
// Count how many admins exist, so the last one is never demoted.
Result<PaginatedResultDto<UserEntity>> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAllUsersResult.IsFailure)
return getAllUsersResult.Errors;
int adminCount = getAllUsersResult.Value.Count(user => user.UserRole?.Role.RoleName == "Admin");
int adminCount = getAllUsersResult.Value.Data.Count(user => user.UserRole?.Role.RoleName == "Admin");
if (adminCount <= 1)
return ApplicationErrors.Authorization.CannotRemoveLastAdmin;
}
}
// get the permissions to assign
// Get the permissions to assign.
Result<IEnumerable<PermissionEntity>> getPermissionsResult =
await _unitOfWork.PermissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false);
if (getPermissionsResult.IsFailure)
return getPermissionsResult.Errors;
// update the user
// Update the user.
UserEntity userToUpdate = getUserResult.Value;
// Build the role link for the requested role, leaving the current role untouched when no role was provided.
UserRoleEntity? userRole = default!;
if (command.RoleId is not null)
{
@@ -118,6 +122,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
};
}
// Build the updated user by copying the unchanged fields and replacing the role and permissions with the requested ones.
UserEntity updatedUser = new()
{
Id = userToUpdate.Id,
@@ -138,12 +143,14 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
LibraryScans = userToUpdate.LibraryScans
};
// save changes and return result
// Save the changes and return the result.
Result<Updated> updateResult = await _unitOfWork.UserRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return new AuthorizationResponse(
userToUpdate.Id,
@@ -106,7 +106,10 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
return updateResult.Errors;
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Updated;
}
}