Yii2 - How to set dynamic authTimeout in User Identity?
✔ Recommended Answer
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'], ], // ...],
Source: stackoverflow.com
Answered By: rob006
To set a dynamic authTimeout
in Yii2's User Identity, you can override the getAuthTimeout()
method in your User
model class.
Here's an example implementation:
phpclass User extends ActiveRecord implements IdentityInterface
{
// ...
public function getAuthTimeout()
{
// Set a default timeout of 30 minutes
$timeout = 1800;
// Check if the user has a specific timeout set in their profile
if (!empty($this->auth_timeout)) {
$timeout = $this->auth_timeout;
}
// You can also add additional logic here to adjust the timeout based on other factors
return $timeout;
}
// ...
}
In this example, we're checking if the user has a specific auth_timeout
value set in their database record. If so, we use that value as the timeout. Otherwise, we use a default timeout of 30 minutes (1800 seconds).
You can adjust this logic to suit your specific use case. Just make sure to return the number of seconds that the user's session should remain active.
Comments
Post a Comment