assign role roles

This commit is contained in:
2026-03-13 21:11:48 +01:00
parent b89fd792bf
commit aaea038619
20 changed files with 495 additions and 11 deletions

View File

@@ -277,6 +277,16 @@ CREATE TABLE IF NOT EXISTS `role_permissions` (
CONSTRAINT `fk_role_permissions_permission` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `role_assignable_roles` (
`role_id` INT UNSIGNED NOT NULL,
`assignable_role_id` INT UNSIGNED NOT NULL,
`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`role_id`, `assignable_role_id`),
KEY `idx_rar_assignable` (`assignable_role_id`),
CONSTRAINT `fk_rar_role` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_rar_assignable` FOREIGN KEY (`assignable_role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `user_departments` (
`user_id` INT UNSIGNED NOT NULL,
`department_id` INT UNSIGNED NOT NULL,
@@ -768,6 +778,18 @@ INSERT INTO `roles` (`uuid`, `description`, `code`, `active`, `created`)
SELECT UUID(), 'User', 'USER', 1, NOW()
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'USER');
INSERT INTO `roles` (`uuid`, `description`, `code`, `active`, `created`)
SELECT UUID(), 'Manager', 'MANAGER', 1, NOW()
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'MANAGER');
INSERT INTO `roles` (`uuid`, `description`, `code`, `active`, `created`)
SELECT UUID(), 'Auditor', 'AUDITOR', 1, NOW()
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'AUDITOR');
INSERT INTO `roles` (`uuid`, `description`, `code`, `active`, `created`)
SELECT UUID(), 'Support', 'SUPPORT', 1, NOW()
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'SUPPORT');
INSERT INTO `users` (
`uuid`,
`first_name`,
@@ -989,7 +1011,8 @@ VALUES
('system_audit.view', 'Can view system audit logs', 1, 1),
('system_audit.purge', 'Can purge system audit logs', 1, 1),
('api_tokens.manage', 'Can manage user API tokens', 1, 1),
('stats.view', 'Can view statistics', 1, 1)
('stats.view', 'Can view statistics', 1, 1),
('roles.assign_all', 'Can assign all roles (bypass assignable-roles check)', 1, 1)
ON DUPLICATE KEY UPDATE
`description` = VALUES(`description`),
`active` = VALUES(`active`),
@@ -1089,7 +1112,8 @@ JOIN permissions p ON p.`key` IN (
'api_docs.view', 'docs.view',
'api_tokens.manage',
'mail_log.view', 'api_audit.view', 'system_audit.view', 'system_audit.purge',
'stats.view'
'stats.view',
'roles.assign_all'
)
WHERE r.description IN ('Admin', 'Administrator') OR r.id = 1
ON DUPLICATE KEY UPDATE role_id = role_id;
@@ -1101,6 +1125,68 @@ JOIN permissions p ON p.`key` IN ('users.self_update', 'address_book.view')
WHERE r.code = 'USER' OR r.description = 'User'
ON DUPLICATE KEY UPDATE role_id = role_id;
-- Manager: user & department management
INSERT INTO `role_permissions` (`role_id`, `permission_id`, `created`)
SELECT r.id, p.id, NOW()
FROM roles r
JOIN permissions p ON p.`key` IN (
'users.view', 'users.view_meta', 'users.create', 'users.update',
'users.update_assignments', 'users.access_pdf', 'users.self_update',
'users.import', 'users.import_assignments',
'address_book.view',
'departments.view', 'departments.create', 'departments.update',
'roles.view',
'custom_fields.edit_values'
)
WHERE r.code = 'MANAGER'
ON DUPLICATE KEY UPDATE role_id = role_id;
-- Auditor: read-only + audit logs
INSERT INTO `role_permissions` (`role_id`, `permission_id`, `created`)
SELECT r.id, p.id, NOW()
FROM roles r
JOIN permissions p ON p.`key` IN (
'users.view', 'users.view_meta', 'users.view_audit', 'users.self_update',
'address_book.view',
'tenants.view', 'departments.view', 'roles.view', 'permissions.view',
'settings.view',
'imports.view', 'imports.audit.view',
'user_lifecycle_audit.view',
'mail_log.view', 'api_audit.view', 'system_audit.view',
'stats.view', 'jobs.view'
)
WHERE r.code = 'AUDITOR'
ON DUPLICATE KEY UPDATE role_id = role_id;
-- Support: helpdesk / user support
INSERT INTO `role_permissions` (`role_id`, `permission_id`, `created`)
SELECT r.id, p.id, NOW()
FROM roles r
JOIN permissions p ON p.`key` IN (
'users.view', 'users.view_meta', 'users.view_audit',
'users.update', 'users.self_update',
'address_book.view',
'departments.view', 'roles.view',
'api_tokens.manage',
'custom_fields.edit_values'
)
WHERE r.code = 'SUPPORT'
ON DUPLICATE KEY UPDATE role_id = role_id;
-- Admin role can assign every role (also has roles.assign_all permission as fallback)
INSERT IGNORE INTO `role_assignable_roles` (`role_id`, `assignable_role_id`)
SELECT admin_role.id, all_roles.id
FROM roles admin_role
CROSS JOIN roles all_roles
WHERE admin_role.description IN ('Admin', 'Administrator') OR admin_role.id = 1;
-- Manager can assign USER and SUPPORT roles
INSERT IGNORE INTO `role_assignable_roles` (`role_id`, `assignable_role_id`)
SELECT mgr.id, target.id
FROM roles mgr
JOIN roles target ON target.code IN ('USER', 'SUPPORT')
WHERE mgr.code = 'MANAGER';
INSERT INTO `settings` (`key`, `value`, `description`)
SELECT 'default_tenant_id', CAST(t.id AS CHAR), 'setting.default_tenant'
FROM tenants t

View File

@@ -0,0 +1,31 @@
-- Idempotent update: introduce assignable-roles mapping for privilege-escalation prevention.
-- Each role defines which other roles its members may assign to users.
CREATE TABLE IF NOT EXISTS `role_assignable_roles` (
`role_id` INT UNSIGNED NOT NULL,
`assignable_role_id` INT UNSIGNED NOT NULL,
`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`role_id`, `assignable_role_id`),
KEY `idx_rar_assignable` (`assignable_role_id`),
CONSTRAINT `fk_rar_role` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_rar_assignable` FOREIGN KEY (`assignable_role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Permission: bypass assignable-roles check (super-admin)
INSERT INTO `permissions` (`key`, `description`, `active`, `is_system`)
VALUES ('roles.assign_all', 'permission.roles.assign_all', 1, 1)
ON DUPLICATE KEY UPDATE `key` = `key`;
-- Grant roles.assign_all to the ADMIN role
INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.`key` = 'roles.assign_all'
WHERE r.code = 'ADMIN';
-- Seed: ADMIN role can assign every existing role
INSERT IGNORE INTO `role_assignable_roles` (`role_id`, `assignable_role_id`)
SELECT admin_role.id, all_roles.id
FROM roles admin_role
CROSS JOIN roles all_roles
WHERE admin_role.code = 'ADMIN';

View File

@@ -0,0 +1,81 @@
-- ============================================================
-- 2026-03-13 Seed default roles: MANAGER, AUDITOR, SUPPORT
-- Idempotent — safe to run multiple times.
-- ============================================================
-- 1. Create new roles (skip if already present)
INSERT INTO `roles` (`uuid`, `description`, `code`, `active`, `created`)
SELECT UUID(), 'Manager', 'MANAGER', 1, NOW()
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'MANAGER');
INSERT INTO `roles` (`uuid`, `description`, `code`, `active`, `created`)
SELECT UUID(), 'Auditor', 'AUDITOR', 1, NOW()
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'AUDITOR');
INSERT INTO `roles` (`uuid`, `description`, `code`, `active`, `created`)
SELECT UUID(), 'Support', 'SUPPORT', 1, NOW()
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'SUPPORT');
-- 2. MANAGER permissions (15)
INSERT INTO `role_permissions` (`role_id`, `permission_id`, `created`)
SELECT r.id, p.id, NOW()
FROM roles r
JOIN permissions p ON p.`key` IN (
'users.view', 'users.view_meta', 'users.create', 'users.update',
'users.update_assignments', 'users.access_pdf', 'users.self_update',
'users.import', 'users.import_assignments',
'address_book.view',
'departments.view', 'departments.create', 'departments.update',
'roles.view',
'custom_fields.edit_values'
)
WHERE r.code = 'MANAGER'
ON DUPLICATE KEY UPDATE role_id = role_id;
-- 3. AUDITOR permissions (18)
INSERT INTO `role_permissions` (`role_id`, `permission_id`, `created`)
SELECT r.id, p.id, NOW()
FROM roles r
JOIN permissions p ON p.`key` IN (
'users.view', 'users.view_meta', 'users.view_audit', 'users.self_update',
'address_book.view',
'tenants.view', 'departments.view', 'roles.view', 'permissions.view',
'settings.view',
'imports.view', 'imports.audit.view',
'user_lifecycle_audit.view',
'mail_log.view', 'api_audit.view', 'system_audit.view',
'stats.view', 'jobs.view'
)
WHERE r.code = 'AUDITOR'
ON DUPLICATE KEY UPDATE role_id = role_id;
-- 4. SUPPORT permissions (10)
INSERT INTO `role_permissions` (`role_id`, `permission_id`, `created`)
SELECT r.id, p.id, NOW()
FROM roles r
JOIN permissions p ON p.`key` IN (
'users.view', 'users.view_meta', 'users.view_audit',
'users.update', 'users.self_update',
'address_book.view',
'departments.view', 'roles.view',
'api_tokens.manage',
'custom_fields.edit_values'
)
WHERE r.code = 'SUPPORT'
ON DUPLICATE KEY UPDATE role_id = role_id;
-- 5. MANAGER can assign USER and SUPPORT roles
INSERT IGNORE INTO `role_assignable_roles` (`role_id`, `assignable_role_id`)
SELECT mgr.id, target.id
FROM roles mgr
JOIN roles target ON target.code IN ('USER', 'SUPPORT')
WHERE mgr.code = 'MANAGER';
-- 6. Ensure ADMIN assignable_roles includes the new roles
-- (previous migration only seeded roles that existed at that time)
INSERT IGNORE INTO `role_assignable_roles` (`role_id`, `assignable_role_id`)
SELECT admin_role.id, new_role.id
FROM roles admin_role
CROSS JOIN roles new_role
WHERE (admin_role.description IN ('Admin', 'Administrator') OR admin_role.id = 1)
AND new_role.code IN ('MANAGER', 'AUDITOR', 'SUPPORT');

