Hi,
Is there any way I can validate if a user has access to a certain action in a controller in its init() function and then generate a custom message if they don’t?
Currently, the user gets redirected to my error handler which renders a completely different layout. I’d like to check if users have access in the controller before the action is rendered to decide what to display or what to do.
Something like a "userHasAccess()" function would be great… not sure where to look though.
Thanks
In your main configuration file (main.php) add something like this:
'behaviors' => array('AccessBehavior'),
Then create a new class ‘AccessBehavior’ and drop it into your components directory.
Within that class put:
class AccessBehavior extends CBehavior
{
public function events()
{
return array_merge(parent::events(), array(
'onBeginRequest'=>'beginRequest',
));
}
public function beginRequest()
{
// put your access controls here
}
}
Thank you!
I’m not quite sure on how to use it though.
I don’t want to place accessRules on multiple places and would like to use the ones defined in the controller. How would I check if the user has access to requested action in my AccessBehavior?
In that case its better to put your access rule in your controller. I do it like this in the accessRules():
Replace the ‘users’ => array(’@’) (for example) with something like:
'expression'=>"Yii::app()->user->user_perm == 'admin'",
I register these permissions during login from a user table in /protected/components/useridentity/ eg.
public function authenticate()
{
$record=User::model()->findByAttributes(array('username'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==md5($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
if($record->user_perm == 'Member') {
$this->setState('user_perm', 'member');
} else {
$this->setState('user_perm', 'admin');
}
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}