Yii Framework Forum: [SOLVED]User Login With DB - Yii Framework Forum

Jump to content

  • (2 Pages)
  • +
  • 1
  • 2
  • You cannot start a new topic
  • You cannot reply to this topic

[SOLVED]User Login With DB Login details stored inside DB Rate Topic: -----

#1 User is offline   ejgomez 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 94
  • Joined: 14-June 11

Posted 23 June 2011 - 08:27 AM

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

0

#2 User is offline   kiran sharma 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 492
  • Joined: 21-May 11
  • Location:India

Posted 23 June 2011 - 09:32 AM

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

Thanks,
Kiran Sharma.
1

#3 User is offline   ejgomez 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 94
  • Joined: 14-June 11

Posted 24 June 2011 - 12:55 AM

Thanx a lot for the reply..


Fixed it.
0

#4 User is offline   saham 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 11
  • Joined: 02-February 12

Posted 02 February 2012 - 10:27 AM

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
0

#5 User is offline   kiran sharma 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 492
  • Joined: 21-May 11
  • Location:India

Posted 30 May 2012 - 09:25 AM

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.. :)
Thanks,
Kiran Sharma.
0

#6 User is offline   mint 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 20-June 12

Posted 20 June 2012 - 03:26 AM

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()
{
$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->errorCode == self::ERROR_NONE;
}

return !$this->errorCode;
}

public function getId()
{
return $this->_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 $username;
public $password;
public $rememberMe=false;

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', 'on'=>'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'=>'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.');



}
/**
* 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 ? 0 : 0;
Yii::app()->user->login($this->_identity,$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'=>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);
}
}
0

#7 User is offline   Haviator 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 12-December 12

Posted 13 December 2012 - 01:48 AM

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

#8 User is offline   Haviator 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 12-December 12

Posted 13 December 2012 - 02:15 AM

View PostHaviator, on 13 December 2012 - 01:48 AM, said:

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
0

#9 User is offline   Arely 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 21
  • Joined: 15-February 13

Posted 11 June 2013 - 12:57 PM

View Postkiran sharma, on 23 June 2011 - 09:32 AM, said:

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




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!!
0

#10 User is offline   kiran sharma 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 492
  • Joined: 21-May 11
  • Location:India

Posted 12 June 2013 - 09:43 AM

Hey,

Your code in UserIdentity is as below,

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

Now just check with,

echo $this->username; // This must come from form field and should not be null
your above line will generate query model "select * from login where user="$this->username"";


View PostArely, on 11 June 2013 - 12:57 PM, said:

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.

Thanks,
Kiran Sharma.
0

#11 User is offline   Arely 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 21
  • Joined: 15-February 13

Posted 12 June 2013 - 03:04 PM

View Postkiran sharma, on 12 June 2013 - 09:43 AM, said:

Hey,

Your code in UserIdentity is as below,

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

Now just check with,

echo $this->username; // This must come from form field and should not be null
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 (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(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(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(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(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
0

#12 User is offline   Travis Stroud 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 33
  • Joined: 29-August 12

Posted 12 June 2013 - 03:35 PM

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.
0

#13 User is offline   Arely 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 21
  • Joined: 15-February 13

Posted 12 June 2013 - 06:18 PM

View PostRandom Name, on 12 June 2013 - 03:35 PM, said:

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
0

#14 User is offline   Larry Jr. 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 19
  • Joined: 13-March 13
  • Location:Tomohon

Posted 23 September 2013 - 09:43 PM

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.

View Postkiran sharma, on 23 June 2011 - 09:32 AM, said:

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


JoenMarz
0

#15 User is offline   kiran sharma 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 492
  • Joined: 21-May 11
  • Location:India

Posted 24 September 2013 - 04:12 AM

Yes, why not?
..

View PostLarry Jr., on 23 September 2013 - 09:43 PM, said:

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.

Thanks,
Kiran Sharma.
0

#16 User is offline   Larry Jr. 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 19
  • Joined: 13-March 13
  • Location:Tomohon

Posted 02 October 2013 - 12:51 AM

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.

View Postkiran sharma, on 23 June 2011 - 09:32 AM, said:

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)
        ...
	
       else  // What's the use of this part?
       {  
          $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;
   }
}


JoenMarz
0

#17 User is offline   kiran sharma 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 492
  • Joined: 21-May 11
  • Location:India

Posted 02 October 2013 - 03:39 AM

If(UserName Or Password mismatch)
{

}else{
	// Login success
	// This will use to set any user state or session on successful login
}


View PostLarry Jr., on 02 October 2013 - 12:51 AM, said:

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.

Thanks,
Kiran Sharma.
0

#18 User is offline   funwalker 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 05-April 14

Posted 06 April 2014 - 01:13 AM

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,..
0

#19 User is offline   Ta Thanh Phuong 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 3
  • Joined: 18-May 14

Posted 18 May 2014 - 03:36 AM

Help me!
I not login with error Incorrect username or password.

1. File UserIdentity.php

<?php

class UserIdentity extends CUserIdentity
{
private $_id;
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) // here I compare db password with passwod field
{ $this->_id=$this->username;
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}else{
$this->_id=$record['username'];
$this->setState('email', $record['email']);
$this->errorCode=self::ERROR_NONE;

}
return !$this->errorCode;
}

public function getId() // override Id
{
return $this->_id;
}
}
?>

2.File LoginForm.php in model

<?php

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())
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect username or password.');
}
//var_dump($this->_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($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;
}
}

3.actionLogin in controller

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("index"));

}

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

4. View login.php

<?php
$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
'Login',
);
?>
<div class='content_right'>
<div class="content_detail">

<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<table width="700" height="500" align="center" border="1">
<tr>
<td align="center">
<h2 class="ac">Login User</h2>
<?php echo $form->error($model,'username'); ?>
<p style="margin-bottom: 30px">
Username : <input type="text" id="LoginForm_username" class="full" value="" name="LoginForm[username]" required="required" placeholder="Username" />
</p>

<?php echo $form->error($model,'password'); ?>
<p style="margin-bottom: 30px">
Password : <input type="password" id="LoginForm_password" class="full" value="" name="LoginForm[password]" required="required" placeholder="Password" />
</p>

<p class="clearfix">
<span class="fl" style="line-height: 23px;">
<label class="choice" for="remember">
<input type="checkbox" id="remember" class="" value="1" name="LoginForm[rememberMe]"/>
Remember me
</label>
</span>
<br/>
<button class="fr" type="submit">Đăng nhập</button>
</p>
</td>
</tr>
</table>
<?php $this->endWidget(); ?>
</div><!-- form -->

</div>

</div>


Help me!
0

#20 User is offline   Rohit Suthar 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 135
  • Joined: 12-May 14
  • Location:Mumbai, India

Posted 10 June 2014 - 06:10 AM

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.yiiframew...error-messages/
Thanks & regards,

ROHIT SUTHAR,
Mumbai(India)

Follow me - @rohisuthar

www.yiiframework.us



Don't be shellfish to click +1 button
0

Share this topic:


  • (2 Pages)
  • +
  • 1
  • 2
  • You cannot start a new topic
  • You cannot reply to this topic

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