sevenlab/laravel-roles

Laravel中处理角色和权限的强大包。

6.0.1 2023-01-09 14:55 UTC

README

Laravel中处理角色和权限的强大包。

安装

此包非常容易设置。只需几个步骤。

Composer

通过 Composer 拉取此包

composer require 7Lab/laravel-roles

如果您仍在使用 Laravel 5.0,则必须拉取版本 1.7.*

服务提供者

将包添加到您的应用程序服务提供者 config/app.php 文件中。

'providers' => [

    ...

    /**
     * Third Party Service Providers...
     */
    Ultraware\Roles\RolesServiceProvider::class,

],

配置文件和迁移

将包的配置文件和迁移发布到您的应用程序。在您的终端中运行以下命令。

php artisan vendor:publish --provider="Ultraware\Roles\RolesServiceProvider" --tag=config
php artisan vendor:publish --provider="Ultraware\Roles\RolesServiceProvider" --tag=migrations

并且也要运行迁移。

php artisan migrate

这使用的是 Laravel 中的默认用户表。您应该已经有用户表的迁移文件并且已经迁移。

HasRoleAndPermission 特性和契约

包含 HasRoleAndPermission 特性,并在您的 User 模型中实现 HasRoleAndPermission 契约。

从 Bican 角色迁移

如果您从 bican/roles 迁移到 ultraware/roles,需要更新一些内容。

  • 将所有对 cancanOnecanAll 的调用更改为 hasPermissionhasOnePermissionhasAllPermissions
  • 将所有对 isisOneisAll 的调用更改为 hasRolehasOneRolehasAllRoles

使用方法

创建角色

use Ultraware\Roles\Models\Role;

$adminRole = Role::create([
    'name' => 'Admin',
    'slug' => 'admin',
    'description' => '', // optional
    'level' => 1, // optional, set to 1 by default
]);

$moderatorRole = Role::create([
    'name' => 'Forum Moderator',
    'slug' => 'forum.moderator',
]);

由于 Slugable 特性,如果您犯了一个错误,例如在 slug 参数中留下空格,它将被自动替换为点,这是由于 str_slug 函数。

附加、移除和同步角色

这非常简单。您从数据库中获取一个用户并调用 attachRole 方法。在 UserRole 模型之间存在 BelongsToMany 关系。

use App\User;

$user = User::find($id);

$user->attachRole($adminRole); // you can pass whole object, or just an id
$user->detachRole($adminRole); // in case you want to detach role
$user->detachAllRoles(); // in case you want to detach all roles
$user->syncRoles($roles); // you can pass Eloquent collection, or just an array of ids

检查角色

现在您可以检查用户是否有所需的角色。

if ($user->hasRole('admin')) { // you can pass an id or slug
    //
}

您也可以这样做

if ($user->isAdmin()) {
    //
}

当然,还有检查多个角色的方法

if ($user->hasRole(['admin', 'moderator'])) {
    /*
    | Or alternatively:
    | $user->hasRole('admin, moderator'), $user->hasRole('admin|moderator'),
    | $user->hasOneRole('admin, moderator'), $user->hasOneRole(['admin', 'moderator']), $user->hasOneRole('admin|moderator')
    */

    // The user has at least one of the roles
}

if ($user->hasRole(['admin', 'moderator'], true)) {
    /*
    | Or alternatively:
    | $user->hasRole('admin, moderator', true), $user->hasRole('admin|moderator', true),
    | $user->hasAllRoles('admin, moderator'), $user->hasAllRoles(['admin', 'moderator']), $user->hasAllRoles('admin|moderator')
    */

    // The user has all roles
}

层级

当您创建角色时,有一个可选参数 level。默认设置为 1,但您可以重写它,然后您可以这样做

if ($user->level() > 4) {
    //
}

如果用户有多个角色,方法 level 返回最高级别。

Level 对权限继承也有很大影响。稍后讨论。

创建权限

多亏了 Permission 模型,这非常简单。

use Ultraware\Roles\Models\Permission;

$createUsersPermission = Permission::create([
    'name' => 'Create users',
    'slug' => 'create.users',
    'description' => '', // optional
]);

$deleteUsersPermission = Permission::create([
    'name' => 'Delete users',
    'slug' => 'delete.users',
]);

附加、移除和同步权限

您可以将权限附加到角色或直接附加到特定用户(当然,也可以解除它们)。

use App\User;
use Ultraware\Roles\Models\Role;

$role = Role::find($roleId);
$role->attachPermission($createUsersPermission); // permission attached to a role

