权限验证
框架中提供了一套完整的权限验证逻辑,可对路由下所有method
进行权限验证
用户需要在action中添加privilege
方法,具体返回字段如下
class testActionextends baseAction- {
private $key ='test' ;protected function privilege ()- {
return array (// 登录验证(在privilegeService中定义) 'login_required' =>array ('actions' =>'*' ,// 绑定action,*为所有method 'params' => [],// 传参(能获取到$this,不用另外传)可不传 'callBack' => [],// 验证失败回调函数, 可不传 - ),
'my_required' =>array ('actions' => ['index' ],// 对action_index进行验证 'params' => [$this ->key ],// 传参 'callBack' => [$this ,'test' ],// 验证失败后调用$this->test() - ),
- );
- }
// 根据逻辑被调用前会分别进行login_required和my_required验证,都成功后进入该方法 public function action_index ()- {
// do something - }
// my_required验证失败后调用, $action为验证失败的action(这里是$this) public function test ($action ,$error )- {
// do something - }
- }
然后在privilegeService
中定义验证方法
第一个参数$action为testAction,$key为params传入参数 public function my_required ($action ,$key =NULL )- {
if ($key ){// 通过校验 return $this ->correct ();// 等同于 return true; - }
else {// 校验失败,错误信息可通过$this->privilegeService->getError()获取 return $this ->error ('key not exist' );- }
- }
callBack
参数为校验失败时调用的方法,默认不填会抛出错误异常,程序不会再继续执行。
如果需要不同路由都使用同一个验证方法,而分别传入不同参数验证,可以使用requires
参数,用法参考下例:
class testActionextends baseAction- {
protected function privilege ()- {
return array ('privilege_required' =>array (// 根据不同路由传入相应操作权限 'requires' => [- [
'actions' =>['index' ,'view' ],'params' =>[Privilege::user ]],- [
'actions' =>['edit' ,'delete' ],'params' =>[Privilege::admin ]],- ],
'callBack' => [$this ,'test' ],// 验证失败后调用$this->test() - ),
- );
- }
// privilegeService public function privilege_required ($action ,$privilege )- {
if (App::$model ->person ->hasPrivilege ($privilege )){// 该用户有相应权限 return $this ->correct ();// 等同于 return true; - }
else {// 校验失败,错误信息可通过$this->privilegeService->getError()获取 return $this ->error ('forbidden' );- }
- }
注意:
使用requires
参数时,actions
和params
参数将被覆盖