Toma Tomov
Toma Tomov

Reputation: 1674

How to Override Yii2 $app->user->identity

I have a module which uses a secondary database. In it, I am trying to log in to the user table from that secondary database. The problem is that the \Yii::$app->user->identity->id is using the first database. How should I override the class to do it like this? What I got in my LoginForm.php in the module is :

public function login()
    {

        if ($this->validate() && $this->user) {
            $isLogged = Yii::$app->getUser()->login($this->user, $this->rememberMe ? $this->module->rememberFor : 0);
            //var_dump($this->user);exit;
            if ($isLogged) {
                $user = \frontend\modules\store\models\User::findOne(Yii::$app->user->identity->id);
                $user->last_login_at = time();
                $user->update();
              //  $this->user->updateAttributes(['last_login_at' => time()]);
            }

            return $isLogged;
        }

        return false;
    }

As you can see the user class here is overridden and it is using the secondary database. But how should I override the Yii::$app->user->identity->id to use this database also? Thank you in advance!

Upvotes: 1

Views: 1093

Answers (2)

Irfan Ashraf
Irfan Ashraf

Reputation: 607

As you are using Yii2 advanced template, you should consider adding a new sub application. Yii2 advanced template allows you to have different sessions for frontend and backend sub applications. Advanced Template on Same Domain and different sessions

Similarly, you can add a new app, in your case it may be called store. If you do it as a separate app, you can simply override identity class and even have different model for user. Help about adding new app is here.

Upvotes: 1

Golub
Golub

Reputation: 195

You can override user identity in config

'user' => [
'identityClass' => 'app\models\User', // User must implement the IdentityInterface
'enableAutoLogin' => true,
// 'loginUrl' => ['user/login'],
// ...

]

more info here

Upvotes: 1

Related Questions