$user = User::find($userId);
$user->attachPermission($deleteUsersPermission); // permission attached to a user
$role->detachPermission($createUsersPermission); // in case you want to detach permission
$role->detachAllPermissions(); // in case you want to detach all permissions
$role->syncPermissions($permissions); // you can pass Eloquent collection, or just an array of ids

$user->detachPermission($deleteUsersPermission);
$user->detachAllPermissions();
$user->syncPermissions($permissions); // you can pass Eloquent collection, or just an array of ids

检查权限

if ($user->hasPermission('create.users')) { // you can pass an id or slug
    //
}

if ($user->canDeleteUsers()) {
    //
}

您可以使用与角色相同的方式检查多个权限。您可以使用额外的方法,如 hasOnePermissionhasAllPermissions

权限继承

级别较高的角色会从级别较低的角色的权限中继承权限。

这里有一个这个 魔法 的例子

您有三个角色:usermoderatoradmin。用户有阅读文章的权限,版主可以管理评论,管理员可以创建文章。用户的级别为 1,版主的级别为 2,管理员的级别为 3。这意味着,版主和管理员也有阅读文章的权限,但管理员还可以管理评论。

如果您不想在应用程序中启用权限继承功能,只需在创建角色时忽略 level 参数即可。

实体检查

假设您有一篇文章并想编辑它。这篇文章属于一个用户(文章表中有一个 user_id 列)。

use App\Article;
use Ultraware\Roles\Models\Permission;

$editArticlesPermission = Permission::create([
    'name' => 'Edit articles',
    'slug' => 'edit.articles',
    'model' => 'App\Article',
]);

$user->attachPermission($editArticlesPermission);

$article = Article::find(1);

if ($user->allowed('edit.articles', $article)) { // $user->allowedEditArticles($article)
    //
}

此条件检查当前用户是否为文章的所有者。如果不是,它将查找我们之前创建的权限行。

if ($user->allowed('edit.articles', $article, false)) { // now owner check is disabled
    //
}

Blade 扩展

有四个Blade扩展。基本上,它是经典if语句的替代品。

@role('admin') // @if(Auth::check() && Auth::user()->hasRole('admin'))
    // user has admin role
@endrole

@permission('edit.articles') // @if(Auth::check() && Auth::user()->hasPermission('edit.articles'))
    // user has edit articles permissison
@endpermission

@level(2) // @if(Auth::check() && Auth::user()->level() >= 2)
    // user has level 2 or higher
@endlevel

@allowed('edit', $article) // @if(Auth::check() && Auth::user()->allowed('edit', $article))
    // show edit button
@endallowed

@role('admin|moderator', true) // @if(Auth::check() && Auth::user()->hasRole('admin|moderator', true))
    // user has admin and moderator role
@else
    // something else
@endrole

中间件

此包包含 VerifyRoleVerifyPermissionVerifyLevel 中间件。您必须将它们添加到您的 app/Http/Kernel.php 文件中。

/**
 * The application's route middleware.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'role' => \Ultraware\Roles\Middleware\VerifyRole::class,
    'permission' => \Ultraware\Roles\Middleware\VerifyPermission::class,
    'level' => \Ultraware\Roles\Middleware\VerifyLevel::class,
];

现在您可以轻松地保护您的路由。

$router->get('/example', [
    'as' => 'example',
    'middleware' => 'role:admin',
    'uses' => 'ExampleController@index',
]);

$router->post('/example', [
    'as' => 'example',
    'middleware' => 'permission:edit.articles',
    'uses' => 'ExampleController@index',
]);

$router->get('/example', [
    'as' => 'example',
    'middleware' => 'level:2', // level >= 2
    'uses' => 'ExampleController@index',
]);

如果出错,它会抛出 \Ultraware\Roles\Exceptions\RoleDeniedException\Ultraware\Roles\Exceptions\PermissionDeniedException\Ultraware\Roles\Exceptions\LevelDeniedException 异常。

您可以在 app/Exceptions/Handler.php 文件中捕获这些异常并执行您想要的任何操作。

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    if ($e instanceof \Ultraware\Roles\Exceptions\RoleDeniedException) {
        // you can for example flash message, redirect...
        return redirect()->back();
    }

    return parent::render($request, $e);
}

配置文件

您可以更改模型连接、slug分隔符、模型路径,还有一个方便的模拟功能。有关更多信息,请查看配置文件。

更多信息

有关更多信息,请参阅 HasRoleAndPermission 合同。

许可证

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