登录后如何设置用户角色
Yii::app()->user->login($identity, 0);?
在您的 WebUser 类中添加方法 getRole,如下所示:
class WebUser extends CWebUser {
private $_model = null;
function getRole() {
if($user = $this->getModel()) {
return $user->role;
}
}
private function getModel(){
if (!$this->isGuest && $this->_model === null){
$this->_model = User::model()->findByPk($this->id, array('select' => 'role'));
}
return $this->_model;
}
}
然后在config中配置你的用户组件
'user'=>array(
'class' => 'WebUser',
// …
),
然后添加您的 AuthManager 类(例如我使用 PhpAuthManager。不要忘记在您的配置文件中配置用户组件)
class PhpAuthManager extends CPhpAuthManager{
public function init(){
// auth.php in config directory consist your roles
if($this->authFile===null){
$this->authFile=Yii::getPathOfAlias('application.config.auth').'.php';
}
parent::init();
if(!Yii::app()->user->isGuest){
$this->assign(Yii::app()->user->role, Yii::app()->user->id);
}
}
}
你的 auth.php 是这样的:
return array(
'guest' => array(
'type' => CAuthItem::TYPE_ROLE,
'description' => 'Guest',
'bizRule' => null,
'data' => null
),
'admin' => array(
'type' => CAuthItem::TYPE_ROLE,
'description' => 'User',
'children' => array(
'guest', // extend all permission form guest user
),
'bizRule' => null,
'data' => null
),
);
然后在您的控制器过滤器中使用:
public function accessRules()
{
return array(
array('allow',
'actions'=>array('admin', 'onlyAdmin'),
// use roles key not user
'roles'=>array('admin'),
),
);
}
在你的行动或模板中:
if(Yii::app()->user->checkAccess('admin')){
echo "hello, I'm administrator";
}
查看更多内容:
http://www.yiiframework.com/wiki/65