Controller中进行权限校验的方式:
第一种: 通过can函数来判断是否有某个权限的执行权限,如果没有则抛出未授权的异常,通常在Controller的Action开头使用,如下
/**
* 发布商品
*/
public function actionAdd ()
{
if(! can('shop-goods-add'))
{
throw new \common\base\UnauthorizedException();
}
.........
}
第二种:重写Controller的auths函数,返回访问权限配置:
/**
* 权限校验
*
* {@inheritDoc}
*
* @see \common\web\Controller::auths()
*/
public function auths ()
{
// 发布商品
$auths['add|add-images|success'] = 'shop-goods-add';
// 编辑商品
$auths['edit|edit-images|edit-gift'] = 'shop-goods-edit';
// 获取运费模板列表:必须拥有发布或者编辑的权限
$auths['freights'] = [
'shop-goods-add',
'shop-goods-edit'
];
// 商品上下架
$auths['offsale|onsale'] = 'shop-goods-sale';
// 商品删除
$auths['delete'] = 'shop-goods-delete';
return $auths;
}
现在主要对第二种进行详细解读:
1.模式:$auths[A] = B;
其中 A 为访问Action的Id,例如:actionAdd则A为add,actionAddGoods则A为add-goods;如果需要多个action对应一套权限代码,则多个actionId间用“|”分割。
其中 B 为权限代码,可以为字符串,多个权限可以用数组表示,并且多个权限间的逻辑关系为“或”,只要有用户拥有其中一个权限即可进行访问操作。
2.公式:$auths[A|A|A|A|A] = [B,B,B,B,B]