View File

@@ -184,6 +184,7 @@
"perm.roles.create": "Rollen erstellen",
"perm.roles.update": "Rollen bearbeiten",
"perm.roles.delete": "Rollen löschen",
"perm.roles.assign_all": "Alle Rollen zuweisen",
"perm.permissions.view": "Berechtigungen anzeigen",
"perm.permissions.create": "Berechtigungen erstellen",
"perm.permissions.update": "Berechtigungen bearbeiten",
@@ -533,6 +534,7 @@
"Role": "Rolle",
"Roles": "Rollen",
"No roles available": "Keine Rollen verfügbar",
"Assignable roles": "Zuweisbare Rollen",
"Create role": "Rolle anlegen",
"Edit role": "Rolle bearbeiten",
"Role created": "Rolle erstellt",

View File

@@ -184,6 +184,7 @@
"perm.roles.create": "Create roles",
"perm.roles.update": "Update roles",
"perm.roles.delete": "Delete roles",
"perm.roles.assign_all": "Assign all roles",
"perm.permissions.view": "View permissions",
"perm.permissions.create": "Create permissions",
"perm.permissions.update": "Update permissions",
@@ -533,6 +534,7 @@
"Role": "Role",
"Roles": "Roles",
"No roles available": "No roles available",
"Assignable roles": "Assignable roles",
"Create role": "Create role",
"Edit role": "Edit role",
"Role created": "Role created",

View File

@@ -5,13 +5,16 @@ namespace MintyPHP\App\Container\Registrars;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Container\ContainerRegistrar;
use MintyPHP\Repository\Access\PermissionRepository;
use MintyPHP\Repository\Access\RoleAssignableRoleRepository;
use MintyPHP\Repository\Access\RolePermissionRepository;
use MintyPHP\Repository\Access\RoleRepository;
use MintyPHP\Service\Access\AccessServicesFactory;
use MintyPHP\Service\Access\AssignableRoleService;
use MintyPHP\Service\Access\AuthorizationService;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Access\RoleService;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Service\Audit\SystemAuditService;
use MintyPHP\Service\Directory\DirectoryServicesFactory;
final class AccessRegistrar implements ContainerRegistrar
@@ -28,6 +31,14 @@ final class AccessRegistrar implements ContainerRegistrar
$container->set(RoleService::class, static fn (AppContainer $c): RoleService => $c->get(DirectoryServicesFactory::class)->createRoleService());
$container->set(PermissionRepository::class, static fn (AppContainer $c): PermissionRepository => $c->get(AccessServicesFactory::class)->createPermissionRepository());
$container->set(RolePermissionRepository::class, static fn (AppContainer $c): RolePermissionRepository => $c->get(AccessServicesFactory::class)->createRolePermissionRepository());
$container->set(RoleAssignableRoleRepository::class, static fn (AppContainer $c): RoleAssignableRoleRepository => $c->get(AccessServicesFactory::class)->createRoleAssignableRoleRepository());
$container->set(RoleRepository::class, static fn (AppContainer $c): RoleRepository => $c->get(DirectoryServicesFactory::class)->createRoleRepository());
$container->set(AssignableRoleService::class, static fn (AppContainer $c): AssignableRoleService => new AssignableRoleService(
$c->get(RoleAssignableRoleRepository::class),
$c->get(AccessServicesFactory::class)->createUserRoleRepository(),
$c->get(PermissionService::class),
$c->get(RoleRepository::class),
$c->get(SystemAuditService::class)
));
}
}

