kafrii/委托

本包提供了一种灵活的方式来为Laravel添加基于角色的权限,由amer kafri定制。

2.8 2023-11-07 19:51 UTC

This package is auto-updated.

Last update: 2024-09-08 12:19:32 UTC


README

Entrust 是一种简洁灵活的方法,用于向 Laravel 8 添加基于角色的权限。

内容

安装

  1. 为了安装 Laravel 8 Entrust,只需将以下内容添加到您的 composer.json 中。然后运行 composer update
composer require kafrii/entrust
  1. 打开您的 config/app.php 并将以下内容添加到 providers 数组中
Kafrii\Entrust\EntrustServiceProvider::class,
  1. 在相同的 config/app.php 中,将以下内容添加到 aliases 数组中
'Entrust'   => Kafrii\Entrust\EntrustFacade::class,
  1. 运行以下命令以发布包配置文件 config/entrust.php
php artisan vendor:publish
  1. 打开您的 config/auth.php 并将其添加到其中
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => Namespace\Of\Your\User\Model\User::class,
        'table' => 'users',
    ],
],
  1. 如果您想使用 中间件(需要 Laravel 5.1 或更高版本),您还需要将以下内容添加到 app/Http/Kernel.php 中的 routeMiddleware 数组中。
    'role' => \Kafrii\Entrust\Middleware\EntrustRole::class,
    'permission' => \Kafrii\Entrust\Middleware\EntrustPermission::class,
    'ability' => \Kafrii\Entrust\Middleware\EntrustAbility::class,

config/auth.php 中设置属性值。这些值将被 entrust 用于引用正确的用户表和模型。

配置

要进一步自定义表名和模型命名空间,请编辑 config/entrust.php

现在生成 Entrust 迁移

用户与角色的关系

它将生成 <timestamp>_entrust_setup_tables.php 迁移。您现在可以运行 artisan migrate 命令

php artisan entrust:migration

迁移完成后,将出现四个新表

php artisan migrate

roles — 存储角色记录

  • permissions — 存储权限记录
  • role_user — 存储角色与用户之间的多对多关系
  • permission_role — 存储角色与权限之间的多对多关系
  • user_permission — 存储用户与权限之间的多对多关系
  • user_permission — 存储用户与权限之间的多对多关系

模型

角色

app/Role.php 中创建一个 Role 模型,使用以下示例

<?php namespace App;

use Kafrii\Entrust\EntrustRole;

class Role extends EntrustRole
{
    protected $guarded = [];
}

Role 模型有三个主要属性

  • name — 角色的唯一名称,用于在应用层查找角色信息。例如:“管理员”、“所有者”、“员工”。
  • display_name — 角色的可读名称。不一定是唯一的,是可选的。例如:“用户管理员”、“项目所有者”、“Widget Co. 员工”。
  • description — 角色更详细的说明。也是可选的。

display_namedescription 都是可选的;它们的字段在数据库中是可空的。

权限

app/Permission.php 中创建一个 Permission 模型,使用以下示例

<?php namespace App;

use Kafrii\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{
    protected $guarded = [];
    
    public function parent()
    {
        return $this->hasOne(Permission::class, 'id', 'parent');
    }

    public function children()
    {
        return $this->hasMany(Permission::class, 'parent', 'id');
    }

    public static function tree( $level = 1 )
    {
        return static::with(implode('.', array_fill(0, $level, 'children')))
            ->whereParent(0)
            ->whereAppear(1)
            ->whereSidebarLink(1)
            ->orderBy('ordering', 'asc')
            ->get();
    }
    
}

Permission 模型与 Role 模型具有相同的三个属性

  • name — 权限的唯一名称,用于在应用层查找权限信息。例如:“创建帖子”、“编辑用户”、“发布付款”、“订阅邮件列表”。
  • display_name — 权限的可读名称。不一定是唯一的,是可选的。例如:“创建帖子”、“编辑用户”、“发布付款”、“订阅邮件列表”。
  • description — 权限的更详细说明。

通常来说,将最后两个属性以句子形式来思考可能会有所帮助:“权限display_name允许用户description。”

