Using bizrules in Yii RBAC System (examples with rights module)

Last updated:

Say you have a user whose username is user1 and whose id is 2.

We will play a little bit with Yii's RBAC system to get to know it a little better.

Bizrules (business rules) are just code snippets that return true or false that get run when access check is being performed. true lets the user access that item, false doesn't.

Anywhere inside a controller action, type (these are some examples):

  • bizrule that always returns true:

    $am = Yii::app()->authManager;
    $bizrule = "return 'bar'=='bar';";//will always return true
    $am->assign('op1','2'); /*user 'user1' will always be able to access item */
  • bizrule that always returns false

    $am = Yii::app()->authManager;
    $bizrule2 = "return 'bar'!='bar';";//will always return false
    $am->assign('op2','2'); /*user 'user1' will never be able to access item*/
  • bizrule that evaluates to true depending on current user's ID

    $am = Yii::app()->authManager;
    $bizrule3 = 'return Yii::app()->user->id==$params["owner_id"];';  //will return true if both IDs match
    /*user 'user1' will only be able to access item if his ID matched the ID passed as parameter*/

An example of how to use the last method would be this:

public function actionViewObject($id)
    $obj = Obj::model()->findByPk($id);
    $params = array('owner_id'=>$obj->owner_id);
        //current user is the owner, so let him access the object.
        //unauthorized access

You can perform the steps above even if you're using an extension rather than Yii's default RBAC model.

I am, for example, using the very good rights extension. It's a very good extension to make the boring parts of managing a full RBAC system, I did have to look into the code to fully understand the more subtle things mainly concerning bizRules and data.

In the bizRules, you can also use stuff that's viewable all around the Application, for example Yii::app()->user->XXX and Yii::app()->XXX and $_POST['xxx'] and Yii::app()->user->getState('xxx')

If you want to add methods to your Yii::app()->user object , you can add them in CWebUser class or any custom subclasses.

Dialogue & Discussion