nigam214 / rbac
适用于Laravel 5.3+的强大RBAC包
Requires
- php: >=5.5.9
- illuminate/support: ~5.0
README
强大的Laravel 5.3角色和权限处理包
基于Bican/Roles包。
资源
- Packagist: https://packagist.org.cn/packages/nigam214/rbac
- Github: https://github.com/nigam214/RBAC
- Forked From: https://github.com/DynamicCodeNinja/RBAC
- Based On: https://github.com/romanbican/roles
新功能
此包是从https://github.com/DynamicCodeNinja/RBAC分支出来的,并修改以提供更多对RBAC的控制。包名已更改,使其成为新项目。为了使此包通用,用户已被对象取代。此RBAC可以应用于任何对象,而不仅仅是用户。
有何不同?
区别在于继承的工作方式。在Bican/Roles中,权限基于您最高的角色级别
进行继承。
而此包使用一个parent_id
列来启用角色之间的继承。
这使得我们只能获取用户/对象继承的或直接分配给用户/对象的角色的权限。
安装
此包设置非常简单,只有几个步骤。
Composer
通过Composer(文件composer.json
)引入此包。
{ "require": { "php": ">=5.5.9", "laravel/framework": "5.1.*", "nigam214/rbac": "~2.0" } }
在终端中运行此命令。
composer update
服务提供者
将包添加到您的应用程序服务提供者config/app.php
文件中。
'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Foundation\Providers\ArtisanServiceProvider::class, Illuminate\Auth\AuthServiceProvider::class, ... /** * Third Party Service Providers... */ Nigam214\RBAC\RBACServiceProvider::class, ],
配置文件和迁移
将包配置文件和迁移发布到您的应用程序。在终端中运行以下命令。
php artisan vendor:publish --provider="Nigam214\RBAC\RBACServiceProvider" --tag=config
php artisan vendor:publish --provider="Nigam214\RBAC\RBACServiceProvider" --tag=migrations
并运行迁移。
php artisan migrate
必须为Laravel自带的用户表创建迁移文件。对于其他自定义对象,必须有对象表的迁移文件。
HasRoleAndPermission 特性和契约
在您的User
模型或Object
模型中包含HasRoleAndPermission
特性和实现HasRoleAndPermission
契约。同时,在您的User
模型或Object
模型中包含$rbacName
。
use Nigam214\RBAC\Traits\HasRoleAndPermission; use Nigam214\RBAC\Contracts\HasRoleAndPermission as HasRoleAndPermissionContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract { use Authenticatable, CanResetPassword, HasRoleAndPermission; public $rbacName = "user_role_permission";
use Nigam214\RBAC\Traits\HasRoleAndPermission; use Nigam214\RBAC\Contracts\HasRoleAndPermission as HasRoleAndPermissionContract; class Object extends Model implements HasRoleAndPermissionContract { use HasRoleAndPermission; public $rbacName = "user_role_permission";
如果
Role
或Permission
模型是扩展的,那么每个模型都必须像为User
模型那样定义rbacName
。
rbacName
必须与rbac配置文件中给出的名称之一匹配。
这就完成了!
用法
创建角色
use Nigam214\RBAC\Models\Role; $authUser = User::where('email' = $email)->first(); $adminRole = new Role([ 'name' => 'Admin', 'slug' => 'admin', 'description' => '', // optional 'parent_id' => NULL, // optional, set to NULL by default ]); $adminRole->owner_id = $authUser->id; // `owner_id` should match with config('rbac.owner.id') $adminRole->save(); $moderatorRole = new Role([ 'name' => 'Forum Moderator', 'slug' => 'forum.moderator', ]); $moderatorRole->owner_id = $authUser->id; // `owner_id` should match with config('rbac.owner.id') $moderatorRole->save();
由于
Slugable
特性和str_slug
函数,如果您在slug参数中留下空格,它将被自动替换为点。
附加和分离角色
这非常简单。您从数据库中获取一个用户/对象,然后调用 attachRole
方法。在 User
/Object
和 Role
模型之间存在 BelongsToMany
关系。
use App\User; $authUser = User::where('email' = $email)->first(); $user = User::find($id); $user->attachRole($adminRole, $authUser->id); //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
Object
模型的示例。
use App\Object; $authUser = User::where('email' = $email)->first(); $object = Object::find($id); $object->attachRole($adminRole, $authUser->id); //you can pass whole object, or just an id $object->detachRole($adminRole); // in case you want to detach role $object->detachAllRoles(); // in case you want to detach all roles
拒绝角色
要拒绝用户/对象的角色及其所有子角色,请参阅以下示例。
如果您打算使用此功能,我们建议您相应地规划您的角色。因为您可能会在不经意间锁定用户/对象。
use App\User; $authUser = User::where('email' = $email)->first(); $role = Role::find($roleId); $user = User::find($userId); $user->attachRole($role, $authUser->id, FALSE); // Deny this role, and all of its decedents to the user regardless of what has been assigned.
use App\Object; $authUser = User::where('email' = $email)->first(); $role = Role::find($roleId); $object = Object::find($objectId); $object->attachRole($role, $authUser->id, FALSE); // Deny this role, and all of its decedents to the object regardless of what has been assigned.
检查角色
现在您可以检查用户/对象是否具有所需的角色。
if ($user->roleIs('admin')) { // you can pass an id or slug // }
您也可以这样做
if ($user->roleIsAdmin()) { // }
当然,还有检查多个角色的方法
if ($user->roleIs('admin|moderator')) { // or $user->roleIs('admin, moderator') and also $user->roleIs(['admin', 'moderator']) // if user has at least one role } if ($user->roleIs('admin|moderator', true)) { // or $user->roleIs('admin, moderator', true) and also $user->roleIs(['admin', 'moderator'], true) // if user has all roles }
以及通配符
if ($user->roleIs('admin|moderator.*')) { // or $user->roleIs('admin, moderator.*') and also $user->roleIs(['admin', 'moderator.*']) //User has admin role, or a moderator role }
创建权限
多亏了 Permission
模型,这非常简单。
use Nigam214\RBAC\Models\Permission; $authUser = User::where('email' = $email)->first(); $createUsersPermission = new Permission([ 'name' => 'Create users', 'slug' => 'create.users', 'description' => '', // optional ]); $createUsersPermission->owner_id = $authUser->id; // `owner_id` should match with config('rbac.owner.id') $createUsersPermission->save(); $deleteUsersPermission = new Permission([ 'name' => 'Delete users', 'slug' => 'delete.users', ]); $deleteUsersPermission->owner_id = $authUser->id; // `owner_id` should match with config('rbac.owner.id') $deleteUsersPermission->save();
附加和分离权限
您可以将权限附加到角色或直接附加到特定用户(当然,也可以解除它们)。
use App\User; use Nigam214\RBAC\Models\Role; $authUser = User::where('email' = $email)->first(); $role = Role::find($roleId); $role->attachPermission($createUsersPermission, $authUser->id); // permission attached to a role $user = User::find($userId); $user->attachPermission($deleteUsersPermission, $authUser->id); // 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();
拒绝权限
您可以拒绝用户权限,或者您可以拒绝整个角色的权限。
为此,在附加权限时,只需传递一个布尔值为 false 的第二个参数。这将阻止该用户获得该权限,无论他们被分配了什么。拒绝的权限优先于继承和授予的权限。
use App\User; use Nigam214\RBAC\Models\Role; $authUser = User::where('email' = $email)->first(); $role = Role::find($roleId); $role->attachPermission($createUsersPermission, $authUser->id, FALSE); // Deny this permission to all users who have or inherit this role. $user = User::find($userId); $user->attachPermission($deleteUsersPermission, $authUser->id, FALSE); // Deny this permission to this user regardless of what roles they are in.
检查权限
if ($user->can('create.users') { // you can pass an id or slug // } if ($user->canDeleteUsers()) { // }
您可以通过与角色相同的方式检查多个权限。
继承
如果您不希望在应用程序中使用继承功能,只需在创建角色时忽略
parent_id
参数即可。
分配给其他角色的 parent_id
的角色在用户被分配或继承父角色时将自动继承。
以下是一个示例
您有 5 个管理员组。管理员、商店管理员、商店库存管理员、博客管理员和博客作家。
《管理员角色》是《商店管理员角色》和《博客管理员角色》的父角色。
而《商店管理员角色》是《商店库存管理员角色》的父角色。
并且《博客管理员角色》是《博客作家》的父角色。
这使得《管理员角色》可以继承《商店库存管理员角色》和《博客作家角色》。
但《商店管理员角色》仅继承《商店库存管理员角色》,
并且《博客管理员角色》仅继承《博客作家角色》。
另一个示例
在这里,admin
继承 admin.user
、admin.blog
和 blog.writer
。
而 admin.user
不继承任何内容,admin.blog
继承 blog.writer
。
没有内容继承 development
,development
也不继承任何内容。
实体检查
假设您有一篇文章,并想编辑它。这篇文章属于一个用户(文章表中有一个 user_id
列)。
use App\Article; use Nigam214\RBAC\Models\Permission; $authUser = User::where('email' = $email)->first(); $editArticlesPermission = new Permission([ 'name' => 'Edit articles', 'slug' => 'edit.articles', 'model' => 'App\Article', ]); $editArticlesPermission->owner_id = $authUser->id; // `owner_id` should match with config('rbac.owner.id') $editArticlesPermission->save(); $user->attachPermission($editArticlesPermission, $authUser->id); $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 语句的替代品。
Blade 扩展仅适用于
User
模型,并通过 Auth 获取 blade 页上的有效用户。
@role('admin') // @if(Auth::check() && Auth::user()->roleIs('admin')) // user is admin @endrole @permission('edit.articles') // @if(Auth::check() && Auth::user()->can('edit.articles')) // user can edit articles @endpermission @allowed('edit', $article) // @if(Auth::check() && Auth::user()->allowed('edit', $article)) // show edit button @endallowed @role('admin|moderator', 'all') // @if(Auth::check() && Auth::user()->roleIs('admin|moderator', 'all')) // user is admin and also moderator @else // something else @endrole
中间件
此包包含 VerifyRole
和 VerifyPermission
中间件。您必须在 app/Http/Kernel.php
文件中添加它们。
Blade 扩展仅适用于
User
模型,并通过 Auth 获取 blade 页上的有效用户。
/** * 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' => \Nigam214\RBAC\Middleware\VerifyRole::class, 'permission' => \Nigam214\RBAC\Middleware\VerifyPermission::class, ];
现在您可以轻松地保护您的路由。
$router->get('/example', [ 'as' => 'example', 'middleware' => 'role:admin', 'uses' => 'ExampleController@index', ]); $router->post('/example', [ 'as' => 'example', 'middleware' => 'permission:edit.articles', 'uses' => 'ExampleController@index', ]);
您还可以在 VerifyPermission
和 VerifyRole
中间件中传递多个参数,例如:role:admin,moderator,true
,最后一个参数将用于确定用户是否具有所有角色或只是所传递的任何角色,默认值为 false
。
如果出错,它会抛出 \Nigam214\RBAC\Exception\RoleDeniedException
或 \Nigam214\RBAC\Exception\PermissionDeniedException
异常。
您可以在 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 \Nigam214\RBAC\Exceptions\RoleDeniedException) { // you can for example flash message, redirect... return redirect()->back(); } return parent::render($request, $e); }
配置文件
您可以更改模型连接、slug 分隔符、模型路径,并且还有一个方便的模拟功能。有关更多信息,请查看配置文件。
更多信息
本项目基于 Bican/Roles。
许可
本软件包是免费软件,根据 MIT 许可协议分发。
我不在乎你如何使用它。
贡献
我老实说不知道我在做什么。如果你看到可以修复的东西,请在 develop 分支上提交一个 pull request!。