1.開發(fā)必讀
bouncer 目錄下:\vendor\silber\bouncer\src 的bouncer為主文件
bouncer 數(shù)據(jù)庫模型:\vendor\silber\bouncer\src\Database 里面已經(jīng)把四個表的模型整理完畢
2.基本配置
自己的數(shù)據(jù)庫模型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為禁止!