[SOLVED]User Login With DB

I want to login using the details stored inside a DB.After going through several topics and forums. i edited my Useridentity.php and Login.php files. But nothing is working for me.Can someone pls help.

My useridentity code


public function authenticate()

	{

			$user = TblUser::model()->findByAttributes(array('username'=>$this->username));


		if ($user===null) {

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		} else if ($user->password !== SHA1($this->password) ) { 

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		} else { // Okay!

		    $this->errorCode=self::ERROR_NONE;

		   

		    

		}

		return !$this->errorCode;

	}

loginform.php


public function rules()

{

	return array(

		array('username, password', 'required'),

		array('password', 'authenticate'),

	);

}


	

	public function authenticate($attribute,$params)

	{

		if(!$this->hasErrors())  // we only want to authenticate when no input errors

		{

			$identity=new UserIdentity($this->username,$this->password);

			$identity->authenticate();

			switch($identity->errorCode)

			{

				case UserIdentity::ERROR_NONE:

					Yii::app()->user->login($identity);

					break;

				case UserIdentity::ERROR_USERNAME_INVALID:

					$this->addError('username','Username is incorrect.');

					break;

				default: // UserIdentity::ERROR_PASSWORD_INVALID

					$this->addError('password','Password is incorrect.');

					break;

			}

		}

	}

sitecontroller.php


public function actionLogin()

	{

		$model=new LoginForm;


		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

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

		{

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

			

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

				$this->redirect(Yii::app()->user->returnUrl);

		}

		$this->render('login',array('model'=>$model));

	}



Hi , refer following steps.

step : 1

first you have to override id using getId() function , I post here working code of UserIdentity ,


class UserIdentity extends CUserIdentity

{

   private $_id;

   public function authenticate()

   {

       $record=Employee::model()->findByAttributes(array('E_EMAIL'=>$this->username));  // here I use Email as user name which comes from database

       if($record===null)

               {

                       $this->_id='user Null';

         			   $this->errorCode=self::ERROR_USERNAME_INVALID;

               }

       else if($record->E_PASSWORD!==$this->password)            // here I compare db password with passwod field

               {        $this->_id=$this->username;

                       $this->errorCode=self::ERROR_PASSWORD_INVALID;

               }

	 else if($record['E_STATUS']!=='Active')                //  here I check status as Active in db

               {        

			   		$err = "You have been Inactive by Admin.";

			        $this->errorCode = $err;

               }

	

       else

       {  

          $this->_id=$record['E_NAME'];

	   $this->setState('title', $record['E_NAME']);

           $this->errorCode=self::ERROR_NONE;


       }

       return !$this->errorCode;

   }


   public function getId()       //  override Id

   {

       return $this->_id;

   }

}




step : 2

here is my loginForm function ,


public function authenticate($attribute,$params)

	{

		if(!$this->hasErrors())

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			if(!$this->_identity->authenticate())

				$this->addError('password','Incorrect username or password.');

		}

	}

step : 3

finaly i use controller as ,


public function actionLogin()

	{

		$model=new LoginForm;

		

		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}


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

		{

		

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

			

			// validate user input and redirect to the previous page if valid

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

			{

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

			

			}

				

		}

                	$this->render('login',array('model'=>$model));

}



Thanx a lot for the reply…

Fixed it.

I am not sure where I have to put this post so I decided to reply this is topic.

I have generated Model and CRUD with gii and as you know it comes with to username/password pairs namely

admin/admin and demo/demo. I have 2 questions:

  1. How can we have more than two userename/password pairs with separate task assign to each. For example, I want to define two other usernames/password like user1/user1 and user2/user2. I want user 1 to be able to view and add and user2 view/add/delete.

  2. What if I dont want to set usernames and password UserIdentity.php and instead, want to retrieve from a Database? The simplest table is a table with two columns, User name and password.

I am really beginner to Yii and Gii so this question may look like straight forward.

Thank you

Yes saham here is your answer,

First refer above code for user login from database,

now as i post in step:1 see else part,


