changing l login form to User Login Model

I have did according to things mentioned in Yii BOOK on user mangement but i get blank page on Login

here is my UserIdentity


<?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;

	/*

	Authenticating using User Model

	*/


	public function authenticate()

	{

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

	if($user==null)

	{

		$this->errorCode=self::ERROR_USERNAME_INVALID;

	}

	else

	{

		if($user->password!==$user->md5($this->password))

		{

		  $this->errorCode=self::ERROR_USERNAME_INVALID;

		}

		else

		{

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

		}

	}

	return !$this->errorCode;

	}


	public function getId()

	{

		return $this->_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()

	{

		$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;

	}*/

}

LoginForm.php in model direcoty


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

	{

		if(!$this->hasErrors())

		{

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

			$_identity->authenticate();

			switch($identity->errorCode)

			{

			  case UserIdentity::ERROR_NONE:

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

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

				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;

			}

		}

	}

*/


	/**

	 * Authenticates the password.

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

	*/

	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;

	}

}

Login.php in view folder


<?php

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

$this->breadcrumbs=array(

	'Login',

);

?>


<h1>Login</h1>


<p>Please fill out the following form with your login credentials:</p>


<div class="form">

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

	'id'=>'login-form',

	'enableClientValidation'=>true,

	'clientOptions'=>array(

		'validateOnSubmit'=>true,

	),

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<div class="row">

		<?php echo $form->labelEx($model,'username'); ?>

		<?php echo $form->textField($model,'username'); ?>

		<?php echo $form->error($model,'username'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'password'); ?>

		<?php echo $form->passwordField($model,'password'); ?>

		<?php echo $form->error($model,'password'); ?>

		<p class="hint">

			Hint: You may login with <tt>demo/demo</tt> or <tt>admin/admin</tt>.

		</p>

	</div>


	<div class="row rememberMe">

		<?php echo $form->checkBox($model,'rememberMe'); ?>

		<?php echo $form->label($model,'rememberMe'); ?>

		<?php echo $form->error($model,'rememberMe'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton('Login'); ?>

	</div>


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

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

Anything else needed?

Not sure if that is the problem… but you did not assign ERROR_NONE anywhere in UserIdentity->authenticate()

ok i am gonna add

but php is show this error

Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /var/www/seolink/protected/components/UserIdentity.php on line 18

and line 18


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

here is my User.php model


<?php


/**

 * This is the model class for table "tbl_user".

 *

 * The followings are the available columns in table 'tbl_user':

 * @property integer $id

 * @property string $username

 * @property string $email

 * @property string $password

 * @property string $fname

 * @property string $lname

 * @property string $city

 * @property string $state

 * @property string $country

 * @property string $zipcode

 */

class User extends CActiveRecord

{

	public $password_repeat;

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return User 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 'tbl_user';

	}


	/**

	 * @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('username, email, password, fname, lname, city, state, country, zipcode', 'required'),

			array('username, email, password, fname, lname, city, state, country', 'length', 'max'=>128),

			array('zipcode', 'length', 'max'=>20),

			array('zipcode', 'length', 'max'=>20),

			array('username, email', 'unique'),

			array('password', 'compare'),

			array('password_repeat', 'safe'),

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

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

			array('username, email, fname, lname, city, state, country, zipcode', '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',

			'username' => 'Username',

			'email' => 'Email',

			'password' => 'Password',

			'fname' => 'First Name',

			'lname' => 'Last Name',

			'city' => 'City',

			'state' => 'State',

			'country' => 'Country',

			'zipcode' => 'Zipcode',

		);

	}


	/**

	 * 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('username',$this->username,true);

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

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

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

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

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

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

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

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


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}


	//this function encrypts password to md5 encryption

    	public function beforeSave()

        {

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

	        $this->password = $pass;

        	return true;

        }

}

do i need to modify something in conroller

here is UserController.php


<?php


class UserController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

		);

	}


	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('admin'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	public function actionView($id)

	{

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

			'model'=>$this->loadModel($id),

		));

	}


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new User;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}


	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 */

	public function actionUpdate($id)

	{

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


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'admin' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

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


			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

			if(!isset($_GET['ajax']))

				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('User');

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new User('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['User']))

			$model->attributes=$_GET['User'];


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

			'model'=>$model,

		));

	}


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer the ID of the model to be loaded

	 */

	public function loadModel($id)

	{

		$model=User::model()->findByPk($id);

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

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

		{

			echo CActiveForm::validate($model);

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

		}

	}

}

