Question

This question may be basic and has been asked before, but I couldn't find it. I'm using Yii and I get trouble when differentiating users with action's access. I have a table called tbl_user, with fields like username, password, and role. When a user login, the system will set the loginAs state with his/her role, for example:

$role = "Super User"; //assume we get this role by querying the tbl_user
Yii::app()->user->setState("loginAs", $role)

In a controller, there are 4 actions, actionIndex, actionCreate, actionUpdate, and actionDelete. If a super user logins, these 4 action will be available. But if another user with different role logins, for example "administrator", all but actionDelete will be available. I tried this:

public function accessRules()
{
    return array(
        array('allow',
            'actions'=>array('index','create','update','delete'),
            'expression'=>'Yii::app()->user->getState("loginAs")=="Super User"'
        ),
        array('allow',
            'actions'=>array('index','create','update'),
            'expression'=>'Yii::app()->user->getState("loginAs")=="Administrator"',
        ),
    );
}

EDITED

The code above doesn't work. When I login as Administrator, I get error 403 for all 4 actions. Administrator should be able to access all except "delete". Is there another way for this? Any help will be appreciated.

Était-ce utile?

La solution

From http://www.yiiframework.com/doc/guide/1.1/en/topics.auth

The access rules are evaluated one by one in the order they are specified. The first rule that matches the current pattern (e.g. username, roles, client IP, address) determines the authorization result. If this rule is an allow rule, the action can be executed; if it is a deny rule, the action cannot be executed; if none of the rules matches the context, the action can still be executed.

So you should combine all the roles that can execute an action in a single expression i.e.

    array('allow',
        'actions'=>array('index','create','update'),
        'expression'=>'in_array(Yii::app()->user->getState("loginAs"),array("Super User","Administrator",...))'
    ),

    array('allow',
        'actions'=>array('delete'),
        'expression'=>'Yii::app()->user->getState("loginAs")=="Super User"'
    ),

Also if you follow the link above, you'll see how to implement RBAC in Yii. This can reduce your code to something like

    array('allow',
        'actions'=>array('index','create','update'),
        'roles'=>array("Super User","Administrator"),
    ),

Autres conseils

Also make sure that accessControl is enabled in you controller filter

public function filters()
{ 
    // ...
    return array('accessControl',);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top