phpyiiyii2yii2-advanced-appyii2-basic-app

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.


Solution

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