1.开发必读
bouncer 目录下:\vendor\silber\bouncer\src 的bouncer为主文件
bouncer 数据库模型:\vendor\silber\bouncer\src\Database 里面已经把四个表的模型整理完毕
2.基本配置
自己的数据库模型User需配置
use Silber\Bouncer\Database\HasRolesAndAbilities 门面
并在class下面 写入 use HasRolesAndAbilities;
例如:
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Silber\Bouncer\Database\HasRolesAndAbilities;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword,HasRolesAndAbilities;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public static function userinfo()
{
return self::find(1);
}
}
3.控制器分配权限
1.分配角色
例如分配用户id=1为editor的角色
$users = User::find(1);
$info = $users->assign('editor');
var_dump($info);
2.分配能力(允许User id为1的用户修改$post(文章id=1的模型));
$users = User::find(1);
$post = artical::find(1);
$info = Bouncer::allow($users)->to('edit', $post);
var_dump($info);
3.检查权限
$users = User::find(1);
$post = artical::find(1);
$info = $users->can('edit', $post);
$info为bool值
另一种分配权限
1.分配角色(分配user id为2的用户为admin)
$users = User::find(2);
$info = $users->assign('admin');
var_dump($info);
2.为角色分配权限(设置角色admin拥有edit的权限)
$post = artical::find(2);
$info = Bouncer::allow('admin')->to('delete', $post);
var_dump($info);
3.检查权限(通过判断user id为2的用户(角色为admin)是否拥有此权限)
$users = User::find(2);
$post = artical::find(1);
$info = $users->can('delete', $post);
$info为bool值,true为拥有,flase为禁止!
网友评论