Home  • Framework • Yii

Yii User Authentication using Database Table

As you may have found that the skeleton application already provides user authentication by checking if the username and password are both demo or admin. In this section, we will modify the corresponding code so that the authentication is done against the User database table. User authentication is performed in a class implementing the [IUserIdentity] interface. The skeleton application uses the UserIdentity class for this purpose. The class is stored in the file protected/components/UserIdentity.php. Note: This tutorial is for the developers who are able to install and create Yii skeleton app using command prompt and basic understanding on Yii MVC Ok, now follow the following steps to complete this tutorial: Step 1: Create an Yii skeleton app using command prompt. Step 2: Configure database and Gii tool for Yii application at the following files: a. protracted/config/main.php b. protracted/config/database.php Step 3: Create a database table and add a user in your database table as follows:
DROP TABLE IF EXISTS `test`.`user`;
CREATE TABLE  `test`.`user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `username` varchar(40) NOT NULL,
  `password` varchar(50) DEFAULT NULL,
  `email` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

insert into `test`.`user`(username,password,email) values('admin','111111','admin@yahoo.com');
Step 4: Enter [yii-app-root]/index.php?r=gii to you browser. Step 5: Create a user model with Gii Model Generator. Step 6: Update protracted/components/UserIdentity.php file with the following code:
<?php
class UserIdentity extends CUserIdentity
{	
	private $_id;	
	
	public function authenticate()
	{
		$user=User::model()->findByAttributes(array('username'=>$this->username));
		
		if($user===null){
			 $this->errorCode=self::ERROR_USERNAME_INVALID;
		}else{
			
			if($user->password!==$this->password){
				 $this->errorCode=self::ERROR_PASSWORD_INVALID;
			}else{				
			   $this->_id=$user->id;
               $this->username=$user->username;
               $this->errorCode=self::ERROR_NONE;
			}
			
		}	
		return !$this->errorCode;
	}	
	
	public function getId()
    {
        return $this->_id;
    }
	
}
Now try to login!

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd