[Solved] AuthManager and roles

Hello,

I created db schema and have set up AuthManager like that:



$auth=Yii::app()->authManager;


$bizRule='return !Yii::app()->user->isGuest;';


$auth->createRole('authenticated', 'authenticated user', $bizRule);


 


$bizRule='return Yii::app()->user->isGuest;';


$auth->createRole('guest', 'guest user', $bizRule);





$auth->createRole('administrator', 'administrator user');


$auth->assign('administrator','admin');


Now when i changed my controllers "accessRules" to



public function accessRules() {


  return array(


    array('allow',


      'actions'=>array('show'),


      'users'=>array('*'),


    ),


    


    array('allow',


      'actions'=>array('create'),


      'roles'=>array('administrator'),


    ),


    


    array('deny',  // deny all users


      'users'=>array('*'),


    ),


  );


}


I get "You are not authorized to perform this action." when i'm logged in as "admin" and try "create".

What might be wrong?

Is Yii::app()->user->id equal to 'admin'?

Quote

Is Yii::app()->user->id equal to 'admin'?

Yii::app()->user->id = 1 <- the id of the "admin"

By default, Yii is using user ID to check role assignment. So you need to change assign() call to use user ID, or extend CWebUser.checkAccess to check access using username.

Quote

By default, Yii is using user ID to check role assignment. So you need to change assign() call to use user ID, or extend CWebUser.checkAccess to check access using username.

Could i change my implementation of CUserIdentity to set id as username?

Yeah, that's fine too.

Quote

Yeah, that's fine too.

Got it to work if i used database id's in CDbAuthManager.assign, when i changed my CUserIdentity implementation and with CWebUser implementation.

Later feels like the correct solution :) Thanks qiang!

./protected/components/WebUser.php:



class WebUser extends CWebUser {


public function checkAccess($operation,$params=array()){


		return Yii::app()->getAuthManager()->checkAccess($operation,$this->getName(),$params);


	}


}


./protected/config/main.php



...


'components'=>array(


...


'user'=>array(


        'class'=>'WebUser',


        'allowAutoLogin'=>true,


),


...


Yes, your latter solution is better because it doesn't change your original intention.

Quote

$auth=Yii::app()->authManager;

$bizRule='return !Yii::app()->user->isGuest;';

$auth->createRole('authenticated', 'authenticated user', $bizRule);

$bizRule='return Yii::app()->user->isGuest;';

$auth->createRole('guest', 'guest user', $bizRule);

$auth->createRole('administrator', 'administrator user');

$auth->assign('administrator','admin');

Hi All!

I have a little question. As I can see - I need to create roles/assign only once, so I don't want to keep in my code createRole method calls.

Is there any opportunity to run code above without running any controller?

Put it in a console command and run it offline.