简体   繁体   中英

Yii2 - How to set dynamic authTimeout in User Identity?

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.

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'],
    ],
    // ...
],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM