Download the PHP package cloty/cloty-entrust without Composer
On this page you can find all versions of the php package cloty/cloty-entrust. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package cloty-entrust
Entrust (Laravel 5 Package)
cloty-entrust 是一个基于laravel5的简单验证角色权限的插件
内容
- Entrust (Laravel 5 Package)
- 内容
- 安装
- 配置
- 表结构说明
- Entrust Models
- EntrustRole
- EntrustPermission
- EntrustPermissionRole
- User
- 使用
- 例子
- 验证Roles&Permissions
- User ability & Entrust ability
- Blade
- Middleware
- 例子
安装
1) 安装entrust的方式很简单,直接添加到laravel5的composer.json安装即可。或者通过命令 composer update 安装:
2) 在 config/app.php中的 providers 引入服务提供者:
3) 同样的在 config/app.php 中的 aliases 引入:
4) 运行下面的命令,发布包配置文件 config/cloty-entrust.php 和 migrations:
5) 如果你需要引入中间件 Middleware (Laravel 5.*) 时,须在 app\Http\Kernel.php 中添加以下内容:
配置
可以通过编辑文件 config/entrust.php 变更对应的表名或者模型
cfc 可选参数1|2,为2时,错误返回back()->with('error', '权限不被允许')。
请求方式为ajax时,验证不通过统一返回response()->json(['status' => 0, 'msg' => '权限不被允许'])。
配置完后可以使用artisan迁移命令来运行它:
表结构说明
迁移之后,将出现四个新表:
entrust_roles— 角色表entrust_permissions— 权限表entrust_role_users— many-to-many 角色与用户之间的关系entrust_permission_roles— many-to-many 角色和权限之间的关系
Entrust Models
EntrustRole
EntrustPermission
EntrustPermissionRole
User
需要在你的 User模型引入 EntrustUserTrait trait。比如:
这将启用与角色的关系,并在用户模型中添加以下方法 entrustRoles(), hasRole($name), canDo($permission), and ability($roles, $permissions, $options)。
使用
例子
Controller use Entrust:
新增角色记录
接下来,让我们将它们分配给用户。 由于“HasRole”的特点,用户绑定角色将变得简单:
现在我们只需要为这些角色添加权限:
添加非p_id = 0的权限时,需指明上级p_id,子权限的命名方式 name 必须是用父级命名做前缀,如新增子权限post_create。
创建子权限时若不写前缀post_,Entrust将自动补全。多级子权限亦同。如 post_create_detail ...
验证Roles&Permissions
现在我们可以简单地检查角色和权限:
hasRole() 和 canDo() 验证角色和权限时都支持使用数组:
默认情况下,如果为用户提供了任何角色或权限,则该方法将返回true。 作为第二个参数传递“true”,指示该方法需要 所有 角色或权限:
还可以通过 Entrust 这个类验证角色或权限 canDo() 和 hasRole(),通过Entrust验证时,验证的是当前登录的用户:
您还可以使用占位符(通配符)来检查任何匹配的权限:
User ability & Entrust ability
可以使用 ability 功能进行更高级的权限验证。 它包含三个参数(roles,permissions,options):
roles需要验证的角色.permissions需要验证的权限.
roles 或 permissions 变量可以是逗号分隔的字符串或数组:
这将检查用户是否具有任何提供的角色和权限。 在这种情况下,它将返回true,因为用户是 admin 并具有post_create权限。
第三个参数 options为选填项,传递参数为数组:
validate_all该参数值为boolean,如果设置为true,则验证 所有roles或permissions都匹配时,则返回true.return_type指定返回的值格式.
例子:
Entrust中的ability()提供快捷验证当前登录的用户方法:
Blade
Entrust提供三个Blade模板指令。你可以在提供的指令中将参数直接传递到相应的方法:
Middleware
可以使用中间件entrust.role或entrust.permission过滤路由和路由组:
可以使用|符号作为 OR 运算符:
要使用 AND 验证时只需使用多个中间件实例:
对于更复杂的情况,可以使用 entrust.ability 中间件.使用时可传递3个参数: roles, permissions, validate_all
All versions of cloty-entrust with dependencies
illuminate/database Version 5.*
illuminate/support Version 5.*
illuminate/cache Version 5.*