huang-yi/laravel-rbac

Laravel 的 RBAC(基于角色的访问控制)包。

v2.0.0 2020-06-17 18:31 UTC

This package is auto-updated.

Last update: 2024-09-18 03:34:42 UTC


README

英文 | 中文

Laravel RBAC

此包帮助您管理权限和角色。

安装

您可以通过 Composer 安装此包

composer require huang-yi/laravel-rbac

接下来,您应使用 vendor:publish Artisan 命令发布配置和迁移文件

php artisan vendor:publish --provider="HuangYi\Rbac\RbacServiceProvider"

最后,您应运行您的数据库迁移

php artisan migrate

配置

  • user:您使用的用户模型类。
  • 数据库:
    • connection:RBAC 表的数据库连接。
    • prefix:RBAC 表的公共前缀。
  • cache:缓存开关。

使用方法

您的用户模型必须配置为 rbac.user 选项。它应该实现 HuangYi\Rbac\Contracts\Authorizable 接口并使用 HuangYi\Rbac\Concerns\Authorizable 特性。

namespace App;

use HuangYi\Rbac\Concerns\Authorizable;
use HuangYi\Rbac\Contracts\Authorizable as AuthorizableContract;

class User extends Authenticatable implement AuthorizableContract
{
    use Authorizable, Notifiable;
}

将权限存储到数据库

use HuangYi\Rbac\Permission;

Permission::make('edit post');

将角色存储到数据库

use HuangYi\Rbac\Role;

Permission::make('personnel manager');

将权限附加或分离到角色

$role->attachPermissions($permissions);

$role->detachPermissions($permissions);

$role->syncPermissions($permissions);

将角色附加或分离到用户

$user->attachRoles($roles);

$user->detachRoles($roles);

$user->syncRoles($roles);

将权限附加或分离到用户

$user->attachPermissions($permissions);

$user->detachPermissions($permissions);

$user->syncPermissions($permissions);

确定用户是否有角色

$user->hasRole('author');

$user->hasRoles(['author', 'personnel manager']);

$user->hasAnyRoles(['author', 'personnel manager']);

确定用户是否有权限

$user->hasPermission('create post');

$user->hasPermissions(['create post', 'edit post']);

$user->hasAnyPermissions(['create post', 'edit post']);

// this is similar to hasAnyPermissions
$user->can('edit post|edit post');

超级管理员

您可以使用 Rbac::checkSuperAdminUsing() 方法注册一个回调来决定用户是否为超级管理员

namespace App\Providers;

use HuangYi\Rbac\Rbac;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Rbac::checkSuperAdminUsing(function ($user) {
            return in_array($user->email, ['admin@example.com']);
        });
    }
}

中间件

// role middleware
Route::get('admin/staffs', [StaffController::class, 'index'])->middleware('role:personnel manager|vice president');

// permission middleware
Route::post('post/{post}', [PostController::class, 'update'])->middleware('permission:create post|edit post');

// this is similar to 'permission' middleware
Route::post('post/{post}', [PostController::class, 'update'])->middleware('can:create post|edit post');

Blade 指令

角色指令

  • @role@elserole@endrolehasRole
  • @roles@elseroles@endroleshasRoles
  • @anyroles@elseanyroles@endanyroleshasAnyRoles

权限指令

  • @permission@elsepermission@endpermissionhasPermission
  • @permissions@elsepermissions@endpermissionshasPermissions
  • @anypermissions@elseanypermissions@endanypermissionshasAnyPermissions

测试

composer test

许可

此包是开源软件,受 MIT 许可 许可。