nh / access-control
通过角色和权限进行访问控制
README
通过 composer 安装包
composer require nh/access-control
发布角色对应的数据库和模型
php artisan vendor:publish --tag=access-control
要创建具有角色的模型,可以通过控制台命令创建迁移: –many 选项将创建一个具有多对多关系的 roleables 表
php artisan role:new {--model= : the name of the model (singular/lowercase)} {--many : is the model using many to many}
然后,如果您的模型只有一个角色,请将 HasAccess 特性添加到您的模型中
use Nh\AccessControl\Traits\HasAccess;
use HasAccess;
创建权限
您可以通过控制台命令创建权限: 您可以选择创建单个权限或为模型创建所有操作权限。
php artisan permission:new {--model= : the name of the model (singular/lowercase)} {--softDelete : is the model using SoftDelete}
检查访问权限
检查模型是否有任何角色
Auth::user()->hasAnyRole()
检查模型是否有某些角色: 您必须传递一个字符串或一个数组 默认情况下,它将在 guard 列上检查,但您也可以指定列
Auth::user()->hasRoles('admin')
Auth::user()->hasRoles('Administrator','name')
检查模型是否有某些权限: 您必须传递一个字符串或一个数组
Auth::user()->hasPermissions('only-admin')
检查模型是否有对模型/操作的访问权限: 您必须传递一个字符串用于模型和一个字符串或一个数组用于操作
// Request
hasAccess(string $model, mixed $actions = null, boolean $strict = false)
// Has ANY permission of the Role model
Auth::user()->hasAccess('role')
// Has ALL permission of the Role model
Auth::user()->hasAccess('role', null, true)
// Has a specific permission of the Role model
Auth::user()->hasAccess('role', 'update')
// Has ANY specific permission of the Role model
Auth::user()->hasAccess('role', ['update','delete'])
// Has ALL specific permission of the Role model
Auth::user()->hasAccess('role', ['update','delete'], true)
检查模型是否有超级权限: 您可以在配置文件中更改超级权限角色
// Return a boolean
Auth:user()->has_superpowers;
使用角色(s)限制模型
User::withRole('admin')->get();
User::withRole(['superadmin','admin'])->get();
User::withRole(2,'role_id')->get();
模型
该包附带两个模型
- 角色
- 权限
角色
角色具有 guard 和 name 属性。
您可以检索受限的权限
$role->restrictions();
您还可以从具有多个角色的模型检索受限的权限
Auth::user()->permission_restrictions;
您可以通过以下方式检查角色是否有权限: $permissions 可以是一个字符串或一个数组
$role->hasPermissions($permissions, $column)
您可以通过以下方式检查角色是否有权限:通过模型/操作 $actions 可以是一个字符串或一个数组 $strict 必须是一个布尔值,用于检查 AS ANY 或 AS ALL 权限
$role->hasPermissionsModel($model,$actions,$strict)
事件
您可以使用 RoleEvent 来触发角色访问发生的事件。
RoleEvent::dispatch('my-event', $model, $role, 1);
您可以使用 PermissionEvent 来触发角色/权限访问发生的事件。
PermissionEvent::dispatch('my-event', $role, $permission, 1);
门禁
您可以使用 set-roles 门禁来检查当前 Auth 是否可以设置角色。 $roles 必须是一个 ID 数组 在配置文件中,您可以指定受保护的角色和需要具有相同角色的 Auth 的角色
Gate::authorize('set-roles', $roles);
您可以使用 set-permissions 门禁来检查当前 Auth 是否可以为一个角色设置权限。 $permissions 必须是一个 ID 数组 在配置文件中,您可以指定受保护的角色和需要具有相同角色的 Auth 的角色
Gate::authorize('set-permissions', $permissions);