Yii::app()->user->isGuest always returns true even though login was successful

48,099

Solution 1

Maybe you can try to debug harder: change messages to something like this:

if(Yii::app()->user->isGuest) {
    print("Not logged");
} else {
    print_r(Yii::app()->user);
    print("Welcome ".Yii::app()->user->name);
    print("Your id is ".Yii::app()->user->id);

}

And check session variable in your config/main.php file

...
    'session' => array(
        'autoStart'=>true,
    ),
...

Solution 2

The error is in the following line

$this->setState('id', $user[0]->id);            

As seen in the official yii documentation regarding auth & auth, setState should be used for anything but the id field. In order to implement the key Yii will use to identify your user, return a unique value per user in the Identity getId() function.

In your case, this means you simply have to change the above line into the following:

$this->_id = $user[0]->id;

Regarding the actual inner working of the login procedure, I'd recommend a look at the CWebUser class, and especially at its login function, which is responsible for the actual storage of the Identity getId() return value.

Solution 3

when you call authenticate function login user as

 $userIdentity = new UserIdentity($username, $password);   
        $userIdentity->authenticate();
        if ($userIdentity->errorCode===UserIdentity::ERROR_NONE) {
            Yii::app()->user->login($userIdentity,0);
 }

and fetch id as

echo 'id='.Yii::app()->user->getId();

apply this code and check

Solution 4

I have faced same problem and found that only one line in UserIdentity Component will resolve this issue.

This is your code:

else 
{   
    $this->setState('id', $user[0]->id);            
    $this->username = $user[0]->username;
    $this->errorCode=self::ERROR_NONE;
    return true;
}

Update this code by this one

else 
{
    $this->_id = $user[0]->id;   
    $this->setState('id', $user[0]->id);            
    $this->username = $user[0]->username;
    $this->errorCode=self::ERROR_NONE;
    return true;
}
Share:
48,099
Soph
Author by

Soph

Updated on July 09, 2022

Comments

  • Soph
    Soph almost 2 years

    I started to make some differences between those users which have authenticated and those that not. For this, i am using

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

    However, in a determined view i put the following code:

    <?php 
        if(Yii::app()->user->isGuest) {
            print("Welcome back Guest!");
            print("Your id is ".Yii::app()->user->id);
        } else {
            print("Welcome back ".Yii::app()->user->name);
            print("Your id is ".Yii::app()->user->id);
    }?>
    

    And i always get the "welcome back guest!", whether i have logged in (successfully) or not. And if i have logged in, then it displays the welcome message together with the user's id!

    EDIT

    @briiC.lv Hey.. sorry for the late reply, I hope you are still following this! I am not extending the given UserIdentity class. Is this mandatory? Since i still dont get very well the whole authorization issue, i thought it would be best to give a try with the class they provide, and then extend with my own functionality.. Anyway, next i post my UserIdentity class with its small tweaks.. maybe the problem lies here??

    <?php class UserIdentity extends CUserIdentity{
    private $_id;
    
    public function authenticate()
    {   
        $user = Users::model()->findAll('username=\''.$this->username.'\' AND password=\''.$this->encryptedPassword.'\'');
        if(!isset($user[0]))
        {
            return false;
        }
        else 
        {   
            $this->setState('id', $user[0]->id);            
            $this->username = $user[0]->username;
            $this->errorCode=self::ERROR_NONE;
            return true;
        }
    }
    
    public function getId()
    {
        return $this->_id;
    }
    

    }

    Here is the output i got when i started to log as you suggested; i got this output immediately after successfully logging in.

    [05:23:21.833][trace][vardump] CWebUser#1 ( 
    [allowAutoLogin] => true 
    [guestName] => 'Guest' 
    [loginUrl] => array ( '0' => '/site/login' ) 
    [identityCookie] => null 
    [authTimeout] => null 
    [autoRenewCookie] => false 
    [autoUpdateFlash] => true 
    [CWebUser:_keyPrefix] => '0f4431ceed8f17883650835e575b504b' 
    [CWebUser:_access] => array() 
    [behaviors] => array() 
    [CApplicationComponent:_initialized] => true 
    [CComponent:_e] => null 
    [CComponent:_m] => null 
    )
    

    Any help is much appreciated!

  • Soph
    Soph almost 13 years
    I just tried that but it didnt work. However, doesnt this parameter default to true? This is the relevant part -i think, of my config file: 'components'=>array( 'user'=>array( // enable cookie-based authentication 'allowAutoLogin'=>true, ), 'session' => array ( 'autoStart' => true, ), I have very very little experience with web authentication altogether, so I am clueless to where the problem might be. Thanks por your help though, any other suggestion or code snippet that could reveal the problem? Thank you!
  • k to the z
    k to the z almost 13 years
    Ha. Why is it so many php programers think debugging is printing out variables. Wouldn't it make more sense to use netbeans and a real debugger? You can even watch the code run in real time and set a break point to stop it. Genius!
  • Soph
    Soph almost 13 years
    @k to the z Well, as much as i would love to do that kind of debugging, when i started out with this framework (a month ago) i dedicated a few days trying to figure out how to debug and couldnt. Since i couldnt afford losing more time, i turned to the old fashioned way... placing print() commands just about anywhere! though one could debate how much time im actually gaining... I still havent been able to resolve this it is driving me crazy!!
  • briiC
    briiC almost 13 years
    @k to the z (and @Soph ) Yii have buil-in debugging : Yii::log(...) (search it with WebLogRoute). But about authorization.. try add debugging to your userIdentity class (if you extending it). and check maybe you are destroying session somewhere?
  • chris
    chris almost 13 years
    In the config for your authManager, check to see if defaultRoles contains guest. The default roles will be assigned to all users everytime logged in or not.
  • Leonardo Situmorang
    Leonardo Situmorang over 11 years
    as a side note. $this->_id or whatever instance variable name can be use as long as it's returned by UserIdentity::getId()
  • René Vogt
    René Vogt about 8 years
    Welcome to StackOverflow! It would improve your answer a lot if you could explain a little how this solves the problem.