and 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'=>array(

				'class'=>'CCaptchaAction',

				'backColor'=>0xFFFFFF,

			),

			// page action renders "static" pages stored under 'protected/views/site/pages'

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

			'page'=>array(

				'class'=>'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'

		$this->render('index');

	}


	/**

	 * This is the action to handle external exceptions.

	 */

	public function actionError()

	{

	    if($error=Yii::app()->errorHandler->error)

	    {

	    	if(Yii::app()->request->isAjaxRequest)

	    		echo $error['message'];

	    	else

	        	$this->render('error', $error);

	    }

	}


	/**

	 * Displays the contact page

	 */

	public function actionContact()

	{

		$model=new ContactForm;

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

		{

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

			if($model->validate())

			{

				$headers="From: {$model->email}\r\nReply-To: {$model->email}";

				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);

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

				$this->refresh();

			}

		}

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

	}


	/**

	 * Displays the login page

	 */

	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->returnUrl);

		}

		// display the login form

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

	}


	/**

	 * Logs out the current user and redirect to homepage.

	 */

	public function actionLogout()

	{

		Yii::app()->user->logout();

		$this->redirect(Yii::app()->homeUrl);

	}

}

Please read the guidelines for posting - http://www.yiiframework.com/forum/index.php/topic/19451-guidelines-for-posting-this-forum/

It really does not help others if you just copy/paste your whole model/controller/project here…

If you get an error with a line number… than the error is there… what use has to post all other code… and especially how can you expect to get proper help if in your first post you just write “I’m getting a blank page”… when a bit later you say you are getting an error ???

About your problem check the line 18… the error is there… but I will not tell you what it is… just compare it with any other similar command and you will find it…

Spoiler: try to use google, search for “syntax error, unexpected T_OBJECT_OPERATOR”, you will certainly find a post not related to Yii but with similar error you made ;)

thanks anyways, i will resolve it myself…


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

missing model()




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



You see… it was not that hard ;)

Don’t you feel better when you find the problem instead of someone else pointing it to you ;)

yeah but after 4 horus :( but now another… i have removed md5 but error is same

Object of class UserIdentity could not be converted to string

this line is highlight in yii stack trace


     if($user->password!==$user->$this->password)

What is $user->$this->password ?

page 165 of yii book AGILE WEB DEVELOPMENT

Check out this and compare my code… i did same as mentioned in that book

Sorry but I’m currently in the office and don’t have the book… if that is written there than probably it’s a typo error… are you sure it’s written the same as you wrote it

$user->$this->password

here i am adding screenshot, let me know where is error… :( yeah i was using md5 before but i remove it, in book they are using encrpt

3089

yii_1.jpg

3090

yii_2.jpg

So, now as you see - your line is not even near to that in the book.

$user->encrypt($this->password) is not even near the same as $user->$this->password

I’m afraid that if you don’t understand the difference between those two lines, than you will not progress too much with Yii as that is simple PHP understanding.

Because of that I would suggest you to first read/learn/understand PHP syntax as if not you will just continue to make similar errors (omitting () included).

As for the above if you just want to compare the user password with the one entered you need to use $this->password. But that in turn means you are keeping plain (unencrypted) passwords in the database, that itself is not wise but not part of this issue.

just tried out this one and working for me :)

now login is fine and its from database using md5 encryption

later i will serve yii with very good video tutorials :) for all startup users


    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!==md5($this->password))

            $this->errorCode=self::ERROR_PASSWORD_INVALID;

        else

        {

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

            //$this->setState('title', $user->title);

            $this->errorCode=self::ERROR_NONE;

        }

        return !$this->errorCode;

    }

 

    public function getId()

    {

        return $this->_id;

    }

$user->$this->password

yeah this is my mistake… i need a little rest… after this i will start rbac :)

thank mdomba for help really appreciate :)