Skip to main content

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');
    }
    ...  

Popular posts from this blog

Yii, return to previous url after login or logout

If you want to return to your previous url after login or logout try this : <?php $this -> redirect (Yii :: app () -> request -> urlReferrer ); ?> To set the return url to be the url that was before the login page or registeration page was called you can put following code in views/layouts/main.php file : <?php //this checks id the controller action is not 'login' then it keeps the current url in returnUrl if (CController :: getAction () -> id != 'login' ) { Yii :: app () -> user -> setReturnUrl (Yii :: app () -> request -> getUrl ()); } ?>

Yii2: Using csrf token

Yii2: Using csrf token First, if you do not understand what is the CSRF token? and why should we use it, please refer to the following link : https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) One of the new features of Yii2 is CSRF validation enabled by default. If you use ajax or basic form as follows : <form action='#' method='POST'> ........... </form> You will get an error exception : Bad Request (#400): Unable to verify your data submission That is because you do not submit csrf token. The easiest way if you dont care about csrf just disable it in main config : 'components' => [ 'request' => [ .... 'enableCsrfValidation'=>false, ], ..... ], Or in Controller : public function beforeAction($action) { $this->enableCsrfValidation = false; return parent::beforeAction($action); } So how to use Csrf Validation for your strong security website: * Wi