Add role management validation to prevent removal of the last admin
- Introduced a new error, `CannotRemoveLastAdmin`, to handle attempts to downgrade the last admin user in the system. - Updated `RoleService` to check the number of admin users before allowing a role change that would remove the last admin. - Enhanced unit tests to verify the new behavior, ensuring that attempts to downgrade the last admin correctly propagate the failure. - Updated API documentation to reflect the new validation logic and its implications for role management.
This commit is contained in:
@@ -17,4 +17,8 @@ public static class RoleErrors
|
||||
"Roles.RoleInUse",
|
||||
"Роль назначена пользователям — сначала переназначьте их."
|
||||
);
|
||||
public static readonly Error CannotRemoveLastAdmin = Error.Conflict(
|
||||
"Roles.CannotRemoveLastAdmin",
|
||||
"Нельзя снять роль admin с последнего администратора."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -100,6 +100,16 @@ internal sealed class RoleService(
|
||||
return Result.Failure(RoleErrors.NotFound);
|
||||
|
||||
var currentRoles = await userManager.GetRolesAsync(user);
|
||||
var wasAdmin = currentRoles.Contains(RoleNames.Admin, StringComparer.OrdinalIgnoreCase);
|
||||
var staysAdmin = role.Name!.Equals(RoleNames.Admin, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (wasAdmin && !staysAdmin)
|
||||
{
|
||||
var adminCount = (await userManager.GetUsersInRoleAsync(RoleNames.Admin)).Count;
|
||||
if (adminCount <= 1)
|
||||
return Result.Failure(RoleErrors.CannotRemoveLastAdmin);
|
||||
}
|
||||
|
||||
if (currentRoles.Count > 0)
|
||||
await userManager.RemoveFromRolesAsync(user, currentRoles);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user