Set user role to different users ( by session )

one can give different roles to user as shown below ,

setp : 1 => one can define session to different roles ,

        here I define session for admin ,

You can use this code in login controller …


if($model->validate() && $model->login())

	{

		...

                ..

		if($empData['E_ROLE']=='Admin'){              //  Find role="Admin" in database.

			Yii::app()->session['aid'] = $eid;

	  	        Yii::app()->session['adminUser'] = "admin";

			$this->redirect(array("adminPage"));

			}else{

				$this->redirect(array("otherPage"));

		}

	}





setp : 2 => Now you can define access rules in controller file as ...


public function accessRules()

{

	if(Yii::app()->session['adminUser'] == "admin"){

			$arr = array('create','update','index','view','admin','delete');    // give all access to admin

		}else{

			$arr = array('');          //  no access to other user

		}

		array('allow', // allow authenticated user to perform 'create' and 'update' actions

			'actions'=>$arr,

			'users'=>array('@'),

		),

		array('deny',  // deny all users

			'users'=>array('*'),

		),

	);

}





step : 3 => now you can unset session on logout ,


public function actionLogout()

	{

		if(isset(Yii::app()->session['adminUser']))

		{

			unset(Yii::app()->session['adminUser']);

			unset(Yii::app()->session['aid']);

		}

		Yii::app()->user->logout();

		$this->redirect(Yii::app()->homeUrl);

	}

You can manage in a very simple way.

Create your own user class wich extends CWebUser, and implement a function isAdmin:


public function getIsAdmin()

{

   return (whether the user is admin)

}

You can just set the rules with an expression:


public function accessRules()

{

                array('allow', // allow authenticated user to perform 'create' and 'update' actions

                        'actions'=>array('create','update','index','view','admin','delete'),

                        'expression'=>'Yii::app->user->isAdmin',

                ),

                array('deny',  // deny all users

                        'users'=>array('*'),

                ),

        );

}



If you use CDbAuthManager, you can set rules based on roles.

can you give better idea where&&how to use ,


public function getIsAdmin()

{

   return (whether the user is admin)

}

There are examples of the use of CWebUser

THIS

Be careful with storing user’s role in the session. You can’t revoke the role then, during session, and a session theoretically can last forever…

If you later change your mind and go for a plain old RBAC scheme, try rights. Very useful and very easy to use.

Thanks for the guide, but do not solve my problem.

I want to ask how to set roles in Yii? :unsure: