yiiaccess-rules

How to get user permission from a database in Yii


I am very very new to Yii. I am developing a real world example. I have a table,hence a model, called user which gets the data from database. Three main fields in Database are username,password and userRole. Username and password work just fine. All I need to look at the userRole in database and based on that, assign a role to a user. For example is the user's userRole field ==1, the user is admin and can Create, Read,Update and Delete (CRUD). But if user's userRole ==2, user can Update and Create but not delete. I tried to do it with 'expression' ib accessRules() in UserController.php but it didnt work. Then I read about it and found I should do it with role. That's what I wrote:

public function accessRules()
    {
        $auth = Yii::app()->authManager;

        $auth->createOperation('createUser','create a user');
        $auth->createOperation('updateUser','update a user');
        $auth->createOperation('deleteUser','delete a user');

        $role=$auth->createRole('creator');
        $role->addChild('createUser');

        $role=$auth->createRole('updater');
        $role->addChild('updateUser');

        $role=$auth->createRole('deleter');
        $role->addChild('deleteUser');


        return array(
................................
        array('allow',
            'actions'=>array('create','update'),
            'users'=>array('@'),
            'roles'=>????,

.....................

??? is where I have no idea what to do. Am I defining the createOperation/addChild in a right place/file? How can I use 'roles' in the returning array? Also where should I get the userRole from Database?

I am desperately looking for answer as Yii Forum is not active

Thank you


Solution

  • you must assign role(s) to logged user (or by known user id)

    $auth->assign('creator',user()->id);
    $auth->assign('updater', 102); //102 as user id
    //...
    

    And in accessRules you must write

    'actions'=>array('create','update'),
    'roles'=>array('creator','updater'),
    

    Is this answeryou are looking for?