Revision #6 has been created by björnfan on Oct 25, 2010, 10:15:49 AM with the memo:
Fixed indent in code-blocks
« previous (#5) next (#7) »
Changes
Title
unchanged
How to setup RBAC with a php file
Category
unchanged
How-tos
Yii version
unchanged
Tags
unchanged
Authentication
Content
changed
[...]
Now we need to tell Yii when a user logs in what role s/he gets. I do this part in my UserIdentity class which takes care of my authentication for my blog. Here is how my UserIdentity class looks like:
```php
public function authenticate()
{
$user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
{
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else
{
$this->_id=$user->id;
$this->username=$user->username;
$auth=Yii::app()->authManager;
if(!$auth->isAssigned($user->role,$this->_id))
{
if($auth->assign($user->role,$this->_id))
{
Yii::app()->authManager->save();
}
{
if($auth->assign($user->role,$this->_id))
{
Yii::app()->authManager->save();
}
}
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}
```[...]
```php
$auth=Yii::app()->authManager; //initializes the authManager
if(!$auth->isAssigned($user->role,$this->_id)) //checks if the role for this user has already been assigned and if it is NOT than it returns true and continues with assigning it below
{
{
if($auth->assign($user->role,$this->_id)) //assigns the role to the user
{
Yii::app()->authManager->save(); //saves the above declaration
}
{
Yii::app()->authManager->save(); //saves the above declaration
}
}
```
>Info: Please see comments at the end of the lines for explanation on what every line of code does. It is important to remember that it is good practice to check if a roles has already been assigned becuase Yii assignes roles and does not delete them until you call the revoke() function. In canse you forget and try to re-assign a role Yii will return an error. Another important point is when you assign a role you must save it by calling Yii::app()->authManager->save();[...]
```php
public function actionLogout()
{
$assigned_roles = Yii::app()->authManager->getRoles(Yii::app()->user->id); //obtains all assigned roles for this user id
if(!empty($assigned_roles)) //checks that there are assigned roles
{
{
$auth=Yii::app()->authManager; //initializes the authManager
foreach($assigned_roles as $n=>$role)
{
{
if($auth->revoke($n,Yii::app()->user->id)) //remove each assigned role for this user
Yii::app()->authManager->save(); //again always save the result
}
}
}
}
Yii::app()->user->logout(); //logout the user
$this->redirect(Yii::app()->homeUrl); //redirect the user
}
```
## Adiitional/optional settings: ##
In your auth.php file you can use the following parameters:[...]