httpoz/roles

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

v9.0.0 2022-02-09 20:11 UTC

README

Laravel中处理角色的简单包。

Build Status Total Downloads codecov Latest Stable Version

安装

此包设置非常简单。只有几个步骤。

以前版本

有关以前的版本,请参阅 版本页面

Composer

通过Composer将包添加到您的项目中。

composer require httpoz/roles:^v9.0

配置文件和迁移

要发布包的配置文件和迁移到您的应用程序,请在终端中运行此命令。

php artisan vendor:publish --provider="HttpOz\Roles\RolesServiceProvider"
php artisan migrate

启用HasRole特性和契约

在您的用户模型中包含HasRole特性和实现HasRole契约。

<?php

use HttpOz\Roles\Traits\HasRole;
use HttpOz\Roles\Contracts\HasRole as HasRoleContract;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements HasRoleContract
{
    use Notifiable, HasRole;

    ///
}

就这样!

用法

创建角色

$adminRole = \HttpOz\Roles\Models\Role::create([
    'name' => 'Admin',
    'slug' => 'admin',
    'description' => 'Custodians of the system.', // optional
    'group' => 'default' // optional, set as 'default' by default
]);

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

由于Slugable特性和str_slug函数,如果您在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

同步角色

您还可以使用sync方法将角色附加到用户模型。任何未传递到方法中的角色都将从用户的角色中分离。因此,在此操作完成后,只有传递到方法中的角色将附加到用户。

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

$roles = [1, 4, 6]; // using the role IDs we want to assign to a user

$user->syncRoles($roles); // you can pass Eloquent collection, or just an array of ids

检查角色

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

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

// or

if($user->hasRole('admin')) {
    // do something
}

// or

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

当然,也有检查多个角色的一种方法

在这种情况下,用户必须至少拥有所提供角色中的一个。以下列出了多个选项,它们实现了相同的目标。

    if ($user->isRole('admin|forum.moderator')) {
        // do something
    }

    if($user->isRole('admin, forum.moderator')){
        // do something
    }

    if($user->isRole(['admin', 'forum.moderator'])){
        // do something
    }

    if($user->isOne('admin|forum.moderator')){
        // do something
    }

    if($user->isOne('admin, forum.moderator')){
        // do something
    }

    if($user->isOne(['admin', 'forum.moderator'])){
        // do something
    }

在这种情况下,用户必须拥有所有所提供角色。以下列出了多个选项,它们实现了相同的目标。

    if ($user->isRole('admin|forum.moderator', true)) {
        // do something
    }

    if($user->isRole('admin, forum.moderator', true)){
        // do something
    }

    if($user->isRole(['admin', 'forum.moderator'], true)){
        // do something
    }

    if($user->isAll('admin|forum.moderator')){
        // do something
    }

    if($user->isAll('admin, forum.moderator')){
        // do something
    }

    if($user->isAll(['admin', 'forum.moderator'])){
        // do something
    }

按角色查找用户

有几种方法可以通过用户给出的角色获取用户列表。

使用角色的ID

   $admins = Role::find(1)->users;

使用角色的slug

   $adminRole = Role::findBySlug('admin');
   $admins = $adminRole->users;

使用角色的组

   $adminRole = Role::where('group', 'forum.moderator')->first();
   $admins = $adminRole->users;

如果您在用户模型上使用了软删除,并想包括已删除的用户,请使用usersWithTrashed方法而不是users

if ($user->group() == 'application.managers') {
    //
}

if ($user->inGroup('application.managers')) {
    // if true do something
}

如果用户有多个角色,则group方法将返回按字母顺序排序的第一个角色(将探索此实现的更好方法)。

Group旨在将权限(Laravel的内置授权功能)组织并分配给一个可以由多个角色共享的角色组(将在未来的文档中添加示例和实现)。

Blade扩展

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

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

@group('application.managers') // @if(Auth::check() && Auth::user()->group() == 'application.managers')
    // user belongs to 'application.managers' group
@endgroup

@role('admin|moderator', 'all') // @if(Auth::check() && Auth::user()->isRole('admin|moderator', 'all'))
    // user is admin and also moderator
@else
    // something else
@endrole

中间件

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

/**
 * The application's route middleware.
 *
 * @var array
 */
protected $routeMiddleware = [

    // ...

    'role' => \HttpOz\Roles\Middleware\VerifyRole::class,
    'group' => \HttpOz\Roles\Middleware\VerifyGroup::class,
];

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

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

$router->get('/example', [
    'as' => 'example',
    'middleware' => 'group:application.managers',
    'uses' => 'ExampleController@index',
]);

如果出错,它会抛出\HttpOz\Roles\Exceptions\RoleDeniedException\HttpOz\Roles\Exceptions\GroupDeniedException异常。

您可以在app/Exceptions/Handler.php文件中捕获这些异常,并执行您想要的任何操作。您可以控制当应用用户尝试打开他们角色不允许访问的页面时看到的错误页面。此包已经捆绑了一个视图,应该已经在发布包时发布到resources/views/vendor/roles/error.blade.php。只需在app\Exceptions\Handler.php的render函数中添加以下条件即可。您可以自由地指向您选择的另一个视图。

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof \HttpOz\Roles\Exceptions\RoleDeniedException || $exception instanceof \HttpOz\Roles\Exceptions\GroupDeniedException) {
            return response()->view('vendor.roles.error', compact('exception'), 403);
        }

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

配置文件

您可以更改模型的连接、缩略符分隔符、模型路径,还有一个便捷的模拟功能。查看配置文件以获取更多信息。

缓存

缓存过期时间的配置默认为2周(以秒为单位)。您可以更新此值以满足您的项目特定需求。

许可证

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