code-orange/entrust

此包提供了一种灵活的方式来为 Laravel 添加基于角色的权限

维护者

详细信息

github.com/code-orange/entrust

源代码

安装: 1,226

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 1,290

4.0 2020-03-20 22:02 UTC

README

Build Status License ProjectStatus Total Downloads SensioLabsInsight

Entrust 是一种简洁且灵活的方式,可以轻松地将基于角色的权限添加到 Laravel 7

如果您正在寻找 Laravel 4 版本,请查看 发布 1.3.x 版本的发布树。

内容

安装

为了安装 Laravel 5 Entrust,只需在您的 composer.json 中添加

"zizaco/entrust": "dev-laravel-5"

然后运行 composer installcomposer update

然后在您的 config/app.php 中添加

Zizaco\Entrust\EntrustServiceProvider::class

providers 数组中,并将

'Entrust' => Zizaco\Entrust\EntrustFacade::class

添加到 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_namedescription 都是可选的;它们的字段在数据库中是可空的。

权限

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 Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable,
        Authorizable,
        CanResetPassword,
        EntrustUserTrait // add this trait to your user model
        {
            EntrustUserTrait ::can insteadof Authorizable; //add insteadof avoid php trait conflict resolution
        }
        
        ...

这将启用与 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

使用方法

概念

让我们首先创建以下 RolePermission

$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);

用户能力

可以使用强大的 ability 函数进行更高级的检查。它接受三个参数(角色、权限、选项)

  • roles 是要检查的角色集合。
  • permissions 是要检查的权限集合。

任一角色或权限变量可以是逗号分隔的字符串或数组

$user->ability(array('admin', 'owner'), array('create-post', 'edit-user'));

// or

$user->ability('admin,owner', 'create-post,edit-user');

这将检查用户是否有任何提供的角色和权限。在这种情况下,它将返回 true,因为用户是 admin 并有 create-post 权限。

第三个参数是选项数组

$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)
// }

简短语法路由过滤器

要按权限或角色过滤路由,您可以在 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,则函数仅在用户的所有角色/权限失败时才会失败。这对于需要允许多个组访问的应用程序很有用。

// 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 中的 canhasRole 方法来在过滤器中使用 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 编码标准和语义化版本。

请将您在问题页面中发现的任何问题报告给我们。
欢迎提交拉取请求。