Yii user authentication and session not working

ajaybc picture ajaybc · May 19, 2012 · Viewed 7.6k times · Source

I am building a website in Yii and I am stuck at the user authentication step. Whatever i do I am not able to authenticate users or store some value in the session.

My UserIdentity component is as follows:

class UserIdentity extends CUserIdentity
{
    private $_id;

    public function authenticate(){
        if(($userRecord = Admin::model()->findByAttributes(array('username'=>$this->username)))===null){
            return $this->errorCode=self::ERROR_USERNAME_INVALID;
        }
        if($userRecord->password!=hash('sha256', $this->password)){
            return $this->errorCode=self::ERROR_PASSWORD_INVALID;
        }
        $this->_id=$userRecord->id;
        $this->setState('title', $userRecord->username);
        Yii::app()->session['clientId'] = $userRecord->clientId;
        Yii::app()->session['id'] = $userRecord->id;
        Yii::app()->session['loggedin'] = true;

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

    public function getId(){
        return $this->_id;
    }

}

My Yii:app()->user->isGuest always returns true and Yii::app()->user->id returns nothing.

That is why I tried using Yii::app()->session['loggedin'] to do authentication. But even that is not working. When I access session array like this Yii::app()->session I get the error Property "CWebUser.session" is not defined..

This is getting really frustrating. I am new to Yii. Please help.

Answer

bool.dev picture bool.dev · May 19, 2012

Use the login function of CWebUser.

Follow this tutorial.