View File

@@ -38,6 +38,7 @@ use MintyPHP\Service\Settings\SettingServicesFactory;
use MintyPHP\Service\Tenant\TenantRepositoryFactory;
use MintyPHP\Service\Tenant\TenantScopeService;
use MintyPHP\Service\Tenant\TenantServicesFactory;
use MintyPHP\Service\Access\AssignableRoleService;
use MintyPHP\Service\User\UserGatewayFactory;
use MintyPHP\Service\User\UserRepositoryFactory;
use MintyPHP\Service\User\UserServicesFactory;
@@ -130,7 +131,10 @@ final class ServiceFactoryRegistrar implements ContainerRegistrar
$c->get(AuditServicesFactory::class),
$c->get(UserRepositoryFactory::class),
$c->get(UserGatewayFactory::class),
$c->get(DatabaseSessionRepository::class)
$c->get(DatabaseSessionRepository::class),
// Wrapped in a closure to break circular dependency:
// UserServicesFactory -> AssignableRoleService -> RoleRepository -> DirectoryServicesFactory -> UserServicesFactory
static fn (): AssignableRoleService => $c->get(AssignableRoleService::class)
));
$container->set(AuthGatewayFactory::class, static fn (AppContainer $c): AuthGatewayFactory => new AuthGatewayFactory(
$c->get(AuthRepositoryFactory::class),

View File

@@ -0,0 +1,74 @@
<?php
namespace MintyPHP\Repository\Access;
use MintyPHP\DB;
class RoleAssignableRoleRepository implements RoleAssignableRoleRepositoryInterface
{
public function listAssignableRoleIdsByRoleId(int $roleId): array
{
$rows = DB::select(
'select assignable_role_id from role_assignable_roles where role_id = ?',
(string) $roleId
);
if (!is_array($rows)) {
return [];
}
$ids = [];
foreach ($rows as $row) {
$data = $row['role_assignable_roles'] ?? $row;
if (is_array($data) && isset($data['assignable_role_id'])) {
$ids[] = (int) $data['assignable_role_id'];
}
}
return array_values(array_unique($ids));
}
public function listAssignableRoleIdsByRoleIds(array $roleIds): array
{
$roleIds = array_values(array_unique(array_map('intval', $roleIds)));
$roleIds = array_values(array_filter($roleIds, static fn (int $id): bool => $id > 0));
if (!$roleIds) {
return [];
}
$placeholders = implode(',', array_fill(0, count($roleIds), '?'));
$rows = DB::select(
'select distinct assignable_role_id from role_assignable_roles where role_id in (' .
$placeholders .
')',
...array_map('strval', $roleIds)
);
if (!is_array($rows)) {
return [];
}
$ids = [];
foreach ($rows as $row) {
$data = $row['role_assignable_roles'] ?? $row;
if (is_array($data) && isset($data['assignable_role_id'])) {
$ids[] = (int) $data['assignable_role_id'];
}
}
return array_values(array_unique($ids));
}
public function replaceForRole(int $roleId, array $assignableRoleIds): bool
{
DB::delete('delete from role_assignable_roles where role_id = ?', (string) $roleId);
$ids = array_values(array_unique(array_filter(array_map('intval', $assignableRoleIds))));
if (!$ids) {
return true;
}
foreach ($ids as $assignableRoleId) {
DB::insert(
'insert into role_assignable_roles (role_id, assignable_role_id, created) values (?,?,NOW())',
(string) $roleId,
(string) $assignableRoleId
);
}
return true;
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace MintyPHP\Repository\Access;
interface RoleAssignableRoleRepositoryInterface
{
/** @return int[] */
public function listAssignableRoleIdsByRoleId(int $roleId): array;
/**
* Union of assignable role IDs across multiple roles (e.g. all roles of an actor).
* @param int[] $roleIds
* @return int[]
*/
public function listAssignableRoleIdsByRoleIds(array $roleIds): array;
/**
* Atomic replace: delete all + re-insert.
* @param int[] $assignableRoleIds
*/
public function replaceForRole(int $roleId, array $assignableRoleIds): bool;
}

View File

@@ -4,6 +4,8 @@ namespace MintyPHP\Service\Access;
use MintyPHP\Repository\Access\PermissionRepository;
use MintyPHP\Repository\Access\PermissionRepositoryInterface;
use MintyPHP\Repository\Access\RoleAssignableRoleRepository;
use MintyPHP\Repository\Access\RoleAssignableRoleRepositoryInterface;
use MintyPHP\Repository\Access\RolePermissionRepository;
use MintyPHP\Repository\Access\RolePermissionRepositoryInterface;
use MintyPHP\Repository\Access\UserRoleRepository;
@@ -13,6 +15,7 @@ class AccessRepositoryFactory
{
private ?PermissionRepository $permissionRepository = null;
private ?RolePermissionRepository $rolePermissionRepository = null;
private ?RoleAssignableRoleRepository $roleAssignableRoleRepository = null;
private ?UserRoleRepository $userRoleRepository = null;
public function createPermissionRepository(): PermissionRepositoryInterface
@@ -25,6 +28,11 @@ class AccessRepositoryFactory
return $this->rolePermissionRepository ??= new RolePermissionRepository();
}
public function createRoleAssignableRoleRepository(): RoleAssignableRoleRepositoryInterface
{
return $this->roleAssignableRoleRepository ??= new RoleAssignableRoleRepository();
}
public function createUserRoleRepository(): UserRoleRepositoryInterface
{
return $this->userRoleRepository ??= new UserRoleRepository();

View File

@@ -3,6 +3,7 @@
namespace MintyPHP\Service\Access;
use MintyPHP\Repository\Access\PermissionRepositoryInterface;
use MintyPHP\Repository\Access\RoleAssignableRoleRepositoryInterface;
use MintyPHP\Repository\Access\RolePermissionRepositoryInterface;
use MintyPHP\Repository\Access\UserRoleRepositoryInterface;
@@ -34,6 +35,11 @@ class AccessServicesFactory
return $this->accessRepositoryFactory->createUserRoleRepository();
}
public function createRoleAssignableRoleRepository(): RoleAssignableRoleRepositoryInterface
{
return $this->accessRepositoryFactory->createRoleAssignableRoleRepository();
}
public function createPermissionService(): PermissionService
{
return $this->accessGatewayFactory->createPermissionService();

View File

@@ -0,0 +1,101 @@
<?php
namespace MintyPHP\Service\Access;
use MintyPHP\Repository\Access\RoleAssignableRoleRepositoryInterface;
use MintyPHP\Repository\Access\RoleRepositoryInterface;
use MintyPHP\Repository\Access\UserRoleRepositoryInterface;
use MintyPHP\Service\Audit\SystemAuditService;
class AssignableRoleService
{
public function __construct(
private readonly RoleAssignableRoleRepositoryInterface $assignableRoleRepository,
private readonly UserRoleRepositoryInterface $userRoleRepository,
private readonly PermissionService $permissionService,
private readonly RoleRepositoryInterface $roleRepository,
private readonly SystemAuditService $systemAuditService
) {
}
/**
* Returns role IDs the given actor is allowed to assign.
* Users with 'roles.assign_all' get all active role IDs.
* Otherwise: union of assignable_role_ids from all of the actor's roles.
*
* @return int[]
*/
public function listAssignableRoleIdsForActor(int $actorUserId): array
{
if ($actorUserId <= 0) {
return [];
}
if ($this->permissionService->userHas($actorUserId, PermissionService::ROLES_ASSIGN_ALL)) {
return $this->roleRepository->listActiveIds();
}
$actorRoleIds = $this->userRoleRepository->listRoleIdsByUserId($actorUserId);
if (!$actorRoleIds) {
return [];
}
return $this->assignableRoleRepository->listAssignableRoleIdsByRoleIds($actorRoleIds);
}
/**
* Computes the effective role set respecting the actor's assignable scope.
*
* Roles the actor cannot assign are "frozen" — they remain as-is.
* frozen = currentIds ∩ NOT-assignable
* touched = submittedIds ∩ assignable
* result = frozen touched
*
* @param int[] $submittedIds Role IDs the form submitted
* @param int[] $currentIds Role IDs the target user currently has
* @return int[]
*/
public function computeEffectiveRoleIds(int $actorUserId, array $submittedIds, array $currentIds): array
{
$assignable = $this->listAssignableRoleIdsForActor($actorUserId);
$assignableMap = array_fill_keys($assignable, true);
// Roles the actor cannot touch — keep them as they are.
$frozen = array_values(array_filter(
$currentIds,
static fn (int $id): bool => !isset($assignableMap[$id])
));
// From the submitted set, only keep roles the actor is allowed to assign.
$touched = array_values(array_filter(
$submittedIds,
static fn (int $id): bool => isset($assignableMap[$id])
));
return array_values(array_unique(array_merge($frozen, $touched)));
}
/**
* Saves which roles this role can assign (admin UI) and logs the change.
*
* @param int[] $assignableRoleIds
*/
public function replaceAssignableRoles(int $roleId, array $assignableRoleIds, int $actorUserId): bool
{
$beforeIds = $this->assignableRoleRepository->listAssignableRoleIdsByRoleId($roleId);
$result = $this->assignableRoleRepository->replaceForRole($roleId, $assignableRoleIds);
$afterIds = $this->assignableRoleRepository->listAssignableRoleIdsByRoleId($roleId);
if ($beforeIds !== $afterIds) {
$this->systemAuditService->record('admin.roles.assignable_roles.update', 'success', [
'actor_user_id' => $actorUserId > 0 ? $actorUserId : null,
'target_type' => 'role',
'target_id' => $roleId,
'before' => ['assignable_role_ids' => $beforeIds],
'after' => ['assignable_role_ids' => $afterIds],
]);
}
return $result;
}
}

View File

@@ -45,6 +45,7 @@ class PermissionService
public const ROLES_CREATE = 'roles.create';
public const ROLES_UPDATE = 'roles.update';
public const ROLES_DELETE = 'roles.delete';
public const ROLES_ASSIGN_ALL = 'roles.assign_all';
public const PERMISSIONS_VIEW = 'permissions.view';
public const PERMISSIONS_CREATE = 'permissions.create';
public const PERMISSIONS_UPDATE = 'permissions.update';

View File

@@ -7,6 +7,7 @@ use MintyPHP\Repository\Org\UserDepartmentRepositoryInterface;
use MintyPHP\Repository\Support\DatabaseSessionRepository;
use MintyPHP\Repository\Tenant\UserTenantRepositoryInterface;
use MintyPHP\Repository\User\UserWriteRepositoryInterface;
use MintyPHP\Service\Access\AssignableRoleService;
use MintyPHP\Service\Access\PermissionService;
class UserAssignmentService
@@ -18,7 +19,8 @@ class UserAssignmentService
private readonly UserDepartmentRepositoryInterface $userDepartmentRepository,
private readonly UserDirectoryGateway $directoryGateway,
private readonly PermissionService $permissionService,
private readonly DatabaseSessionRepository $databaseSessionRepository
private readonly DatabaseSessionRepository $databaseSessionRepository,
private readonly AssignableRoleService $assignableRoleService
) {
}
@@ -172,7 +174,7 @@ class UserAssignmentService
return $result;
}
public function syncRoles(int $userId, array $roleIds, bool $bumpAuthz = true): bool
public function syncRoles(int $userId, array $roleIds, bool $bumpAuthz = true, int $actorUserId = 0): bool
{
$ids = array_values(array_unique(array_map('intval', $roleIds)));
$ids = array_values(array_filter($ids, static fn ($id) => $id > 0));
@@ -181,6 +183,14 @@ class UserAssignmentService
$validMap = array_fill_keys($validIds, true);
$ids = array_values(array_filter($ids, static fn ($id) => isset($validMap[$id])));
}
// Enforce assignable-roles: the actor can only touch roles within their assignable set.
// Roles outside the set are "frozen" and remain as-is on the target user.
if ($actorUserId > 0) {
$currentRoleIds = $this->userRoleRepository->listRoleIdsByUserId($userId);
$ids = $this->assignableRoleService->computeEffectiveRoleIds($actorUserId, $ids, $currentRoleIds);
}
$result = $this->userRoleRepository->replaceForUser($userId, $ids);
$this->permissionService->clearUserCache($userId);
if ($result && $bumpAuthz) {
@@ -228,7 +238,7 @@ class UserAssignmentService
$this->userWriteRepository->bumpAuthzVersion($userId);
}
public function syncAllAssignments(int $userId, array $tenantIds, array $roleIds, array $departmentIds): bool
public function syncAllAssignments(int $userId, array $tenantIds, array $roleIds, array $departmentIds, int $actorUserId = 0): bool
{
if ($userId <= 0) {
return false;
@@ -241,7 +251,7 @@ class UserAssignmentService
// bumpAuthz=false on each sync — bump once at the end to avoid redundant DB writes.
$ok = $this->syncTenants($userId, $tenantIds, false)
&& $this->syncRoles($userId, $roleIds, false)
&& $this->syncRoles($userId, $roleIds, false, $actorUserId)
&& $this->syncDepartments($userId, $departmentIds, false);
if (!$ok) {
$this->rollbackQuietly();

View File

@@ -10,6 +10,7 @@ use MintyPHP\Repository\User\UserListQueryRepositoryInterface;
use MintyPHP\Repository\User\UserReadRepositoryInterface;
use MintyPHP\Repository\User\UserSavedFilterRepositoryInterface;
use MintyPHP\Repository\User\UserWriteRepositoryInterface;
use MintyPHP\Service\Access\AssignableRoleService;
use MintyPHP\Service\Audit\AuditServicesFactory;
use MintyPHP\Service\Audit\UserLifecycleAuditService;
@@ -26,11 +27,15 @@ class UserServicesFactory
private ?UserLifecycleRestoreService $userLifecycleRestoreService = null;
private ?UserLifecycleAuditService $userLifecycleAuditService = null;
/**
* @param \Closure(): AssignableRoleService $assignableRoleServiceFactory Lazy resolver to break circular dependency
*/
public function __construct(
private readonly AuditServicesFactory $auditServicesFactory,
private readonly UserRepositoryFactory $userRepositoryFactory,
private readonly UserGatewayFactory $userGatewayFactory,
private readonly DatabaseSessionRepository $databaseSessionRepository
private readonly DatabaseSessionRepository $databaseSessionRepository,
private readonly \Closure $assignableRoleServiceFactory
) {
}
@@ -59,7 +64,8 @@ class UserServicesFactory
$this->createUserDepartmentRepository(),
$this->createUserDirectoryGateway(),
$this->userGatewayFactory->createPermissionService(),
$this->databaseSessionRepository
$this->databaseSessionRepository,
($this->assignableRoleServiceFactory)()
);
}

View File

@@ -26,6 +26,8 @@ $readonlyAttr = $isReadOnly ? 'readonly' : '';
$disabledAttr = $isReadOnly ? 'disabled' : '';
$permissions = is_array($permissions ?? null) ? $permissions : [];
$selectedPermissionIds = is_array($selectedPermissionIds ?? null) ? $selectedPermissionIds : [];
$allRolesForAssignable = is_array($allRolesForAssignable ?? null) ? $allRolesForAssignable : [];
$selectedAssignableRoleIds = is_array($selectedAssignableRoleIds ?? null) ? $selectedAssignableRoleIds : [];
?>
<form id="<?php e($formId); ?>" method="post" data-standard-detail-form="1">
@@ -33,6 +35,7 @@ $selectedPermissionIds = is_array($selectedPermissionIds ?? null) ? $selectedPer
<div class="app-tabs-nav">
<button type="button" data-tab="basic" data-tab-default><?php e(t('Master data')); ?></button>
<button type="button" data-tab="permissions"><?php e(t('Permissions')); ?></button>
<button type="button" data-tab="assignable-roles"><?php e(t('Assignable roles')); ?></button>
<button type="button" data-tab="visibility"><?php e(t('Visibility')); ?></button>
<?php if ($showDangerZone && $dangerZoneDeleteFormId !== ''): ?>
<button type="button" data-tab="danger"><?php e(t('Danger zone')); ?></button>
@@ -69,6 +72,21 @@ $selectedPermissionIds = is_array($selectedPermissionIds ?? null) ? $selectedPer
<?php endif; ?>
</div>
<div data-tab-panel="assignable-roles">
<?php if ($allRolesForAssignable): ?>
<?php multiSelectForm('role-assignable-roles', 'assignable_role_ids', 'Assignable roles', 'Select roles', $allRolesForAssignable, $selectedAssignableRoleIds, $isReadOnly, 'description'); ?>
<?php else: ?>
<?php
$emptyState = [
'message' => t('No roles available'),
'hint' => t('No active roles are configured yet.'),
'size' => 'compact',
];
require templatePath('partials/app-empty-state.phtml');
?>
<?php endif; ?>
</div>
<div data-tab-panel="visibility">
<?php
$statusFieldName = 'active';

View File

@@ -47,6 +47,10 @@ $errors = [];
$form = $role;
$permissions = $permissionRepository->listActive();
$selectedPermissionIds = $rolePermissionRepository->listPermissionIdsByRoleId($roleId);
$assignableRoleService = app(\MintyPHP\Service\Access\AssignableRoleService::class);
$assignableRoleRepo = app(\MintyPHP\Repository\Access\RoleAssignableRoleRepository::class);
$allRolesForAssignable = app(\MintyPHP\Service\Access\RoleService::class)->listActive();
$selectedAssignableRoleIds = $assignableRoleRepo->listAssignableRoleIdsByRoleId($roleId);
if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
Flash::error(t('Form expired, please try again'), $editTarget, 'csrf_expired');
@@ -70,6 +74,11 @@ if ($request->hasBody('description')) {
$selectedPermissionIds = [$selectedPermissionIds];
}
$selectedPermissionIds = array_values(array_unique(array_map('intval', $selectedPermissionIds)));
$selectedAssignableRoleIds = $request->body('assignable_role_ids', $selectedAssignableRoleIds);
if (!is_array($selectedAssignableRoleIds)) {
$selectedAssignableRoleIds = [$selectedAssignableRoleIds];
}
$selectedAssignableRoleIds = array_values(array_unique(array_map('intval', $selectedAssignableRoleIds)));
if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
$permissionIds = $request->body('permission_ids', []);
@@ -82,6 +91,7 @@ if ($request->hasBody('description')) {
$dbSession->beginTransaction();
try {
$rolePermissionRepository->replaceForRole($roleId, $permissionIds);
$assignableRoleService->replaceAssignableRoles($roleId, $selectedAssignableRoleIds, $currentUserId);
$affectedUserIds = $userRoleRepository->listUserIdsByRoleIds([$roleId]);
if ($affectedUserIds) {
$userWriteRepository->bumpAuthzVersionByUserIds($affectedUserIds);

View File

@@ -56,6 +56,7 @@ $selectedTenantIds = $selectedTenantIds ?? [];
$showRoles = $showRoles ?? false;
$roles = $roles ?? [];
$selectedRoleIds = $selectedRoleIds ?? [];
$visibleSelectedRoleIds = $visibleSelectedRoleIds ?? $selectedRoleIds;
$showDepartments = $showDepartments ?? false;
$departmentOptionsByTenant = $departmentOptionsByTenant ?? [];
$selectedDepartmentIds = $selectedDepartmentIds ?? [];
@@ -681,7 +682,7 @@ foreach ($tenants as $tenant) {
require templatePath('partials/app-empty-state.phtml');
?>
<?php else: ?>
<?php multiSelectForm('user-roles', 'role_ids', 'Assigned roles', 'Select roles', $roles, $selectedRoleIds, $isReadOnly); ?>
<?php multiSelectForm('user-roles', 'role_ids', 'Assigned roles', 'Select roles', $roles, $visibleSelectedRoleIds, $isReadOnly); ?>
<?php endif; ?>
</details>
<?php endif; ?>

View File

@@ -62,6 +62,10 @@ if ($allowedTenantIds) {
$tenants = [];
}
$roles = $roleService->listActive();
$assignableRoleService = app(\MintyPHP\Service\Access\AssignableRoleService::class);
$assignableRoleIds = $assignableRoleService->listAssignableRoleIdsForActor($currentUserId);
$assignableRoleIdMap = array_fill_keys($assignableRoleIds, true);
$roles = array_values(array_filter($roles, static fn (array $r): bool => isset($assignableRoleIdMap[(int) ($r['id'] ?? 0)])));
$selectedTenantIds = [];
$selectedRoleIds = [];
$selectedDepartmentIds = [];

View File

@@ -117,7 +117,12 @@ if (!$primaryTenantId && count($selectedTenantIds) === 1) {
}
$roles = $roleService->listActive();
$assignableRoleService = app(\MintyPHP\Service\Access\AssignableRoleService::class);
$assignableRoleIds = $assignableRoleService->listAssignableRoleIdsForActor($currentUserId);
$assignableRoleIdMap = array_fill_keys($assignableRoleIds, true);
$roles = array_values(array_filter($roles, static fn (array $r): bool => isset($assignableRoleIdMap[(int) ($r['id'] ?? 0)])));
$selectedRoleIds = $userRoleRepository->listRoleIdsByUserId($userId);
$visibleSelectedRoleIds = array_values(array_intersect($selectedRoleIds, $assignableRoleIds));
$permissionRows = $canViewPermissionsTable
? $rolePermissionRepository->listPermissionsWithRolesByRoleIds($selectedRoleIds)
: [];
@@ -233,7 +238,8 @@ if ($request->hasBody('email')) {
$userId,
$tenantIdsForSync,
$selectedRoleIds,
$selectedDepartmentIds
$selectedDepartmentIds,
$currentUserId
);
if (!$assignmentsSynced) {
$errorBag->addGlobal(t('User assignments can not be updated'));