用户

接下来,在你的现有User模型中使用EntrustUserWithPermissionsTrait特性。例如

<?php

use Kafrii\Entrust\Traits\EntrustUserWithPermissionsTrait;

class User extends Authenticatable
{
    use EntrustUserWithPermissionsTrait; // add this trait to your user model

    ...
}

这将启用与Role的关系,并在你的User模型中添加以下方法:roles()hasRole($name)withRole($name)can($permission)ability($roles, $permissions, $options)

用户权限

app/UserPermissions.php中创建一个UserPermissions模型,以下是一个示例

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class UserPermissions extends Model
{
    protected $guarded = [];

    public function permission()
    {
        return $this->belongsToMany(Permission::class, 'id', 'permission_id');
    }

    public function user()
    {
        return $this->belongsToMany(User::class, 'id', 'user_id');
    }
}

别忘了执行composer自动加载

composer dumpautoload

现在你就可以开始了。

软删除

默认迁移利用了枢轴表中的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');

您也可以使用占位符(通配符)通过执行以下操作来检查任何匹配的权限

// match any admin permission
$user->can("admin.*"); // true

// match any permission about users
$user->can("*_users"); // true

要按特定角色筛选用户,可以使用withRole()范围,例如检索所有管理员

$admins = User::withRole('admin')->get();
// or maybe with a relationsship
$company->users()->withRole('admin')->get();

用户能力

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

  • roles是要检查的一组角色。
  • permissions是要检查的一组权限。

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

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

// or

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

这将检查用户是否具有提供的任何角色和权限。在这种情况下,由于用户是管理员并且具有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');

Blade 模板

在您的Blade模板中有三个指令可供使用。您提供给指令参数的内容将被直接传递给相应的Entrust函数。

@role('admin')
    <p>This is visible to users with the admin role. Gets translated to 
    \Entrust::role('admin')</p>
@endrole

@permission('manage-admins')
    <p>This is visible to users with the given permissions. Gets translated to 
    \Entrust::can('manage-admins'). The @can directive is already taken by core 
    laravel authorization package, hence the @permission directive instead.</p>
@endpermission

@ability('admin,owner', 'create-post,edit-user')
    <p>This is visible to users with the given abilities. Gets translated to 
    \Entrust::ability('admin,owner', 'create-post,edit-user')</p>
@endability

中间件

您可以使用中间件通过权限或角色过滤路由和路由组

Route::group(['prefix' => 'admin', 'middleware' => ['role:admin']], function() {
    Route::get('/', 'AdminController@welcome');
    Route::get('/manage', ['middleware' => ['permission:manage-admins'], 'uses' => 'AdminController@manageAdmins']);
});

可以使用管道符号作为OR运算符

'middleware' => ['role:admin|root']

要模拟AND功能,只需使用多个中间件实例即可

'middleware' => ['role:owner', 'role:writer']

对于更复杂的情况,请使用接受3个参数的ability中间件:roles,permissions,validate_all

'middleware' => ['ability:admin|owner,create-post|edit-user,true']

简短语法路由过滤器

要按权限或角色过滤路由,你可以在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
);

路由过滤器

可以使用Entrust角色/权限通过在Facade中使用canhasRole方法在过滤器中进行使用

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资产,或者发布时出了问题。首先,检查你是否有config目录中的entrust.php文件。如果没有,请尝试php artisan vendor:publish,如果它没有出现,请手动将/vendor/Kafrii/entrust/src/config/config.php文件复制到你的config目录,并将其重命名为entrust.php

如果你的应用程序使用自定义命名空间,那么你需要告诉Entrust你的permissionrole模型的位置,你可以通过编辑config/entrust.php中的配置文件来实现

'role' => 'Custom\Namespace\Role'
'permission' => 'Custom\Namespace\permission'

许可协议

Entrust是免费软件,根据MIT许可证的条款分发。

贡献指南

支持遵循PSR-1和PSR-4 PHP编码标准和语义版本控制。

请在问题页面上报告你发现的任何问题。
欢迎提交拉取请求。