buiphu / aclringier
此包提供了一种灵活的方式来为Laravel添加基于角色的权限
Requires (Dev)
- sami/sami: dev-master
This package is not auto-updated.
Last update: 2024-09-28 18:05:23 UTC
README
Ngocphu ACL Ringier
安装
为了安装Laravel 5 Entrust,只需在您的composer.json中添加
"buiphu/aclringier": "dev-master"
。然后运行composer install或composer update。
然后在您的config/app.php中添加
'Zizaco\Entrust\EntrustServiceProvider'
到providers数组,并
'Entrust' => 'Zizaco\Entrust\EntrustFacade'
到aliases数组。
配置
在config/auth.php中设置属性值。这些值将被entrust用于引用正确的用户表和模型。
您还可以发布此包的配置以进一步自定义表名和模型命名空间。
只需使用php artisan vendor:publish,您的app/config目录中就会创建一个entrust.php文件。
用户与角色的关系
现在生成Entrust迁移
php artisan entrust:migration
它将生成<timestamp>_entrust_setup_tables.php迁移。您现在可以用Artisan migrate命令运行它
php artisan migrate
迁移之后,将出现四个新表
roles— 存储角色记录permissions— 存储权限记录role_user— 存储角色与用户之间的多对多关系permission_role— 存储角色与权限之间的多对多关系
模型
角色
在app/models/Role.php内部创建一个Role模型,如下所示
<?php namespace App; use Zizaco\Entrust\EntrustRole; class Role extends EntrustRole { }
Role模型有三个主要属性
name— 角色的唯一名称,用于在应用层查找角色信息。例如:"admin","owner","employee"。display_name— 角色的人读名称。不一定唯一,是可选的。例如:"用户管理员","项目所有者","Widget Co. 员工"。description— 角色的更详细说明。也是可选的。
display_name和description都是可选的;在数据库中,它们的字段是可空的。
权限
在app/models/Permission.php内部创建一个Permission模型,如下所示
<?php namespace App; use Zizaco\Entrust\EntrustPermission; class Permission extends EntrustPermission { }
Permission模型与Role模型具有相同的三个属性
name— 权限的唯一名称,用于在应用层查找权限信息。例如:"create-post","edit-user","post-payment","mailing-list-subscribe"。display_name— 权限的人读名称。不一定唯一,是可选的。例如:"创建帖子","编辑用户","发布付款","订阅邮件列表"。description— 对权限的更详细说明。
一般来说,可以将最后两个属性视为一个句子:"权限display_name允许用户description"。
用户
接下来,在您的现有User模型中使用EntrustUserTrait特质。例如
<?php use Zizaco\Entrust\Traits\EntrustUserTrait; class User extends Eloquent { use EntrustUserTrait; // add this trait to your user model ... }
这将启用与Role的关系,并在您的User模型中添加以下方法roles(),hasRole($name),can($permission)和ability($roles, $permissions, $options)。
别忘了清除composer的自动加载
composer dump-autoload
然后,您就可以开始了。
软删除
默认迁移利用了枢轴表中onDelete('cascade')子句,在删除父记录时删除关系。如果由于某些原因您不能在数据库中使用级联删除,EntrustRole和EntrustPermission类以及HasRole特质包含事件监听器来手动删除相关枢轴表中的记录。为了防止意外删除数据,如果模型使用软删除,事件监听器将不会删除枢轴数据。然而,由于Laravel的事件监听器存在限制,无法区分对delete()的调用与对forceDelete()的调用。因此,在强制删除模型之前,您必须手动删除任何关系数据(除非您的枢轴表使用级联删除)。例如
$role = Role::findOrFail(1); // Pull back a given role // Regular Delete $role->delete(); // This will work no matter what // Force Delete $role->users()->sync([]); // Delete relationship data $role->perms()->sync([]); // Delete relationship data $role->forceDelete(); // Now force delete will work regardless of whether the pivot table has cascading delete
用法
概念
让我们先创建以下Role和Permission
$owner = new Role(); $owner->name = 'owner'; $owner->display_name = 'Project Owner'; // optional $owner->description = 'User is the owner of a given project'; // optional $owner->save(); $admin = new Role(); $admin->name = 'admin'; $admin->display_name = 'User Administrator'; // optional $admin->description = 'User is allowed to manage and edit other users'; // optional $admin->save();
接下来,在创建了这两个角色之后,让我们将它们分配给用户。多亏了HasRole特质,这个过程非常简单
$user = User::where('username', '=', 'michele')->first(); // role attach alias $user->attachRole($admin); // parameter can be an Role object, array, or id // or eloquent's original technique $user->roles()->attach($admin->id); // id only
现在我们只需将这些权限添加到这些角色中
$createPost = new Permission(); $createPost->name = 'create-post'; $createPost->display_name = 'Create Posts'; // optional // Allow a user to... $createPost->description = 'create new blog posts'; // optional $createPost->save(); $editUser = new Permission(); $editUser->name = 'edit-user'; $editUser->display_name = 'Edit Users'; // optional // Allow a user to... $editUser->description = 'edit existing users'; // optional $editUser->save(); $admin->attachPermission($createPost); // equivalent to $admin->perms()->sync(array($createPost->id)); $owner->attachPermissions(array($createPost, $editUser)); // equivalent to $owner->perms()->sync(array($createPost->id, $editUser->id));
检查角色和权限
现在我们可以简单地通过以下方式检查角色和权限
$user->hasRole('owner'); // false $user->hasRole('admin'); // true $user->can('edit-user'); // false $user->can('create-post'); // true
hasRole()和can()都可以接收一个要检查的角色和权限数组
$user->hasRole(['owner', 'admin']); // true $user->can(['edit-user', 'create-post']); // true
默认情况下,如果用户有任何一个角色或权限,则该方法将返回true。将true作为第二个参数传递将指示方法要求所有项目
$user->hasRole(['owner', 'admin']); // true $user->hasRole(['owner', 'admin'], true); // false, user does not have admin role $user->can(['edit-user', 'create-post']); // true $user->can(['edit-user', 'create-post'], true); // false, user does not have edit-user permission
对于每个User,您可以有任意多的Role,反之亦然。
Entrust类为当前登录用户提供了对can()和hasRole()的快捷方式
Entrust::hasRole('role-name'); Entrust::can('permission-name'); // is identical to Auth::user()->hasRole('role-name'); Auth::user()->can('permission-name);
您还可以使用占位符(通配符)来通过执行以下操作检查任何匹配的权限
// match any admin permission $user->can("admin.*"); // true // match any permission about users $user->can("*_users"); // true
用户能力
可以使用出色的ability函数进行更复杂的检查。它接受三个参数(角色、权限、选项)
roles是要检查的角色集。permissions是要检查的权限集。
任一角色或权限变量可以是逗号分隔的字符串或数组
$user->ability(array('admin', 'owner'), array('create-post', 'edit-user')); // or $user->ability('admin,owner', 'create-post,edit-user');
这将检查用户是否具有提供的任何角色和权限。在这种情况下,由于用户是admin并具有create-post权限,因此它将返回true。
第三个参数是选项数组
$options = array( 'validate_all' => true | false (Default: false), 'return_type' => boolean | array | both (Default: boolean) );
validate_all是一个布尔标志,用于设置是否检查所有值以返回true,或者如果至少匹配一个角色或权限,则返回true。return_type指定是否返回布尔值、检查值的数组,或者两者都在数组中返回。
以下是一个示例输出
$options = array( 'validate_all' => true, 'return_type' => 'both' ); list($validate, $allValidations) = $user->ability( array('admin', 'owner'), array('create-post', 'edit-user'), $options ); var_dump($validate); // bool(false) var_dump($allValidations); // array(4) { // ['role'] => bool(true) // ['role_2'] => bool(false) // ['create-post'] => bool(true) // ['edit-user'] => bool(false) // }
Entrust类为当前登录用户提供了对ability()的快捷方式
Entrust::ability('admin,owner', 'create-post,edit-user'); // is identical to Auth::user()->ability('admin,owner', 'create-post,edit-user');
简短语法路由过滤器
要按权限或角色过滤路由,您可以在app/Http/routes.php中调用以下内容
// only users with roles that have the 'manage_posts' permission will be able to access any route within admin/post Entrust::routeNeedsPermission('admin/post*', 'create-post'); // only owners will have access to routes within admin/advanced Entrust::routeNeedsRole('admin/advanced*', 'owner'); // optionally the second parameter can be an array of permissions or roles // user would need to match all roles or permissions for that route Entrust::routeNeedsPermission('admin/post*', array('create-post', 'edit-comment')); Entrust::routeNeedsRole('admin/advanced*', array('owner','writer'));
这两种方法都接受第三个参数。如果第三个参数为null,则禁止访问的返回将为App::abort(403),否则将返回第三个参数。因此,您可以使用它
Entrust::routeNeedsRole('admin/advanced*', 'owner', Redirect::to('/home'));
此外,这两种方法都接受第四个参数。默认为true,并检查所有给出的角色/权限。如果将其设置为false,则函数将仅在所有角色/权限都失败时失败。这对于需要允许多个组访问的admin应用程序非常有用。
// if a user has 'create-post', 'edit-comment', or both they will have access Entrust::routeNeedsPermission('admin/post*', array('create-post', 'edit-comment'), null, false); // if a user is a member of 'owner', 'writer', or both they will have access Entrust::routeNeedsRole('admin/advanced*', array('owner','writer'), null, false); // if a user is a member of 'owner', 'writer', or both, or user has 'create-post', 'edit-comment' they will have access // if the 4th parameter is true then the user must be a member of Role and must have Permission Entrust::routeNeedsRoleOrPermission( 'admin/advanced*', array('owner', 'writer'), array('create-post', 'edit-comment'), null, false );
路由过滤器
可以使用Facade中的can和hasRole方法在过滤器中使用Entrust角色/权限
Route::filter('manage_posts', function() { // check the current user if (!Entrust::can('create-post')) { return Redirect::to('admin'); } }); // only users with roles that have the 'manage_posts' permission will be able to access any admin/post route Route::when('admin/post*', 'manage_posts');
使用过滤器检查角色
Route::filter('owner_role', function() { // check the current user if (!Entrust::hasRole('Owner')) { App::abort(403); } }); // only owners will have access to routes within admin/advanced Route::when('admin/advanced*', 'owner_role');
如你所见,Entrust::hasRole()和Entrust::can()检查用户是否已登录,然后检查他或她是否有角色或权限。如果用户未登录,则返回也将为false。
故障排除
如果您在迁移过程中遇到类似以下错误
SQLSTATE[HY000]: General error: 1005 Can't create table 'laravelbootstrapstarter.#sql-42c_f8' (errno: 150)
(SQL: alter table `role_user` add constraint role_user_user_id_foreign foreign key (`user_id`)
references `users` (`id`)) (Bindings: array ())
然后很可能是您的用户表中的 id 列与 role_user 中的 user_id 列不匹配。确保两者都是 INT(10)。
当尝试使用 EntrustUserTrait 方法时,您遇到了类似以下的错误:
Class name must be a valid object or a string
那么可能您没有发布 Entrust 资产或者发布过程中出现了错误。首先检查您的 app/config 目录下是否有 entrust.php 文件。如果没有,请尝试运行 php artisan vendor:publish,如果它没有出现,请手动将 /vendor/zizaco/entrust/src/config/config.php 文件复制到您的配置目录,并将其重命名为 entrust.php。
许可证
Entrust 是在 MIT 许可证条款下免费软件。
贡献指南
支持遵循 PSR-1 和 PSR-4 PHP 编码标准和语义化版本控制。
请将您在问题页面中发现的任何问题进行报告。
欢迎提交拉取请求。