mgomezbuceta / cakephp-aclmanager
Modern Authorization Manager for CakePHP 5.x - Role-based permission management system
Installs: 17
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 1
Type:cakephp-plugin
pkg:composer/mgomezbuceta/cakephp-aclmanager
Requires
- php: >=8.1
- cakephp/authorization: ^3.0
- cakephp/cakephp: ^5.0
Requires (Dev)
- cakephp/cakephp-codesniffer: ^5.0
- phpunit/phpunit: ^10.0
README
π CakePHP Authorization Manager
Modern Role-Based Permission Management for CakePHP 5.x
A powerful, modern web interface for managing role-based permissions using CakePHP's Authorization plugin.
Features β’ Installation β’ Quick Start β’ Documentation β’ Migration
π Features
π‘ Why Authorization Manager?
Traditional ACL systems (acos/aros) are deprecated in CakePHP 5.x. This plugin provides:
- β Modern Authorization - Uses CakePHP's official Authorization plugin
- β Simplified Structure - No more complex ACO/ARO trees
- β Visual Management - Web interface for managing permissions
- β Role-Based - Industry-standard RBAC pattern
- β Easy Integration - Drop-in authorization solution
- β Multilingual - Spanish and Galician translations included
π Requirements
| Requirement | Version |
|---|---|
| PHP | β₯ 8.1 |
| CakePHP | β₯ 5.0 |
| CakePHP Authorization | β₯ 3.0 |
π Installation
Step 1: Install via Composer
composer require mgomezbuceta/cakephp-aclmanager composer require cakephp/authorization
Step 2: Load the Plugin
Add to your src/Application.php:
public function bootstrap(): void { parent::bootstrap(); $this->addPlugin('AclManager', ['bootstrap' => true, 'routes' => true]); }
Step 3: Run Migrations
bin/cake migrations migrate -p AclManager
Step 4: Sync Resources
Visit /authorization-manager and click "Sync Resources" to discover all your controllers and actions.
That's it! π
β‘ Quick Start
Basic Setup
-
Create Roles
- Visit
/authorization-manager/roles - Click "New Role"
- Create roles like: Administrator, Editor, Viewer
- Visit
-
Assign Permissions
- Click "Manage Permissions" for a role
- Check/uncheck permissions for each controller/action
- Click "Save Permissions"
-
Integrate with Your Auth
// In your AppController or specific controller public function initialize(): void { parent::initialize(); $this->loadComponent('AclManager.AuthorizationManager', [ 'userModel' => 'Users', 'roleField' => 'role_id' ]); } public function isAuthorized($user = null): bool { return $this->AuthorizationManager->isAuthorized($user); }
Add role_id to Your Users Table
ALTER TABLE users ADD COLUMN role_id INT NOT NULL; ALTER TABLE users ADD FOREIGN KEY (role_id) REFERENCES roles(id);
π Documentation
π§ Configuration Options
Admin Access Control
IMPORTANT: By default, only administrators can access the Authorization Manager.
The plugin checks if the user is an admin using multiple methods (in order):
- role_name: Checks if
role_nameis 'admin', 'administrator', or 'superadmin' - role_id: Checks if
role_id == 1(typically admin role) - is_admin: Checks if
is_adminflag is true - email: Checks against a whitelist of admin emails
To customize admin access, add to your config/app.php in the return array:
// In config/app.php, add to the return array: return [ // ... existing configuration ... 'AclManager' => [ 'adminAccess' => [ // Which role IDs can access the Authorization Manager 'adminRoleIds' => [1, 2], // Allow role IDs 1 and 2 // Which role names can access 'adminRoleNames' => ['admin', 'superuser'], // Specific emails (useful for initial setup) 'adminEmails' => [ 'admin@example.com', ], ], 'redirects' => [ 'login' => ['controller' => 'Users', 'action' => 'login'], 'unauthorized' => ['controller' => 'Dashboard', 'action' => 'index'], ], ], ];
Session Timeout and Redirect
When a user's session expires while using the Authorization Manager, they will be redirected to the login page with a redirect parameter containing the original URL.
To handle the redirect in your login controller, add this code after successful authentication:
// In your UsersController login action, after successful authentication: public function login() { $result = $this->Authentication->getResult(); if ($result->isValid()) { // Check if there's a redirect parameter $redirect = $this->request->getQuery('redirect'); if ($redirect) { // Redirect back to the original URL return $this->redirect($redirect); } // Default redirect $target = $this->Authentication->getLoginRedirect() ?? '/dashboard'; return $this->redirect($target); } if ($this->request->is('post') && !$result->isValid()) { $this->Flash->error(__('Invalid username or password')); } }
This ensures users are returned to the Authorization Manager page they were viewing after logging in.
Internationalization (i18n)
The plugin comes with Spanish (es_ES) and Galician (gl_ES) translations out of the box.
To change the language, add to your config/bootstrap.php:
use Cake\I18n\I18n; // Set Spanish (default) I18n::setLocale('es_ES'); // Or Galician I18n::setLocale('gl_ES'); // Or English I18n::setLocale('en_US');
To add your own translation:
- Create
resources/locales/{locale}/acl_manager.poin your app - Copy entries from
vendor/mgomezbuceta/cakephp-aclmanager/resources/locales/es_ES/acl_manager.po - Translate the
msgstrvalues - Run
bin/cake i18n extract --plugin AclManagerto update
Other Configuration Options
In your config/bootstrap.php:
use Cake\Core\Configure; // Actions to ignore during resource scan Configure::write('AclManager.ignoreActions', [ 'isAuthorized', 'beforeFilter', 'initialize', 'AclManager.*', // Ignore plugin 'DebugKit.*' // Ignore DebugKit ]); // Permission checking mode Configure::write('AclManager.permissionMode', 'strict'); // or 'permissive' // Enable permission caching Configure::write('AclManager.cachePermissions', true); Configure::write('AclManager.cacheDuration', '+1 hour'); // Default role for new users Configure::write('AclManager.defaultRoleId', 2);
π οΈ Cambios recientes (Unreleased)
PequeΓ±o resumen de cambios detectados el 2025-12-02:
- Se ha aΓ±adido
Utilities/*aignoreActionspara excluir utilidades del escaneo de recursos. AuthorizationManagerComponentahora utiliza'App'como valor por defecto para el parΓ‘metroplugincuando no estΓ‘ presente.PermissionsTableyResourcesTable: tipos de columna boolean correctamente definidos (allowed,active).ResourceScannerService::getGroupedResources()filtra plugins, controladores y acciones segΓΊnignoreActionsantes de devolver los recursos agrupados.- Plantillas de permisos (
templates/Permissions/*) integranadminRoleIdspara evitar que roles administrativos sean eliminados desde la UI; el enlace "Clear All" ahora invoca la acciΓ³nclearPermissionsy el campo ocultopluginmantiene su valor real. - Archivos de traducciΓ³n: limpieza de cadenas (ej. eliminaciΓ³n de la cadena "Deny").
- Nueva polΓtica
src/Policy/AclManagerPolicy.phpque delega enPermissionService. - Se aΓ±adiΓ³ la clase CSS
.disabled-linkentemplates/layout/default.phppara estilos de enlaces inactivos.
Nota: Se han detectado archivos en la carpeta .snapshots/. Estos archivos suelen ser generados por herramientas locales y no deberΓan comitearse. Se han eliminado del repositorio y aΓ±adida una entrada en .gitignore para evitar futuros commits accidentales.
ποΈ Database Schema
The plugin creates three tables:
- roles β User roles:
id, name, description, priority, active, created, modified - permissions β Role permissions:
id, role_id, controller, action, plugin, allowed, created, modified - resources β Available resources (auto-discovered):
id, controller, action, plugin, description, active, created, modified
π Component Usage
// Load the component $this->loadComponent('AclManager.AuthorizationManager'); // Check if user is authorized $allowed = $this->AuthorizationManager->isAuthorized($user); // Check specific permission $allowed = $this->AuthorizationManager->checkPermission( $roleId, 'Articles', 'edit', 'Blog' // plugin name (optional) ); // Clear permission cache $this->AuthorizationManager->clearCache(); // Handle unauthorized access return $this->AuthorizationManager->handleUnauthorized();
π― Service Layer
use AclManager\Service\PermissionService; use AclManager\Service\ResourceScannerService; // Permission management $permissionService = new PermissionService(); // Grant permission $permissionService->grant($roleId, 'Articles', 'edit'); // Deny permission $permissionService->deny($roleId, 'Articles', 'delete'); // Get permission matrix $matrix = $permissionService->getPermissionMatrix($roleId); // Copy permissions between roles $permissionService->copyPermissions($sourceRoleId, $targetRoleId); // Resource scanning $scannerService = new ResourceScannerService(); $stats = $scannerService->scanAndSync(); // Get grouped resources $resources = $scannerService->getGroupedResources();
π Troubleshooting
No resources showing?
Visit /authorization-manager and click "Sync Resources"
Permission changes not taking effect?
// Clear cache Configure::write('AclManager.cachePermissions', false); // Or clear specific cache $this->AuthorizationManager->clearCache();
Getting "access denied" after setup?
- Make sure your User has a role_id assigned
- Verify permissions are granted for that role
- Check isAuthorized() is properly implemented
π Migration from v2.x
β οΈ BREAKING CHANGE: Version 3.0 uses Authorization plugin instead of deprecated ACL.
Migration Steps
- Backup your data
CREATE TABLE backup_aros_acos AS SELECT * FROM aros_acos;
- Update composer.json
composer remove cakephp/acl composer require cakephp/authorization composer update mgomezbuceta/cakephp-aclmanager
- Run new migrations
bin/cake migrations migrate -p AclManager
- Update routes
- Old:
/acl-manager - New:
/authorization-manager
- Update component
// Old $this->loadComponent('AclManager.AclManager'); // New $this->loadComponent('AclManager.AuthorizationManager');
- Rebuild permissions
- Create new roles matching your old ARO structure
- Use "Sync Resources" to discover controllers
- Manually assign permissions (old ACL data cannot be migrated)
ποΈ Architecture
βββββββββββββββββββββββββββββββββββββββββββ
β PermissionsController β
β (Web Interface) β
ββββββββββββββββ¬βββββββββββββββββββββββββββ
β
ββββββββββ΄βββββββββ
β β
βββββββΌβββββββββββ βββββΌβββββββββββββββββββ
β Permission β β ResourceScanner β
β Service β β Service β
β β β β
β β’ Check Auth β β β’ Scan Controllers β
β β’ Grant/Deny β β β’ Sync Resources β
β β’ Copy Perms β β β’ Auto-Discovery β
ββββββββββββββββββ ββββββββββββββββββββββββ
β β
ββββββββββββ¬βββββββββββ
β
ββββββββββββββΌββββββββββββββ
β Database Tables β
β β’ roles β
β β’ permissions β
β β’ resources β
βββββββββββββββββββββββββββββ
```text
---
## π€ Contributing
Contributions are welcome!
1. π΄ Fork the repository
2. πΏ Create your feature branch (`git checkout -b feature/amazing-feature`)
3. π» Write clean, documented code following PSR-12
4. β
Add tests for new functionality
5. π Commit your changes (`git commit -m 'Add amazing feature'`)
6. π Push to the branch (`git push origin feature/amazing-feature`)
7. π Open a Pull Request
---
## π License
This project is licensed under the **MIT License** - see [LICENSE.md](LICENSE.md) for details.
```text
Copyright (c) 2025 Marcos GΓ³mez Buceta
Copyright (c) 2016 IvΓ‘n Amat
π¨βπ» Author
Marcos GΓ³mez Buceta
π Acknowledgments
This project evolved from the excellent ACL Manager foundation:
- IvΓ‘n Amat - Original CakePHP 4.x Acl Manager
- FrΓ©dΓ©ric Massart (FMCorz) - Original CakePHP 2.x AclManager
Special thanks to the CakePHP community for their continuous support.
β If you find this plugin useful, please give it a star! β
Made with β€οΈ for the CakePHP community