Reports a missing permission when updating a user's role and permissions

This commit is contained in:
BinaryAlley committed 2026-09-27 21:21:04 +03:00
1 parent cd1386b9e7
commit ab4d596500
3 files changed
+21 -16

No files matched your search

@@ -17,7 +17,8 @@ public static partial class Errors
public static Error AdminRoleNotFound => Error.NotFound(description: nameof(AdminRoleNotFound)); public static Error AdminRoleNotFound => Error.NotFound(description: nameof(AdminRoleNotFound));
public static Error AdminRoleCannotBeDeleted => Error.Forbidden(description: nameof(AdminRoleCannotBeDeleted)); public static Error AdminRoleCannotBeDeleted => Error.Forbidden(description: nameof(AdminRoleCannotBeDeleted));
public static Error RoleNotFound => Error.NotFound(description: nameof(RoleNotFound)); public static Error RoleNotFound => Error.NotFound(description: nameof(RoleNotFound));
public static Error PermissionAlreadyExists => Error.Unauthorized(description: nameof(PermissionAlreadyExists)); public static Error PermissionNotFound => Error.NotFound(description: nameof(PermissionNotFound));
public static Error PermissionAlreadyExists => Error.Conflict(description: nameof(PermissionAlreadyExists));
public static Error RoleAlreadyExists => Error.Conflict(description: nameof(RoleAlreadyExists)); public static Error RoleAlreadyExists => Error.Conflict(description: nameof(RoleAlreadyExists));
public static Error RoleIdCannotBeEmpty => Error.Validation(description: nameof(RoleIdCannotBeEmpty)); public static Error RoleIdCannotBeEmpty => Error.Validation(description: nameof(RoleIdCannotBeEmpty));
public static Error PermissionsListCannotBeNull => Error.Validation(description: nameof(PermissionsListCannotBeNull)); public static Error PermissionsListCannotBeNull => Error.Validation(description: nameof(PermissionsListCannotBeNull));
@@ -78,16 +78,17 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
if (getUserResult.IsFailure || getUserResult.Value is null) if (getUserResult.IsFailure || getUserResult.Value is null)
return DomainErrors.Users.UserDoesNotExist; return DomainErrors.Users.UserDoesNotExist;
Result<RoleEntity?> getRoleResult = default; RoleEntity? newRole = null;
if (command.RoleId is not null) if (command.RoleId is not null)
{ {
// Get the new role. // Get the new role.
getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false); Result<RoleEntity?> getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsFailure || getRoleResult.Value is null) if (getRoleResult.IsFailure || getRoleResult.Value is null)
return ApplicationErrors.Authorization.RoleNotFound; return ApplicationErrors.Authorization.RoleNotFound;
newRole = getRoleResult.Value;
// Check if changing the role of an admin would leave the application without any admin. // 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") if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && newRole.RoleName != "Admin")
{ {
// Count how many admins exist, so the last one is never demoted. // 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); Result<PaginatedResultDto<UserEntity>> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -106,22 +107,25 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
if (getPermissionsResult.IsFailure) if (getPermissionsResult.IsFailure)
return getPermissionsResult.Errors; return getPermissionsResult.Errors;
// Every requested permission must exist, otherwise the requested permission set cannot be built and an unknown Id would throw instead of returning a result.
Dictionary<Guid, PermissionEntity> permissionsById = getPermissionsResult.Value.ToDictionary(permission => permission.Id);
if (command.Permissions.Any(permissionId => !permissionsById.ContainsKey(permissionId)))
return ApplicationErrors.Authorization.PermissionNotFound;
// Update the user. // Update the user.
UserEntity userToUpdate = getUserResult.Value; UserEntity userToUpdate = getUserResult.Value;
// Build the role link for the requested role, leaving the current role untouched when no role was provided. // Build the role link for the requested role, keeping the current role untouched when no role was provided.
UserRoleEntity? userRole = default!; UserRoleEntity? userRole = command.RoleId is null
if (command.RoleId is not null) ? userToUpdate.UserRole
{ : new UserRoleEntity
userRole = new()
{ {
UserId = userToUpdate.Id, UserId = userToUpdate.Id,
RoleId = command.RoleId.Value, RoleId = command.RoleId.Value,
Role = getRoleResult.Value!, Role = newRole!,
User = userToUpdate User = userToUpdate
}; };
}
// Build the updated user by copying the unchanged fields and replacing the role and permissions with the requested ones. // Build the updated user by copying the unchanged fields and replacing the role and permissions with the requested ones.
UserEntity updatedUser = new() UserEntity updatedUser = new()
{ {
@@ -137,7 +141,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
{ {
UserId = userToUpdate.Id, UserId = userToUpdate.Id,
PermissionId = permissionId, PermissionId = permissionId,
Permission = getPermissionsResult.Value.First(permission => permission.Id == permissionId), Permission = permissionsById[permissionId],
User = userToUpdate User = userToUpdate
})], })],
LibraryScans = userToUpdate.LibraryScans LibraryScans = userToUpdate.LibraryScans
@@ -154,7 +158,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
return new AuthorizationResponse( return new AuthorizationResponse(
userToUpdate.Id, userToUpdate.Id,
getRoleResult.Value?.RoleName, newRole?.RoleName ?? userToUpdate.UserRole?.Role.RoleName,
userToUpdate.UserPermissions userToUpdate.UserPermissions
.Select(up => up.Permission.PermissionName) .Select(up => up.Permission.PermissionName)
.ToHashSet() .ToHashSet()
@@ -92,13 +92,13 @@ public class UpdateUserRoleAndPermissionsEndpointSummary : Summary<UpdateUserRol
} }
); );
Response(404, "The request failed because the provided role or user do not exist.", "application/problem+json", Response(404, "The request failed because the provided role, user or permission do not exist.", "application/problem+json",
example: new example: new
{ {
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound", title = "General.NotFound",
status = 404, status = 404,
detail = "RoleNotFound | UserDoesNotExist", detail = "RoleNotFound | UserDoesNotExist | PermissionNotFound",
instance = "/api/v1/auth/users/{userId}/role-and-permissions", instance = "/api/v1/auth/users/{userId}/role-and-permissions",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
} }