wffranco/roles

Laravel 5.8+ 中处理角色和权限的包

v1.0 2019-05-31 03:49 UTC

This package is not auto-updated.

Last update: 2024-09-29 06:14:18 UTC


README

Laravel 5.8+ 中处理角色和权限的包。

安装

仍在开发中,但此包易于设置。只需遵循几个步骤。

Composer

通过 Composer (文件 composer.json) 引入此包。

{
    "require": {
        "php": ">=7.1.3",
        "laravel/framework": "5.8.*",
        "wffranco/roles": "~1.0",
    }
}

服务提供者

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

'providers' => [
    ...

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

],

配置文件和迁移

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

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

并运行迁移。

php artisan migrate

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

HasRoleAndPermission 特性和契约

在您的 User 模型中包含 HasRoleAndPermission 特性和契约。

use Wffranco\Roles\Traits\HasRoleAndPermission;
use Wffranco\Roles\Contracts\HasRoleAndPermission as HasRoleAndPermissionContract;

class User extends Authenticatable implements HasRoleAndPermissionContract
{
    use Notifiable, HasRoleAndPermission;

就是这样!

用法

级别

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

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

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

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

创建角色

use Wffranco\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

检查角色

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

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

您也可以这样做

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

当然,您也可以使用和/或运算符来检查多个角色

if ($user->is('admin|moderator')) {
    /*
    | Or alternatively:
    | $user->is(['admin', 'moderator']) // or operator: first braket
    */

    // if user has at least one role
}

if ($user->is('admin&moderator')) {
    /*
    | Or alternatively:
    | $user->is([['admin', 'moderator']]) // and operator: second braket
    */

    // if user has all roles
}

// Mixed or/and
if ($user->is('admin|moderator&publisher')) {
    /*
    | Or alternatively:
    | $user->is(['admin', ['moderator', 'publisher']])
    | $user->is(['admin', 'moderator&publisher'])
    */
}

您可以使用运算符和括号(仅在字符串中)来分组条件。您也可以使用方法 hasRole 而不是 is

创建权限

由于 Permission 模型,这非常简单。

use Wffranco\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 Wffranco\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

$user->detachPermission($deleteUsersPermission);
$user->detachAllPermissions();

检查权限

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

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

您也可以像角色一样检查多个权限。您也可以使用 hasPermission 而不是 can

联合检查角色/权限

假设您有一个博客,只有可以发布管理员或具有写权限的版主才能发布。目前您可以这样做

if ($user->isAdmin() || $user->isModerator() && $user->can('blog.write')) {
}
// or
if ($user->is('admin') || $user->is('moderator') && $user->can('blog.write')) {
}

对于复杂的规则,您可以结合使用角色和权限以及 has 方法。现在您可以这样做

if ($user->has('role:admin|role:moderator&permission:blog.write')) {
}
// you can even abbreviate role & permission to their first letter
if ($user->has('r:admin|r:moderator&p:blog.write')) {
}

与 PHP 一样,在所有 3 个方法(is/can/has)中,除非您使用括号,否则 or 运算符在最后评估。

// Force 'or' first.
if ($user->has('(r:admin|r:moderator)&p:blog.write')) {
}

权限继承

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

这是这个 魔法 的一个例子

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

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

实体检查

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

use App\Article;
use Wffranco\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()->is('admin'))
    // user is admin
@endrole

@permission('edit.articles') // @if(Auth::check() && Auth::user()->can('edit.articles'))
    // user can edit articles
@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', 'all') // @if(Auth::check() && Auth::user()->is('admin|moderator', 'all'))
    // user is admin and also moderator
@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' => \Wffranco\Roles\Middleware\VerifyRole::class,
    'permission' => \Wffranco\Roles\Middleware\VerifyPermission::class,
    'level' => \Wffranco\Roles\Middleware\VerifyLevel::class,
];

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

Route::middleware('role:admin')
    ->get('/example', 'ExampleController@index');

Route::middleware('permission:edit.articles')
    ->post('/example', 'ExampleController@index');

Route::middleware('level:2')
    ->get('/example', 'ExampleController@index');

如果出现错误,它将抛出\Wffranco\Roles\Exceptions\RoleDeniedException\Wffranco\Roles\Exceptions\PermissionDeniedException\Wffranco\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 \Wffranco\Roles\Exceptions\RoleDeniedException) {
        // you can for example flash message, redirect...
        return redirect()->back();
    }

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

配置文件

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

更多信息

有关更多信息,请参阅HasRoleAndPermission契约。

许可

此软件包是免费软件,根据MIT许可协议分发。