在权限控制过程中,会有一个默认的角色在:CAuthManager::defaultRoles属性中
return array(
'components'=>array(
'authManager'=>array(
'class'=>'CDbAuthManager',
'defaultRoles'=>array('user'),
),
),
);
默认角色会分配给每个用户,所以在定义Role时一般都会确定一下是否应用到用户
$bizRule = 'return Yii::app()->user->isUser()'; //isUser()在WebUser.php中定义
$auth->createRole('user','normal user',$bizRule);
在使用$bizRule中的规则时,切记return ...;,后面的分号一定要写,我就是被这个小问题坑了老长时间的
还有在使用这个checkAccess中用户角色时,他都是从auth_assignment表中获取表的角色,不能通过外部判断结构进行判断,比如:$role = $auth->createRole('root','超级管理员','return Yii::app()->user->isRoot()'); 这种情况在Yii::app()->user->checkAccess('root')判断永远是false的,它会先从auth_assignment表中获取角色对象:
yii中checkAccess部分源码:
public function checkAccess($itemName,$userId,$params=array()) {
$assignments=$this->getAuthAssignments($userId);
return $this->checkAccessRecursive($itemName,$userId,$params,$assignments);
}
public function getAuthAssignment($itemName,$userId){
$row=$this->db->createCommand()
->select()
->from($this->assignmentTable)
->where('itemname=:itemname AND userid=:userid', array(
':itemname'=>$itemName,
':userid'=>$userId))
->queryRow();
if($row!==false){
if(($data=@unserialize($row['data']))===false)
$data=null;
return new CAuthAssignment($this,$row['itemname'],$row['userid'],$row['bizrule'],$data);
}
else
return null;
}
同时在使用RBAC时,如果想要实现动态的切换权限的设置,则需要在外部接口判断该用户是否为root,user可以在WebUser中进行切换对象
<?php
public function changeRole($role = null) {
$role = strtolower($role);
if (($role == 'user') || ($role == 'root' && $this->isAdmin())) { /
$userID = Yii::app()->user->getId();
$auth = Yii::app()->authManager;
if ($auth->isAssigned($this->getRole(),$userID)) {
$auth->revoke($this->getRole(),$userID);
$auth->assign($role,$userID);
} esle {
$auth->assign($role,$userID);
}
}
}
?>
这个isAdmin()是指在外部判断该用户的最高权限,这样就可切换到它的下面的权限浏览
$this->getRole = $this->getState('-role');
$auth的其他方法可以查看yii提供的函数
这里就是通过对auth_assignment数据库表的修改实现动态切换用户的权限的 yii AuthManager