codekanzlei / cake-auth-actions
CakePHP 4 的简单 ACL 替代方案
Requires
- php: >=7.2.0
- cakephp/cakephp: ^4.0.0-RC1
Requires (Dev)
- phpstan/phpstan: ^0.11
- scherersoftware/coding-standard: ^4.0-dev
This package is auto-updated.
Last update: 2024-08-30 01:20:44 UTC
README
这是一个简单的基于配置的 ACL 替代方案,适用于 CakePHP 4。允许您为不同类型的用户定义对控制器操作的特定访问权限。
安装
1. 使用 composer 安装插件
composer require codekanzlei/auth-actions
2. 在您的 src/Application.php
中加载插件
$this->addPlugin('AuthActions');
使用 & 配置
1. 配置 AppController.php
在您的 src/Controller/AppController.php
中,将以下代码段插入相应的部分
特质
use \AuthActions\Lib\AuthActionsTrait;
...
use AuthActionsTrait;
$components
public $components = [
'Auth' => [
'authenticate' => [
'Form' => [
'repository' => 'Users',
'scope' => [
'status' => Status::ACTIVE,
]
]
],
'authorize' => ['Controller'],
'loginAction' => [], // prefered login view
'loginRedirect' => [], // redirect after successful login
'logoutRedirect' => [], // redirect after logout
'authError' => 'PERMISSION_DENIED',
// namespace declaration of AuthUtilsComponent
'AuthActions.AuthUtils'
]
];
beforeFilter()
public function beforeFilter(\Cake\Event\Event $event)
{
$this->initAuthActions();
}
2. 配置 AppView.php
initialize()
public function initialize()
{
$this->loadHelper('Auth', [
'className' => 'AuthActions.Auth'
]);
}
3. 创建额外的文件
在您的项目的 config
文件夹中,创建所需的配置文件。
注意:为参考,请参阅以下文件
-
auth_actions.php-default
在这里,您可以授予或限制对控制器函数的访问权限,针对特定的用户角色。
-
user_rights.php-default
在这里,您可以定义进一步的定制访问权限,允许根据查看用户的角色轻松控制哪些按钮将在视图文件中渲染。
有关更多信息,请参阅[4. 授予权限/限制组权限](#### 4. 授予权限/限制组权限)以及示例代码片段。
auth_actions.php
touch config/auth_actions.php
user_rights.php
touch config/user_rights.php
3. 定义自定义用户角色
向您的数据库用户表中添加一个名为 role
的新列。
在您的 User.php
中,您可以定义自定义用户角色为常量。
一个常用、基本的用户角色集 ADMIN 和 USER 可以定义为以下内容
const ROLE_ADMIN = 'admin';
const ROLE_USER = 'user';
4. 授予权限/限制组权限
以下是一个简单的 USER 和 ADMIN 设置的示例,考虑以下常见用例。
-
限制非管理员用户的访问权限:考虑一个基本的 "用户" MVC 设置。假设您只想授予 ADMINS 访问每个控制器操作的权限,包括 edit() 以及以后添加的任何函数,同时限制 USERS 除非 index() 和 view(),否则不允许访问所有功能。
在
auth_actions.php
$config = [ 'auth_actions' => [ // Controller name: 'Users' 'Users' => [ // wildcard * includes every action in this controller '*' => [ User::ROLE_ADMIN ], // here we explicitly list actions that // USERS shall be able to access 'index' => [ User::ROLE_USER ], 'view' => [ User::ROLE_USER ] ] ] ];
-
防止在视图中渲染按钮:上述代码将防止 USERS 调用 UsersController 中的任何操作,除非是 index() 和 view(),但例如,在 index-view 中与用户实体并排的 edit 按钮仍然会渲染。以下是在视文件被非-ADMIN 用户查看时防止它们渲染的方法
在
user_rights.php
$config = [ 'user_rights' => [ // granting a custom right only for Users of type ADMIN 'viewEditButton' => [ User::ROLE_ADMIN ] ] ];
在您的索引视图中
<?php if ($this->Auth->hasRight('viewEditButton')): ?> <?= $this->Html->link(__('Edit'), ['action' => 'edit', $user->id]) ?> <?php endif; ?>