Files
breadcrumb-the-shire/pages/admin/roles/delete($id).php

75 lines
2.3 KiB
PHP
Raw Normal View History

2026-02-04 23:31:53 +01:00
<?php
use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
2026-02-04 23:31:53 +01:00
use MintyPHP\Router;
use MintyPHP\Service\Access\RoleAuthorizationPolicy;
2026-02-23 12:58:19 +01:00
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
2026-02-04 23:31:53 +01:00
$session = app(SessionStoreInterface::class)->all();
2026-02-04 23:31:53 +01:00
Guard::requireLogin();
$currentUserId = (int) ($session['user']['id'] ?? 0);
2026-03-04 15:56:58 +01:00
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
// Authorization is checked generically (can user delete ANY role?) before loading the entity.
// Context-aware policies (departments, tenants, users) load the entity first to pass target_id.
// Both patterns are valid; context-aware is preferred for new code.
$decision = $authorizationService->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_DELETE, [
'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
if (Request::wantsJson()) {
http_response_code($decision->status());
Router::json(['error' => $decision->error()]);
return;
}
Guard::deny();
}
2026-02-04 23:31:53 +01:00
$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
Router::redirect('admin/roles');
return;
2026-02-04 23:31:53 +01:00
}
2026-03-04 15:56:58 +01:00
$role = app(\MintyPHP\Service\Access\RoleService::class)->findByUuid($uuid);
$affectedUserIds = [];
if ($role) {
$roleId = (int) ($role['id'] ?? 0);
if ($roleId > 0) {
$affectedUserIds = app(\MintyPHP\Repository\Access\UserRoleRepository::class)->listUserIdsByRoleIds([$roleId]);
}
}
$result = app(\MintyPHP\Service\Access\RoleService::class)->deleteByUuid($uuid);
2026-02-04 23:31:53 +01:00
if (!($result['ok'] ?? false)) {
$error = $result['error'] ?? 'not_found';
$status = $result['status'] ?? 500;
if (Request::wantsJson()) {
http_response_code($status);
Router::json(['error' => $error]);
return;
}
2026-02-04 23:31:53 +01:00
if ($error === 'admin_role_protected') {
Flash::error('The Admin role cannot be deleted', 'admin/roles', 'admin_role_protected');
} else {
Flash::error('Role not found', 'admin/roles', 'role_not_found');
}
Router::redirect('admin/roles');
return;
2026-02-04 23:31:53 +01:00
}
2026-03-04 15:56:58 +01:00
if ($affectedUserIds) {
app(\MintyPHP\Repository\User\UserWriteRepository::class)->bumpAuthzVersionByUserIds($affectedUserIds);
}
if (Request::wantsJson()) {
http_response_code(204);
Router::json([]);
return;
}
2026-02-04 23:31:53 +01:00
Flash::success('Role deleted', 'admin/roles', 'role_deleted');
Router::redirect('admin/roles');