3

Here, I have extended User Identity of Yii2.

This is my configuration.

'user' => [
            'identityClass' => app\models\UserMaster::class,
            'enableAutoLogin' => false,
            'loginUrl' => ['/auth/login'],
            'authTimeout' => 86400
        ],

Here, I have defined authTimout statically. But, What I want to do is that I want to fetch timeout value from database and set it in authTimeout.

Thanks.

akshaypjoshi
  • 1,180
  • 1
  • 11
  • 22

1 Answers1

4

You can use event to set authTimeout before request will be handled:

'as beforeRequest' => [
    'class' => function (Event $event) {
        /* @var $app \yii\web\Application */
        $app = $event->sender;
        $app->getUser()->authTimeout = (new Query())
            ->select('value')
            ->from('{{%settings}}')
            ->where('name = :name', ['name' => 'authTimeout'])
            ->scalar($app->getDb());
    }
],

But probably more clear approach would be to create custom component and handle this in init().

class WebUser extends \yii\web\User {

    public function init() {
        parent::init();

        $this->authTimeout = (new Query())
            ->select('value')
            ->from('{{%settings}}')
            ->where('name = :name', ['name' => 'authTimeout'])
            ->scalar();
    }
}

Then use new component in your config:

'components' => [
    'user' => [
        'class' => WebUser::class,
        'identityClass' => app\models\UserMaster::class,
        'enableAutoLogin' => false,
        'loginUrl' => ['/auth/login'],
    ],
    // ...
],
rob006
  • 18,710
  • 5
  • 41
  • 58
  • Hi @rob006, i faced similar problem and followed the instructions as given, but somehow it's not working for me. If you can help me, it would be great for me. https://stackoverflow.com/questions/56756109/dynamic-authtimeout-not-getting-set-in-yii2 Thanks – Nana Partykar Jun 25 '19 at 14:18