I rewrote my controllers so that they extends BaseController. BaseController extends CController and assign user->role with user->id if user is not a guest.
Roles i’ve written in protected/data/auth.php
In protected/config/main.php i’ve determined component authManager (CPhpAuthManager).
In protected/components/UserIdentity.php i setup
Yii::app()->user->setState('role', $user->role);
And in each controller in accessRules i’m preventing to actions users with agreeable roles.
But if i’m logged by admin with role “administrator” in database - yii spoke that i’m unauthorized
I revised all code, but didn’t found why it’s not works.
I’m not fully understand you. Maybe you mean this:
public function accessRules()
{
return array(
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','create','update','list','show'),
'roles'=>array('administrator'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
Where put this? To BaseController? Now there is that:
<?php
class BaseController extends CController {
function init(){
// Для гостей у нас и так роль по умолчанию guest.
if(!Yii::app()->user->isGuest){
// Связываем роль, заданную в UserIdentity.authenticate(),
// с идентификатором пользователя, возвращаемым UserIdentity.getId().
Yii::app()->authManager->assign(Yii::app()->user->role, Yii::app()->user->id);
}
}
}
<?php
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$record = User::model()->findByAttributes(array('username'=>$this->username));
if($record===null){
$this->errorCode=self::ERROR_USERNAME_INVALID;
}elseif($record->password!==md5($this->password)){
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}else{
$this->_id=$record->id;
$this->setState('title', $record->title);
$this->setState('role', $record->role);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId(){
return $this->_id;
}
}
Notice that there’s a new model attribute - ‘role’ (string).
BaseController:
<?php
class BaseController extends CController{
public function init(){
// only for non-guests, because guest automatically assigned with 'guest' role
if(!Yii::app()->user->isGuest){
Yii::app()->authManager->assign(Yii::app()->user->role, Yii::app()->user->id);
}
}
}
Then just force your controllers to extend BaseController and check the role permissions in accessRules().