开发者

Extended CWebUser and rewriting Yii accessControl

I have recently extended CWebUser class and now its has such useful methods:

Yii::app()->user->isAdmin;
Yii::ap开发者_如何学Pythonp()->user->isTeacher;
Yii::app()->user->isStudent;

Now there troubles with accessControl filter.

Before, to allow access only for admin, I used:

public function accessRules()
    {
        return array(
            array('allow',
                'actions'=>array('index','update', 'create', 'delete'),
                'users'=>array('admin'),
            ),
            array('deny',
                'users'=>array('*'),
            ),
        );
    } 

How to rewrite accessRules to delegate access only for users, who have an Yii::app()->user->isAdmin attribute?


You can add an option 'expression' to the configuration. Normally it gets a "$user" as argument. So you can do something like:

array('allow',
   'actions'=>array('index','update', 'create', 'delete'),
   'expression'=> '$user->isAdmin',
),

Note that I haven't tested this but I think it will work.

Take a look here for the rest.


Well it won't work because it knows Yii::app()->user as a CWebUser Instance and you developed the UserIdentity class so it would say 'CWebUser and its behaviors do not have a method or closure named "isAdmin"'! To use expressions like $user->isAdmin your should set isAdmin property throw the setState command which would use session to save that usually in authentication method so it would be something like this:

class UserIdentity extends CUserIdentity
{
    public function authenticate() 
    {
        //your authentication code

        //using your functions like $level=$this->isTeacher();
        //or $level=$this->isAdmin();
        $this->setState('isAdmin',$level);
    }
}

and now in the user controller in accessRules method you can have expressions

public function accessRules()
{
    return array(
        array('allow',
            'actions'=>array('action1','action2',...),
            'expression'=>'$user->isAdmin',
            //or Yii::app()->user->getState('isAdmin'),
        ),
        //...
    );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