Saturday, October 25, 2014

Insert session variable after logging in Yii

In this tutorial i will demonstrate how to insert session variable after logging in yii blog demo. First open folder/protected/components/UserIdentity.php , we will use set state function to insert session variable.
$this->setState('sessionName', 'value of session');
insert the code inside public function authenticate(); Make sure that the code is inside the else clause before we assign a session variable. The reason why we put it inside the else clause is that we want to start assigning session variable if the user successfully pass all the login validation. Check the code below for sample.
/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
 private $_id;

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

 /**
  * @return integer the ID of the user record
  */
 public function getId()
 {
  return $this->_id;
 }
}
to call the session variable anywhere, just use this code
 echo Yii::app()->user->role_id;
 echo Yii::app()->user->nameOfUser;

No comments:

Post a Comment