Yii2: Yii::$app->user->getId() always returns null after login

Created on 20 Jan 2014  路  7Comments  路  Source: yiisoft/yii2

My user is configured as:

'user' => [
            'identityClass' => 'app\modules\login\models\user\LoginDatabaseForAllUser',
            'loginUrl' => 'login/login/'
        ],
 'httpcookie' => [
            'class' => 'yii\web\cookie',
            'httponly' => true,
        ],

User Class is:

<?php

namespace app\modules\login\models\user;

use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use yii\web\User;

/**
 * Class User
 * @package common\models
 *
 * @property integer $id
 * @property string $email_address
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $role
 * @property integer $status
 * @property integer $create_time
 * @property integer $update_time
 */
class LoginDatabaseForAllUser extends ActiveRecord implements IdentityInterface {

    /**
     * @var string the raw password. Used to collect password input and isn't saved in database
     */
    public $password;

//  const STATUS_DELETED = 0;
//  const STATUS_ACTIVE = 10;
//  const ROLE_USER = 10;
//  public function behaviors()
//  {
//      return [
//          'timestamp' => [
//              'class' => 'yii\behaviors\AutoTimestamp',
//              'attributes' => [
//                  ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
//                  ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time',
//              ],
//          ],
//      ];
//  }

    /**
     * Finds an identity by the given ID.
     *
     * @param string|integer $id the ID to be looked for
     * @return IdentityInterface|null the identity object that matches the given ID.
     */
    public static function findIdentity($id) {
        return static::find($id);
    }

    /**
     * Finds user by email_address
     *
     * @param string $email_address
     * @return null|User
     */
    public static function findByUsername($email_address) {
        return static::find(['email_address' => $email_address]);
    }

    /**
     * @return int|string|array current user ID
     */
    public function getId() {
        return $this->getPrimaryKey();
    }

    /**
     * @return string current user auth key
     */
    public function getAuthKey() {
        return $this->auth_key;
    }

    /**
     * @param string $authKey
     * @return boolean if auth key is valid for current user
     */
    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password) {
        return Security::validatePassword($password, $this->password_hash);
    }

    public function rules() {
        return [
           // ['status', 'default', 'value' => self::STATUS_ACTIVE],
            //['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
            //['role', 'default', 'value' => self::ROLE_USER],
            //['role', 'in', 'range' => [self::ROLE_USER]],
            ['email_address', 'filter', 'filter' => 'trim'],
            ['email_address', 'required'],
            ['email_address', 'string', 'min' => 2, 'max' => 255],
            //['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            //['email', 'unique', 'message' => 'This email address has already been taken.', 'on' => 'signup'],
            //['email', 'exist', 'message' => 'There is no user with such email.', 'on' => 'requestPasswordResetToken'],
            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    public function scenarios() {
        return [
            'signup' => ['email_address', 'password'],
        ];
    }

//    public function beforeSave($insert) {
//        if (parent::beforeSave($insert)) {
//            if (($this->isNewRecord || $this->getScenario() === 'resetPassword') && !empty($this->password)) {
//                $this->password_hash = Security::generatePasswordHash($this->password);
//            }
//            if ($this->isNewRecord) {
//                $this->auth_key = Security::generateRandomKey();
//            }
//            return true;
//        }
//        return false;
//    }

    public static function tableName() {
        return "login_database_for_all_user";
    }

}

and Controller code is same as default.

1) When I login using wrong email or password, validation error is shown. That is working right.

2) When using correct email and password, no error is shown.
and Yii::$app->user->getId() always returns null.

Used Debugger and there is no error in code.

to be verified bug

Most helpful comment

Thanks to @cebe, @o-rey and all others, the following error I was getting because of following code:-

Wrong Code:- 'id'=>'db' in below code.
'session' => [
            'class' => 'yii\web\DbSession',
            'id' => 'db',
            'gcProbability' => 10,
            'name' => 'SiteAccess',
            'sessionTable' => 'session',
            'cookieParams' => [
                'httponly' => true,
                'lifetime' => 0,
            ],
Right code is --> "I have removed 'id'=>'db' from above code and all started working properly.

All 7 comments

please show database table used for active record. Also show the data stored in db for the user you log in with.

The table structure is
localhost _ 127 0 0 1 _ mywebs _ login_database_for_all_user _ phpmyadmin 4 0 4_2014-01-20_18-22-05

and table data is
localhost _ 127 0 0 1 _ mywebs _ login_database_for_all_user _ phpmyadmin 4 0 4_2014-01-20_18-21-27
In the screenshot, the passwordhash and auth_key column is wrapped to have small image width..

I am not able to reproduce the problem. Must be some issue with code that is not shown here.

This can happen if id is not defined as PK in table schema (PRIMARY KEY (id)).
In this case you should declare function primaryKey() in your model returning PK field name ('id' in your case), like this:

public static function primaryKey()
{
    return ['id'];
}

(but better set PK for the table)

Thanks to @cebe, @o-rey and all others, the following error I was getting because of following code:-

Wrong Code:- 'id'=>'db' in below code.
'session' => [
            'class' => 'yii\web\DbSession',
            'id' => 'db',
            'gcProbability' => 10,
            'name' => 'SiteAccess',
            'sessionTable' => 'session',
            'cookieParams' => [
                'httponly' => true,
                'lifetime' => 0,
            ],
Right code is --> "I have removed 'id'=>'db' from above code and all started working properly.

i am getting same error in which file you made change ...?

@cent040 add primary key to table, works for me

Was this page helpful?
0 / 5 - 0 ratings