Techniques for Multiple User Types

Greetings all!

I’m a bit new to Yii/MVC, so forgive me if there is an obvious answer to this question. I’m wondering how to design my application. I have an application where I have several types of users. For the sake of discussion let’s say that we have these types:

  • Agent

  • Manager

  • Administrator

These three user types have nothing in common, so there’s no cascading or inheriting access. I simply need a user to log in to the app and then have the app check the user type. Admins see one set of pages, managers another, and agents still another.

My question is this: what are considered "proper" ways to address this scenario? E.g., is it as simple as having a controller for each type of user? Does anyone know of any example apps that I could examine to learn more?

TIA! Yii and its community are very cool. :)

-MC

Dear Friend,

If you have created user table ,add a column called role (for example).

When user is created or getting registered,You assign a value(admin,manager,agent) inside the role column.

When users login, the roles should be assigned. In order to do that, you have to modify

CUserIdentity::authenticate method in components directory.

I give an example.




public function authenticate()

	{       $user=User::model()->find('username=:username',array('username'=>$this->username));


		if($user==null)

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		else if(!$user->validatePassword($this->password))

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		else

		

		{Yii::app()->user->setState('role',$user->role);

                 $this->errorCode=self::ERROR_NONE;

		 return !$this->errorCode;}

	

}



Now when user login, you can call the value of his role by calling

Yii::app()->user-role.This is available as far as he gets logged in.

You can call it anywhere.

Now if he is admin,we can allow him to delete a record.

The following code allows only admin to carryout delete action in a controller.




public function actionDelete($id)

	{

		if(Yii::app()->user->role=='admin')

		{

			

			$this->loadModel($id)->delete();


			

		}

		else

			throw new CHttpException('You are not allowed to do this action');

	}



The following code allows both the manager and admin to carryout update action in a controller.




public function actionUpdate($id)

	{

		$model=$this->loadModel($id);

		if(Yii::app()->user->role=='admin'||Yii::app()->user->role=='manager') {


		if(isset($_POST['Post']))

		{

			$model->attributes=$_POST['Post'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('update',array(

			'model'=>$model,

		));

              }

           else

			throw new CHttpException('You are not allowed to do this action');

	}




This is very simple approach of authorization.(for example -blogsite)

Of course you can modify accessRules in the controller for some extra control.