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

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:

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

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

    <?php
    $am = Yii::app()->authManager;
    $bizrule3 = 'return Yii::app()->user->id==$params["owner_id"];';  //will return true if both IDs match
    
    $am->createOperation('op3','op3',$bizrule3);
    $am->assign('op3','2'); 
    /*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:

<?php
public function actionViewObject($id)
{
    $obj = Obj::model()->findByPk($id);
    $params = array('owner_id'=>$obj->owner_id);
    if(Yii::app()->user->checkAccess('op3',$params))
    {
        //current user is the owner, so let him access the object.
    }else{
        //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