How to create a login with user and admin role?

Hello everyone,

I would like to seek your help on how to make a log in with user and admin role.

I have a database called mydb and I have a table called Login. On Login table I have these fields: type, login_name and password. I’m currently using yii’s default username and password: admin

I’ll be using the type field to do some restriction to other users. Can you please help me shed some light on this?

Regards,

Jose

When you install Yii application, in components folder there is class UserIndentity. There are static values for username and password defined in this class, but you can override these static values and connect this class with your database. This means this file is your starting point.

First step is to create a Model for your Login table in database. You can generate model using Gii tool.

When you create a model for Login table, you are able to search and find data in your database.

Change UserIdentity class like demonstrated here:





public function authenticate()

	{

		$user=Login::model()->findByAttributes(array("login_name"=>$this->username));//Find user in DB using username

		if(!isset($user))//User not found in the Database

			$this->errorCode=self::ERROR_USERNAME_INVALID;

                else if($user->password != $this->password)//Password is not good

                    $this->errorCode=self::ERROR_PASSWORD_INVALID;

		else{

			$this->errorCode=self::ERROR_NONE;//No error, user successfully logged in

			if($user->type == 'admin')//Set userType value if user is admin.

				$this->setState('userType', $user->type);

                }

		return !$this->errorCode;

	}



In controller add the following function:




public static function checkAccess(){

	$value= Yii::app()->user->getState('userType');

	if(isset([size=2]value[/size][size=2])){[/size]

		return true;

	}

	return false;

}

In accessRules filter add the following code:





public function accessRules() {

        return array(


 array('allow', 

                'actions'=>array("createUser","changeSettings"),

                'users' => array('@'),//Only logged in users may run actions above

                'expression'=>array("YourController","checkAccess")),//Logged in users must abide this rule also

)

And it should work.

hai… i tried but shows the error like

Fatal error: Cannot use isset() on the result of a function call (you can use "null !== func()" instead) in /opt/lampp/htdocs/yii_pms/protected/controllers/UserController.php on line 186

I’ve updated the code, try again.

Thanks, duri! I’ll look into this :lol: