Yii Framework Forum: Create Login form - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

Create Login form Rate Topic: -----

#1 User is offline   clive 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 07-April 12

Posted 02 June 2012 - 10:14 PM

Hi i'm only new to php framework. I want to ask how to create a simple login function, I have been reading a few basic tutorials but I cant find a way to create a login function with database.
0

#2 User is offline   bennouna 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 1,168
  • Joined: 05-January 12
  • Location:Morocco

Posted 03 June 2012 - 12:01 AM

Hello and welcome. In that case, head to the Larry Ullman tutorial series. One of his posts is exactly about login form with database.
0

#3 User is offline   J.J 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 126
  • Joined: 01-April 11

Posted 04 June 2012 - 05:02 AM

 clive, on 02 June 2012 - 10:14 PM, said:

Hi i'm only new to php framework. I want to ask how to create a simple login function, I have been reading a few basic tutorials but I cant find a way to create a login function with database.


At the first, you must create table, for example table user
And, here the script (sample)
CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `salt` varchar(32) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0;


Then, head to file protected/config/main.php, and modify:
(Assumption using database mysql)

'db'=>array(
    'connectionString' => 'mysql:host=localhost;dbname=test',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => 'root',
    'charset' => 'utf8',
),


And modify also gii:
'modules'=>array(
    // uncomment the following to enable the Gii tool		
    'gii'=>array(
    'class'=>'system.gii.GiiModule',
    'password'=>'gii',
    // If removed, Gii defaults to localhost only. Edit carefully to taste.
    'ipFilters'=>array('127.0.0.1','::1'),
    ),		
),


After that, login using default username and password (admin/admin), and then enter to gii page. (index.php?r=gii)
Then create model and give name User as Model in Model Generator, then generate CRUD through CRUD Generator.

Then, open in protected/models/User.php and add :

// hash password
public function hashPassword($password, $salt)
{
    return md5($salt.$password);
}
	
// password validation
public function validatePassword($password)
{
    return $this->hashPassword($password,$this->salt)===$this->password;
}
	
//generate salt
public function generateSalt()
{
    return uniqid('',true);
}
	
public function beforeValidate()
{
    $this->salt = $this->generateSalt();
    return parent::beforeValidate();
}
	
public function beforeSave()
{
    $this->password = $this->hashPassword($this->password, $this->salt);
    return parent::beforeSave();
}


Now, open file protected/views/user/_form.php, and remark like this:
<!-- 
	<div class="row">
		<?php echo $form->labelEx($model,'salt'); ?>
		<?php echo $form->textField($model,'salt',array('size'=>32,'maxlength'=>32)); ?>
		<?php echo $form->error($model,'salt'); ?>
	</div>
-->


And open your user CRUD page, then insert new username in that page.
After finishing insert data, you should view username, password and salt has been enrcrypted, then logout.

Open and modify, file protected/components/UserIdentity.php

class UserIdentity extends CUserIdentity
{
    private $_id;
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
	/*	
                remark default authentification
                $users=array(
			// username => password
			'demo'=>'demo',
			'admin'=>'admin',
		);
		if(!isset($users[$this->username]))
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		else if($users[$this->username]!==$this->password)
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
			$this->errorCode=self::ERROR_NONE;
		return !$this->errorCode;
        }
        */
            
            $users= User::model()->findByAttributes(array('username'=>$this->username));
            
            if($users===null) {
                $this->errorCode = self::ERROR_USERNAME_INVALID;                
            }
            else if(!$users->validatePassword($this->password)) {
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            }
            else {           
                $this->errorCode = self::ERROR_NONE;
                $this->_id = $users->id;
            }
            return !$this->errorCode;
	}
        
        public function getId() {
            return $this->_id;
        }
}


Then, head to login page, and enter username and password which inserted before in CRUD page.
The system should display success login page. Happy trying.. :rolleyes:
0

#4 User is offline   clive 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 07-April 12

Posted 07 June 2012 - 02:43 AM

wow..thank you everyone for sharing..I will try your suggestions God bless.. ;D
0

#5 User is offline   codesutra 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 596
  • Joined: 15-March 11
  • Location:India

Posted 07 June 2012 - 04:34 AM

Just download a Yii Framework package From This link. :)

You will get a Demo App also with it.So that you can check a User login system is already present in Blog demo app.

Try to go through this code.And come up with the problems which you are facing.;)

Welcome to the Yii Community. :)
CodeSutra
0

#6 User is offline   clive 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 07-April 12

Posted 07 June 2012 - 10:49 AM

 Yosua, on 04 June 2012 - 05:02 AM, said:

At the first, you must create table, for example table user
And, here the script (sample)
CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `salt` varchar(32) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0;


Then, head to file protected/config/main.php, and modify:
(Assumption using database mysql)

'db'=>array(
    'connectionString' => 'mysql:host=localhost;dbname=test',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => 'root',
    'charset' => 'utf8',
),


And modify also gii:
'modules'=>array(
    // uncomment the following to enable the Gii tool		
    'gii'=>array(
    'class'=>'system.gii.GiiModule',
    'password'=>'gii',
    // If removed, Gii defaults to localhost only. Edit carefully to taste.
    'ipFilters'=>array('127.0.0.1','::1'),
    ),		
),


After that, login using default username and password (admin/admin), and then enter to gii page. (index.php?r=gii)
Then create model and give name User as Model in Model Generator, then generate CRUD through CRUD Generator.

Then, open in protected/models/User.php and add :

// hash password
public function hashPassword($password, $salt)
{
    return md5($salt.$password);
}
	
// password validation
public function validatePassword($password)
{
    return $this->hashPassword($password,$this->salt)===$this->password;
}
	
//generate salt
public function generateSalt()
{
    return uniqid('',true);
}
	
public function beforeValidate()
{
    $this->salt = $this->generateSalt();
    return parent::beforeValidate();
}
	
public function beforeSave()
{
    $this->password = $this->hashPassword($this->password, $this->salt);
    return parent::beforeSave();
}


Now, open file protected/views/user/_form.php, and remark like this:
<!-- 
	<div class="row">
		<?php echo $form->labelEx($model,'salt'); ?>
		<?php echo $form->textField($model,'salt',array('size'=>32,'maxlength'=>32)); ?>
		<?php echo $form->error($model,'salt'); ?>
	</div>
-->


And open your user CRUD page, then insert new username in that page.
After finishing insert data, you should view username, password and salt has been enrcrypted, then logout.

Open and modify, file protected/components/UserIdentity.php

class UserIdentity extends CUserIdentity
{
    private $_id;
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
	/*	
                remark default authentification
                $users=array(
			// username => password
			'demo'=>'demo',
			'admin'=>'admin',
		);
		if(!isset($users[$this->username]))
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		else if($users[$this->username]!==$this->password)
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
			$this->errorCode=self::ERROR_NONE;
		return !$this->errorCode;
        }
        */
            
            $users= User::model()->findByAttributes(array('username'=>$this->username));
            
            if($users===null) {
                $this->errorCode = self::ERROR_USERNAME_INVALID;                
            }
            else if(!$users->validatePassword($this->password)) {
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            }
            else {           
                $this->errorCode = self::ERROR_NONE;
                $this->_id = $users->id;
            }
            return !$this->errorCode;
	}
        
        public function getId() {
            return $this->_id;
        }
}


Then, head to login page, and enter username and password which inserted before in CRUD page.
The system should display success login page. Happy trying.. :rolleyes:










thank you very much for your help i tried this codes, but i get an error when logging in a new user. The error is in "C:\xampp\htdocs\sampleyii\protected\components\UserIdentity.php" and it says "Property "UserIdentity._id" is not defined."
0

#7 User is offline   codesutra 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 596
  • Joined: 15-March 11
  • Location:India

Posted 07 June 2012 - 10:57 AM

 clive, on 07 June 2012 - 10:49 AM, said:

thank you very much for your help i tried this codes, but i get an error when logging in a new user. The error is in "C:\xampp\htdocs\sampleyii\protected\components\UserIdentity.php" and it says "Property "UserIdentity._id" is not defined."



 $this->_id = $users->id;


you are getting error due to this line.This code will assign a current user to the application after successful login.Please check it.
CodeSutra
0

#8 User is offline   codesutra 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 596
  • Joined: 15-March 11
  • Location:India

Posted 07 June 2012 - 11:00 AM

<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	private $_id;

	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		
		/*
		 * $user=User::model()->find('LOWER(usr_username)=?',array(strtolower($this->username)));
		if($user===null)
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		else if(!$user->validatePassword($this->password))
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
		{
			$this->_id=$user->id;
			$this->username=$user->username;
			$this->errorCode=self::ERROR_NONE;
		}
		 */
	    $user=User::model()->find('LOWER(usr_username)=?',array(strtolower($this->username)));

		if($user===null)
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		//else if ($user->usr_pass !== $this->password)
		else if(!$user->validatePassword($this->password))
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		elseif($user->usr_status == 0)
		    $this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
		{
                    $this->_id=$user->usr_id;
                    $this->username=$user->usr_username;
                    $this->setState('email', $user->usr_email);
                    $this->setState('firstname', $user->usr_first_name);
                    
                    $this->errorCode=self::ERROR_NONE;
		}
		return $this->errorCode==self::ERROR_NONE;
	}

	/**
	 * @return integer the ID of the user record
	 */
	public function getId()
	{
		return $this->_id;
	}
}



Use this code in your UserIdentity class.
CodeSutra
0

#9 User is offline   codesutra 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 596
  • Joined: 15-March 11
  • Location:India

Posted 07 June 2012 - 11:02 AM

And in your login action in controller file Use this kind of code to Redirect User on any pf the page

public function actionLogin()
	{
		$this->layout="login-layout";

		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login()){
					
				if(Yii::app()->user->returnUrl==Yii::app()->baseUrl.'/index.php'){

					$uid=Yii::app()->user->id;
					//User::model()->updateByPk($uid, array('last_login'=>time()));
					$this->redirect(array('site/index'));
				}else{
					$this->redirect(Yii::app()->user->returnUrl);
				}
			}
				
			//$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}


CodeSutra
0

#10 User is offline   clive 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 07-April 12

Posted 07 June 2012 - 11:08 AM

 jayant, on 07 June 2012 - 11:00 AM, said:

<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	private $_id;

	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		
		/*
		 * $user=User::model()->find('LOWER(usr_username)=?',array(strtolower($this->username)));
		if($user===null)
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		else if(!$user->validatePassword($this->password))
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
		{
			$this->_id=$user->id;
			$this->username=$user->username;
			$this->errorCode=self::ERROR_NONE;
		}
		 */
	    $user=User::model()->find('LOWER(usr_username)=?',array(strtolower($this->username)));

		if($user===null)
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		//else if ($user->usr_pass !== $this->password)
		else if(!$user->validatePassword($this->password))
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		elseif($user->usr_status == 0)
		    $this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
		{
                    $this->_id=$user->usr_id;
                    $this->username=$user->usr_username;
                    $this->setState('email', $user->usr_email);
                    $this->setState('firstname', $user->usr_first_name);
                    
                    $this->errorCode=self::ERROR_NONE;
		}
		return $this->errorCode==self::ERROR_NONE;
	}

	/**
	 * @return integer the ID of the user record
	 */
	public function getId()
	{
		return $this->_id;
	}
}



Use this code in your UserIdentity class.




thank you very much for your help,actually the first codes you gave worked already i found out the cause of error. i forgot to declare _id variable, i really appreciate your help thank you.its now working. :D
0

#11 User is offline   codesutra 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 596
  • Joined: 15-March 11
  • Location:India

Posted 07 June 2012 - 11:10 AM

 clive, on 07 June 2012 - 11:08 AM, said:

thank you very much for your help,actually the first codes you gave worked already i found out the cause of error. i forgot to declare _id variable, i really appreciate your help thank you.its now working. :D



That is great Great...!!

Cheer ! :lol:
CodeSutra
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users