yii, easy and simple user role management using yii’s AuthManager

Step 1 : 
Create table :
CREATE TABLE User( 
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45),
`password` VARCHAR(254),
`title` VARCHAR(45),
PRIMARY KEY(`id`))
ENGINE = MyISAM;
Step 2 :
Add following code in config/main.php
'authManager'=>array(
'class'=>'CDbAuthManager',
'defaultRoles'=>array('authenticated', 'guest'),
),
 Below this code 
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=comocomo',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'abc123',
'charset' => 'utf8',
),

Step 3: 
Create model and crud for user table useing GII or Shell

Step 4: 

You can now go back to the authentication guide and alter your UserIdentity to access the User table and check access like so:
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;
else if($record->password!==md5($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
$this->setState('title', $record->title);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}

public function getId()
{
return $this->_id;
}
}
NOTE the override for getId -- this is VERY important for the authentication systems later.

Step 5 :
 
Now it's time to add more tables to the database for Authentication rule storage. 
In your main yii directory is a file called framework/web/auth/schema.sql . 
Run this file through your mysql command prompt (or editor of choice) and you will have three new tables set up for Authentication Management.
 They are: AuthAssignment, AuthItem, AuthItemChild

Step 6: 

Run following code once in by placing it an any executabelf ile of your yii web app:

$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);

$role = $auth->createRole('admin', 'administrator');
$auth->assign('admin',1); // adding admin to first user created 
$auth->save();

Step 7 : 
 
In your Controllers (we'll use the User as an example since we created that one above) you can now change the /protected/controllers/UserController.php accessRules function to allow only your admin to delete users as such:
public function accessRules(){
return array(
array('allow', // allow anyone to register
'actions'=>array('create'),
'users'=>array('*'), // all users
),
array('allow', // allow authenticated users to update/view
'actions'=>array('update','view'),
'roles'=>array('authenticated')
),
array('allow', // allow admins only to delete
'actions'=>array('delete'),
'roles'=>array('admin'),
),
array('deny', // deny anything else
'users'=>array('*'),
),
);
}


Step 8:

We need a task which allows users to update their own information. Back to the shell:
$auth=Yii::app()->authManager;
$bizRule = 'return Yii::app()->user->id==$params["User"]->id;';
$auth->createTask('updateSelf', 'update own information', $bizRule);

$role = $auth->getAuthItem('authenticated'); // pull up the authenticated role
$role->addChild('updateSelf'); // assign updateSelf tasks to authenticated users
 
 
Step 9:
Finally Open the UserController.php file again and move to the actionUpdate() function. We'll need to modify it as such: 

public function actionUpdate()
{
$model = $this->loadModel();

// set the parameters for the bizRule
$params = array('User'=>$model);
// now check the bizrule for this user
if (!Yii::app()->user->checkAccess('updateSelf', $params) &&
!Yii::app()->user->checkAccess('admin'))
{
throw new CHttpException(403, 'You are not authorized to perform this action');
}
...

7 comments

  1. Very nice article… i was trying while reading your post.. got stuck in step 6. where to put code meaning in which directory and how to execute considering i dont have shell access on server access

  2. Thanks for the great tutorial. Its better of than any other tut I have come accross in the internet, My only question is, How do I tackle step 6? The procedure there seems not very clear.

Leave a comment

Your email address will not be published. Required fields are marked *