else

       {  

          $this->_id=$record['E_NAME'];

           $this->setState('title', $record['E_NAME']);

           [b]$this->setState('userType', $record['userType']); [/b]  // by here you can set state define in db ( admin or normal user )

           $this->errorCode=self::ERROR_NONE;


       }



now you have to use your controller for page redirect at different location by userType, see below code for controller


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

			{

				if(Yii::app()->user->userType=='Admin'){        // we had set above

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

				}elseif(Yii::app()->user->userType=='User'){

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

				}

			}

simple… :)

I had the same problem and follwed your steps to authenticate user from database but it did’nt workout for me. I had store value directly in the database uing inser query and not using the framework.

UserIdentity.php

<?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 using the User data model.

  • @return boolean whether authentication succeeds.

*/

public function authenticate()

{

&#036;user=User::model()-&gt;findByAttributes(array('username'=&gt;&#036;this-&gt;username));


if(&#036;user===null)


{


	&#036;this-&gt;errorCode=self::ERROR_USERNAME_INVALID;


}


else if(&#036;user-&gt;password&#33;==&#036;this-&gt;password)


{


		&#036;this-&gt;errorCode=self::ERROR_PASSWORD_INVALID;


}


else


{	


		&#036;this-&gt;_id = &#036;user-&gt;id;


		&#036;this-&gt;errorCode == self::ERROR_NONE;


}





return &#33;&#036;this-&gt;errorCode;

}

public function getId()

{

return &#036;this-&gt;_id;

}

}

LoginForm.php

<?php

/**

  • LoginForm class.

  • LoginForm is the data structure for keeping

  • user login form data. It is used by the ‘login’ action of ‘SiteController’.

*/

class LoginForm extends CFormModel

{

public &#036;username;


public &#036;password;


public &#036;rememberMe=false;





private &#036;_identity;





/**


 * Declares the validation rules.


 * The rules state that username and password are required,


 * and password needs to be authenticated.


 */


public function rules()


{


	return array(


		// username and password are required


		array('username, password', 'required', 'on'=&gt;'login'),


		// rememberMe needs to be a boolean


		array('rememberMe', 'boolean'),


		// password needs to be authenticated


		array('password', 'authenticate'),


	);


}





/**


 * Declares attribute labels.


 */


public function attributeLabels()


{


	return array(


		'rememberMe'=&gt;'Remember me next time',


	);


}





/**


 * Authenticates the password.


 * This is the 'authenticate' validator as declared in rules().


 */


public function authenticate(&#036;attribute,&#036;params)


{


	


                    &#036;this-&gt;_identity=new UserIdentity(&#036;this-&gt;username,&#036;this-&gt;password);


                    if(&#33;&#036;this-&gt;_identity-&gt;authenticate())


                            &#036;this-&gt;addError('password','Incorrect username or password.');


            








}


/**


 * Logs in the user using the given username and password in the model.


 * @return boolean whether login is successful


 */


public function login()


{


	if(&#036;this-&gt;_identity===null)


	{


		&#036;this-&gt;_identity=new UserIdentity(&#036;this-&gt;username,&#036;this-&gt;password);


		&#036;this-&gt;_identity-&gt;authenticate();


	}


	if(&#036;this-&gt;_identity-&gt;errorCode===UserIdentity::ERROR_NONE)


	{


		&#036;duration=&#036;this-&gt;rememberMe ? 0 : 0; 


		Yii::app()-&gt;user-&gt;login(&#036;this-&gt;_identity,&#036;duration);


		return true;


	}


	else


		return false;


}

}

SiteController.php

<?php

class SiteController extends Controller

{

/**


 * Declares class-based actions.


 */


public function actions()


{


	return array(


		// captcha action renders the CAPTCHA image displayed on the contact page


		'captcha'=&gt;array(


			'class'=&gt;'CCaptchaAction',


			'backColor'=&gt;0xFFFFFF,


		),


		// page action renders &quot;static&quot; pages stored under 'protected/views/site/pages'


		// They can be accessed via: index.php?r=site/page&amp;view=FileName


		'page'=&gt;array(


			'class'=&gt;'CViewAction',


		),


	);


}





/**


 * This is the default 'index' action that is invoked


 * when an action is not explicitly requested by users.


 */


public function actionIndex()


{


	// renders the view file 'protected/views/site/index.php'


	// using the default layout 'protected/views/layouts/main.php'


	&#036;this-&gt;render('index');


}





/**


 * This is the action to handle external exceptions.


 */


public function actionError()


{


    if(&#036;error=Yii::app()-&gt;errorHandler-&gt;error)


    {


    	if(Yii::app()-&gt;request-&gt;isAjaxRequest)


    		echo &#036;error['message'];


    	else


        	&#036;this-&gt;render('error', &#036;error);


    }


}





/**


 * Displays the contact page


 */


public function actionContact()


{


	&#036;model=new ContactForm;


	if(isset(&#036;_POST['ContactForm']))


	{


		&#036;model-&gt;attributes=&#036;_POST['ContactForm'];


		if(&#036;model-&gt;validate())


		{


			&#036;headers=&quot;From: {&#036;model-&gt;email}&#092;r&#092;nReply-To: {&#036;model-&gt;email}&quot;;


			mail(Yii::app()-&gt;params['adminEmail'],&#036;model-&gt;subject,&#036;model-&gt;body,&#036;headers);


			Yii::app()-&gt;user-&gt;setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');


			&#036;this-&gt;refresh();


		}


	}


	&#036;this-&gt;render('contact',array('model'=&gt;&#036;model));


}





/**


 * Displays the login page


 */


public function actionLogin()


{


	&#036;model=new LoginForm;





	// if it is ajax validation request


	if(isset(&#036;_POST['ajax']) &amp;&amp; &#036;_POST['ajax']==='login-form')


	{


		echo CActiveForm::validate(&#036;model);


		Yii::app()-&gt;end();


	}





	// collect user input data


	if(isset(&#036;_POST['LoginForm']))


	{


		&#036;model-&gt;attributes=&#036;_POST['LoginForm'];


		// validate user input and redirect to the previous page if valid


		if(&#036;model-&gt;validate() &amp;&amp; &#036;model-&gt;login())


			&#036;this-&gt;redirect(Yii::app()-&gt;user-&gt;returnUrl);


	}


	// display the login form


	&#036;this-&gt;render('login',array('model'=&gt;&#036;model));


}





/**


 * Logs out the current user and redirect to homepage.


 */


public function actionLogout()


{


	Yii::app()-&gt;user-&gt;logout();


	&#036;this-&gt;redirect(Yii::app()-&gt;homeUrl);


}

}

Hi everybody , I’m new to yii , and thnaks to your help i managed to get the user login through my database working , but know i can’t logout anymore as it shows me a page with message this when I click logout


Error 404 

The system is unable to find the requested action "logout".

The exception generated is




06:46:55.130893	error	exception.CHttpException.404	

exception 'CHttpException' with message 'The system is unable to find the

requested action "logout".' in


#0 C:\wamp\www\YiiRoot\framework\web\CController.php(271):

CController->missingAction('logout')

#1 C:\wamp\www\YiiRoot\framework\web\CWebApplication.php(283):

CController->run('logout')

#2 C:\wamp\www\YiiRoot\framework\web\CWebApplication.php(142):

CWebApplication->runController('site/logout')

#3 C:\wamp\www\YiiRoot\framework\base\CApplication.php(162):

CWebApplication->processRequest()

#4 C:\wamp\www\ChefsClub\index.php(15): CApplication->run()

#5 {main}


REQUEST_URI=/ChefsClub/index.php/site/logout

HTTP_REFERER =localhost/ChefsClub/index.php/site/page?view=about


---




What have I done wrong ?

Problem Solved now .I figured out that I accidently deleted the logout function :P

Hi, I’m trying this, but when I login it keeps me saying there’s incorrect user or password, I debugged $record and it always sends NULL, I’ dunno what can be doing wrong. Hope you can help me.

here is my Users and passwords model:




class Login extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return Login the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'login';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('id, user, password', 'required'),

			array('id', 'numerical', 'integerOnly'=>true),

			array('email', 'safe'),

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, user, password, email', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id' => 'ID',

			'user' => 'User',

			'password' => 'Password',

			'email' => 'Email',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('id',$this->id);

		$criteria->compare('user',$this->user,true);

		$criteria->compare('password',$this->password,true);

		$criteria->compare('email',$this->email,true);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}

}



USerIdentity




private $_id;

   public function authenticate()

   {

       $record=Login::model()->findByAttributes(array('user'=>$this->username)); 

       var_dump($record);

       die(); // here I use Email as user name which comes from database

       if($record===null)

               {

                       

                                   $this->errorCode=self::ERROR_USERNAME_INVALID;

               }

       else if($user->password!==$this->password)            // here I compare db password with passwod field

               {     

                       $this->errorCode=self::ERROR_PASSWORD_INVALID;

               }

         

        

       else

       {  

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

           $this->errorCode=self::ERROR_NONE;


       }

       return !$this->errorCode;

   }


   public function getId()       //  override Id

   {

       return $this->_id;

   }



LoginForm


class LoginForm extends CFormModel

{

	public $username;

	public $password;

	public $rememberMe;


	private $_identity;


	/**

	 * Declares the validation rules.

	 * The rules state that username and password are required,

	 * and password needs to be authenticated.

	 */

	public function rules()

	{

		return array(

			// username and password are required

			array('username, password', 'required'),

			// rememberMe needs to be a boolean

			array('rememberMe', 'boolean'),

			// password needs to be authenticated

			array('password', 'authenticate'),

		);

	}


	/**

	 * Declares attribute labels.

	 */

	public function attributeLabels()

	{

		return array(

			'rememberMe'=>'Remember me next time',

		);

	}


	/**

	 * Authenticates the password.

	 * This is the 'authenticate' validator as declared in rules().

	 */

	public function authenticate($attribute,$params)

        {

               $this->_identity=new UserIdentity($this->username,$this->password);

					if(!$this->_identity->authenticate())

					$this->addError('password','Incorrect username or password.');

        }

	/*public function authenticate($attribute,$params)

	{

		if(!$this->hasErrors())

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			if(!$this->_identity->authenticate())

				$this->addError('password','Incorrect username or password.');

		}

	}*/


	/**

	 * Logs in the user using the given username and password in the model.

	 * @return boolean whether login is successful

	 */

	public function login()

	{

		if($this->_identity===null)

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			$this->_identity->authenticate();

		}

		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)

		{

			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

			Yii::app()->user->login($this->_identity,$duration);

			return true;

		}

		else

			return false;

	}

}

And SitesController


public function actionLogin()

        {

                $model=new LoginForm;

                

                if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')

                {

                        echo CActiveForm::validate($model);

                        Yii::app()->end();

                }


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

                {

                

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

                        

                        // validate user input and redirect to the previous page if valid

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

                        {

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

                        

                        }

                                

                }

                        $this->render('login',array('model'=>$model));

}

Thanks!!

Hey,

Your code in UserIdentity is as below,

[color="#000000"]$record[/color][color="#666600"]=[/color][color="#660066"]Login[/color][color="#666600"]::[/color][color="#000000"]model[/color]color="#666600"->[/color][color="#000000"]findByAttributes[/color]color="#666600";[/color]

Now just check with,

echo $this->username;[size="2"] // This must come from form field and should not be null[/size]

your above line will generate query model "select * from login where user="$this->username"";

[/size]

Ok, when I do echo $this->username; it sends me the user correctly, if I do a var_dump($record); die(); it sends mi this big code:


object(User)#37 (12) { ["_md":"CActiveRecord":private]=> object(CActiveRecordMetaData)#23 (5) { ["tableSchema"]=> object(CDbTableSchema)#27 (<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> { ["name"]=> string(4) "user" ["rawName"]=> string(6) "'user'" ["primaryKey"]=> NULL ["sequenceName"]=> NULL ["foreignKeys"]=> array(0) { } ["columns"]=> array(5) { ["id"]=> object(CSqliteColumnSchema)#28 (15) { ["name"]=> string(2) "id" ["rawName"]=> string(4) ""id"" ["allowNull"]=> bool(false) ["dbType"]=> string(7) "integer" ["type"]=> string(7) "integer" ["defaultValue"]=> NULL ["size"]=> NULL ["precision"]=> NULL ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } ["username"]=> object(CSqliteColumnSchema)#29 (15) { ["name"]=> string(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> "username" ["rawName"]=> string(10) ""username"" ["allowNull"]=> bool(false) ["dbType"]=> string(12) "varchar(254)" ["type"]=> string(6) "string" ["defaultValue"]=> NULL ["size"]=> int(254) ["precision"]=> int(254) ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } ["password"]=> object(CSqliteColumnSchema)#30 (15) { ["name"]=> string(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> "password" ["rawName"]=> string(10) ""password"" ["allowNull"]=> bool(false) ["dbType"]=> string(12) "varchar(254)" ["type"]=> string(6) "string" ["defaultValue"]=> NULL ["size"]=> int(254) ["precision"]=> int(254) ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } ["title"]=> object(CSqliteColumnSchema)#31 (15) { ["name"]=> string(5) "title" ["rawName"]=> string(7) ""title"" ["allowNull"]=> bool(true) ["dbType"]=> string(11) "varchar(45)" ["type"]=> string(6) "string" ["defaultValue"]=> NULL ["size"]=> int(45) ["precision"]=> int(45) ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } ["email"]=> object(CSqliteColumnSchema)#32 (15) { ["name"]=> string(5) "email" ["rawName"]=> string(7) ""email"" ["allowNull"]=> bool(true) ["dbType"]=> string(4) "text" ["type"]=> string(6) "string" ["defaultValue"]=> NULL ["size"]=> NULL ["precision"]=> NULL ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } } ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } ["columns"]=> array(5) { ["id"]=> object(CSqliteColumnSchema)#28 (15) { ["name"]=> string(2) "id" ["rawName"]=> string(4) ""id"" ["allowNull"]=> bool(false) ["dbType"]=> string(7) "integer" ["type"]=> string(7) "integer" ["defaultValue"]=> NULL ["size"]=> NULL ["precision"]=> NULL ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } ["username"]=> object(CSqliteColumnSchema)#29 (15) { ["name"]=> string(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> "username" ["rawName"]=> string(10) ""username"" ["allowNull"]=> bool(false) ["dbType"]=> string(12) "varchar(254)" ["type"]=> string(6) "string" ["defaultValue"]=> NULL ["size"]=> int(254) ["precision"]=> int(254) ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } ["password"]=> object(CSqliteColumnSchema)#30 (15) { ["name"]=> string(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> "password" ["rawName"]=> string(10) ""password"" ["allowNull"]=> bool(false) ["dbType"]=> string(12) "varchar(254)" ["type"]=> string(6) "string" ["defaultValue"]=> NULL ["size"]=> int(254) ["precision"]=> int(254) ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } ["title"]=> object(CSqliteColumnSchema)#31 (15) { ["name"]=> string(5) "title" ["rawName"]=> string(7) ""title"" ["allowNull"]=> bool(true) ["dbType"]=> string(11) "varchar(45)" ["type"]=> string(6) "string" ["defaultValue"]=> NULL ["size"]=> int(45) ["precision"]=> int(45) ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } ["email"]=> object(CSqliteColumnSchema)#32 (15) { ["name"]=> string(5) "email" ["rawName"]=> string(7) ""email"" ["allowNull"]=> bool(true) ["dbType"]=> string(4) "text" ["type"]=> string(6) "string" ["defaultValue"]=> NULL ["size"]=> NULL ["precision"]=> NULL ["scale"]=> NULL ["isPrimaryKey"]=> bool(false) ["isForeignKey"]=> bool(false) ["autoIncrement"]=> bool(false) ["comment"]=> NULL ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } } ["relations"]=> array(0) { } ["attributeDefaults"]=> array(0) { } ["_model":"CActiveRecordMetaData":private]=> object(User)#22 (12) { ["_md":"CActiveRecord":private]=> *RECURSION* ["_new":"CActiveRecord":private]=> bool(false) ["_attributes":"CActiveRecord":private]=> array(0) { } ["_related":"CActiveRecord":private]=> array(0) { } ["_c":"CActiveRecord":private]=> NULL ["_pk":"CActiveRecord":private]=> NULL ["_alias":"CActiveRecord":private]=> string(1) "t" ["_errors":"CModel":private]=> array(0) { } ["_validators":"CModel":private]=> NULL ["_scenario":"CModel":private]=> string(0) "" ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } } ["_new":"CActiveRecord":private]=> bool(false) ["_attributes":"CActiveRecord":private]=> array(5) { ["id"]=> string(1) "2" ["username"]=> string(5) "test2" ["password"]=> string(5) "pass2" ["title"]=> string(0) "" ["email"]=> string(17) "test2@example.com" } ["_related":"CActiveRecord":private]=> array(0) { } ["_c":"CActiveRecord":private]=> NULL ["_pk":"CActiveRecord":private]=> NULL ["_alias":"CActiveRecord":private]=> string(1) "t" ["_errors":"CModel":private]=> array(0) { } ["_validators":"CModel":private]=> NULL ["_scenario":"CModel":private]=> string(6) "update" ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL }

What can be wrong? :c

What is the $user variable in the UserIdentity.php file? It is not defined, but it is used to compare the password that the user enters. Try changing it to $record->password instead of $user->password.

Thank you! Now is working:DDD

Hi Kiran,

I just wan’t to ask about the database. Can we use this model to a simple database’s table with only 2 fields included like username & password? I’m quite newbie with this. Thanks.

Yes, why not?

[/size]

Really simple! And works fine! Thanks Kiran.

Only one thing I’m courious to know, can You explain the else statement part I’ve quote below?

Thanks before.




If(UserName Or Password mismatch)

{


}else{

	// Login success

	// This will use to set any user state or session on successful login

}

Hi All,… I’m a verry newbie in yii :)

Would u like to help me please,…?

i followed the steps over,.

i got nothing error, but when i’m entering username and password then trying to log in, the site back to login form again without anything happend.

I have 4 fields in my db such as id, username, password and level.

Please help, i dont know how to solve this… :(

And here is my code

User.php


class User extends CActiveRecord

{

    //memproses data setelah validasi

    protected function afterValidate(){

        parent::afterValidate();

        

        $this->password = $this->encrypt($this->password);

    }

    

    protected function encrypt($value){

        return md5($value);

    }

    

     protected function validatePassword ($password)

    {

        return ($this->password==md5($password));

    }

    

    protected function beforeSave()

    {

        if (parent::beforeSave())

        {

            if ($this->isNewRecord)

            {

                $this->setAttribute('password',  md5($this->password));

            }

            return TRUE;

        }

        return FALSE;

    }

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()

	{

            

            $record=User::model()->findByAttributes(array('username'=>  $this->username));

            

            if($record===NULL)

            {

                $this->_id='user Null';

                $this->errorCode=  self::ERROR_USERNAME_INVALID;

            }

            else if ($record->password!==$this->password)

            {

                $this->_id=  $this->username;

                $this->errorCode=  self::ERROR_PASSWORD_INVALID;

            }

            else if ($record['level']!=='Active')

            {

                $err="You have been inactive by Admin.";

                $this->errorCode=$err;

            }

            else

             {

                    $this->_id=$record['username'];

                    $this->setState('title', $record['username']);

                   

                    $this->errorCode=  self::ERROR_NONE;

            }

            return !$this->errorCode==self::ERROR_NONE;

            /*

		$users=array(

			// username => password

			'demo'=>'demo',

			'admin'=>'admin',

		);

		if(!isset($users[$this->username]))

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		elseif($users[$this->username]!==$this->password)

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		else

			$this->errorCode=self::ERROR_NONE;

		return !$this->errorCode;

             * 

             */

	}

        public function getId(){

            return $this->_id;

        }

}

SiteController.php


public function actionLogin()

	{

		$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())

                        {

			

                            $this->redirect(Yii::app()->user->contactUrl);

                        }

		}

		// display the login form

		$this->render('login',array('model'=>$model));

	}

Thanks before,…

[center]Help me![/center]

[center]I not login with error Incorrect username or password.[/center]

1. File UserIdentity.php

<?php

class UserIdentity extends CUserIdentity

{

private $_id;

public function authenticate()

{

   &#036;record=User::model()-&gt;findByAttributes(array('username'=&gt;&#036;this-&gt;username));  


   if(&#036;record===null)


           {


                   &#036;this-&gt;_id='user Null';


                               &#036;this-&gt;errorCode=self::ERROR_USERNAME_INVALID;


           }


   else if(&#036;record-&gt;password&#33;==&#036;this-&gt;password)            // here I compare db password with passwod field


           {        &#036;this-&gt;_id=&#036;this-&gt;username;


                   &#036;this-&gt;errorCode=self::ERROR_PASSWORD_INVALID;


           }else{  


    &#036;this-&gt;_id=&#036;record['username'];


       &#036;this-&gt;setState('email', &#036;record['email']);


       &#036;this-&gt;errorCode=self::ERROR_NONE;





   }


   return &#33;&#036;this-&gt;errorCode;

}

public function getId() // override Id

{

   return &#036;this-&gt;_id;

}

}

?>

2.File LoginForm.php in model

<?php

class LoginForm extends CFormModel

{

    public &#036;username;


    public &#036;password;


    public &#036;rememberMe;





    private &#036;_identity;





    /**


     * Declares the validation rules.


     * The rules state that username and password are required,


     * and password needs to be authenticated.


     */


    public function rules()


    {


            return array(


                    // username and password are required


                    array('username, password', 'required'),


                    // rememberMe needs to be a boolean


                    array('rememberMe', 'boolean'),


                    // password needs to be authenticated


                    array('password', 'authenticate'),


            );


    }





    /**


     * Declares attribute labels.


     */


    public function attributeLabels()


    {


            return array(


                    'rememberMe'=&gt;'Remember me next time',


            );


    }





    /**


     * Authenticates the password.


     * This is the 'authenticate' validator as declared in rules().


     */


    public function authenticate(&#036;attribute,&#036;params)


    {


            if(&#33;&#036;this-&gt;hasErrors())


            {


                    &#036;this-&gt;_identity=new UserIdentity(&#036;this-&gt;username,&#036;this-&gt;password);


                    if(&#33;&#036;this-&gt;_identity-&gt;authenticate())


                            &#036;this-&gt;addError('password','Incorrect username or password.');


            }


            //var_dump(&#036;this-&gt;_identity); die('aaa');


    }





    /**


     * Logs in the user using the given username and password in the model.


     * @return boolean whether login is successful


     */


    public function login()


    {


            if(&#036;this-&gt;_identity===null)


            {


                    &#036;this-&gt;_identity=new UserIdentity(&#036;this-&gt;username,&#036;this-&gt;password);


                    &#036;this-&gt;_identity-&gt;authenticate();


            }


            if(&#036;this-&gt;_identity-&gt;errorCode===UserIdentity::ERROR_NONE)


            {


                    &#036;duration=&#036;this-&gt;rememberMe ? 3600*24*30 : 0; // 30 days


                    Yii::app()-&gt;user-&gt;login(&#036;this-&gt;_identity,&#036;duration);


                    return true;


            }


            else


                    return false;


    }

}

3.actionLogin in controller

public function actionLogin()

    {


            &#036;model=new LoginForm;


            


            if(isset(&#036;_POST['ajax']) &amp;&amp; &#036;_POST['ajax']==='login-form')


            {


                    echo CActiveForm::validate(&#036;model);


                    Yii::app()-&gt;end();


            }





            if(isset(&#036;_POST['LoginForm']))


            {


            


                    &#036;model-&gt;attributes=&#036;_POST['LoginForm'];


                    


                    // validate user input and redirect to the previous page if valid


                    if(&#036;model-&gt;validate() &amp;&amp; &#036;model-&gt;login())


                    {


                      &#036;this-&gt;redirect(array(&quot;index&quot;));


                    


                    }


                            


            }


                    &#036;this-&gt;render('login',array('model'=&gt;&#036;model));

}

4. View login.php

<?php

$this->pageTitle=Yii::app()->name . ’ - Login’;

$this->breadcrumbs=array(

'Login',

);

?>

<div class=‘content_right’>

&lt;div class=&quot;content_detail&quot;&gt;

<div class="form">

<?php $form=$this->beginWidget(‘CActiveForm’, array(

'id'=&gt;'login-form', 


'enableClientValidation'=&gt;true,


'clientOptions'=&gt;array(


    'validateOnSubmit'=&gt;true,


),

)); ?>

<table width="700" height="500" align="center" border="1">

&lt;tr&gt;


&lt;td align=&quot;center&quot;&gt;


 &lt;h2 class=&quot;ac&quot;&gt;Login User&lt;/h2&gt;


    &lt;?php echo &#036;form-&gt;error(&#036;model,'username'); ?&gt;


    &lt;p style=&quot;margin-bottom: 30px&quot;&gt;


    Username :  &lt;input type=&quot;text&quot; id=&quot;LoginForm_username&quot; class=&quot;full&quot; value=&quot;&quot; name=&quot;LoginForm[username]&quot; required=&quot;required&quot; placeholder=&quot;Username&quot; /&gt;           


    &lt;/p&gt; 


           


    &lt;?php echo &#036;form-&gt;error(&#036;model,'password'); ?&gt;


    &lt;p style=&quot;margin-bottom: 30px&quot;&gt;


    Password :  &lt;input type=&quot;password&quot; id=&quot;LoginForm_password&quot; class=&quot;full&quot; value=&quot;&quot; name=&quot;LoginForm[password]&quot; required=&quot;required&quot; placeholder=&quot;Password&quot; /&gt;           


    &lt;/p&gt;


            


    &lt;p class=&quot;clearfix&quot;&gt;


        &lt;span class=&quot;fl&quot; style=&quot;line-height: 23px;&quot;&gt;


            &lt;label class=&quot;choice&quot; for=&quot;remember&quot;&gt;


                &lt;input type=&quot;checkbox&quot; id=&quot;remember&quot; class=&quot;&quot; value=&quot;1&quot; name=&quot;LoginForm[rememberMe]&quot;/&gt;


                Remember me


            &lt;/label&gt;


        &lt;/span&gt;


        &lt;br/&gt;


        &lt;button class=&quot;fr&quot; type=&quot;submit&quot;&gt;Đăng nhập&lt;/button&gt;


    &lt;/p&gt;    


     &lt;/td&gt;


    &lt;/tr&gt;


    &lt;/table&gt;

<?php $this->endWidget(); ?>

</div><!-- form -->

&lt;/div&gt;

</div>

Help me!

Define in UserIdentity.php -


class UserIdentity extends CUserIdentity

{

    // Define your Constant(s)

    const ERROR_USERNAME_NOT_ACTIVE = 3;

 

    private $_id;

 

    public function authenticate()

    {

        $username=strtolower($this->username);

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

        if($user===null)

            $this->errorCode=self::ERROR_USERNAME_INVALID;

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

            $this->errorCode=self::ERROR_PASSWORD_INVALID;

 

        // Add in the logic condition

        else if($user->isActive == 0)

        $this->errorCode=self::ERROR_USERNAME_NOT_ACTIVE;

 

        else

        {

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

            $this->username=$user->username;

            $this->errorCode=self::ERROR_NONE;

        }

 

        // Change the return statement to return the value not just a pass condition

        // was: return $this->errorCode==self::ERROR_NONE;

        return $this->errorCode;

    }

 

    public function getId()

    {

        return $this->_id;

    }

}


public function authenticate($attribute,$params)

    {

        if(!$this->hasErrors())

        {

            $this->_identity=new UserIdentity($this->username,$this->password);

            if(!$this->_identity->authenticate())

            {

                if(($this->_identity->errorCode == 1) or ($this->_identity->errorCode == 2))

                    $this->addError('password',Yii::t('zii','Incorrect username or password.'));

                elseif($this->_identity->errorCode == 3)

                    $this->addError('username',Yii::t('zii','Username is currently not active.'));

                else

                    $this->addError('username',Yii::t('zii','Invalid Exception!'));

            }

        }

    }

Best solution here -

Please follow this article - http://www.yiiframework.com/wiki/463/custom-login-error-messages/