简体   繁体   中英

yii2 identity session expiry

I am new to yii2 framework and I am facing a problem with the identity. when the session timeouts or when I change my user status to inactive I am getting an error of Trying to get property of non-object from the user component.

public function getName()
{
    return \Yii::$app->user->identity->username;
}

as I am retrieving this value in the header of the website, I want to redirect to login page instead of showing this error

As good practice you should use Access Control Filters in your controller. Please refer to this link to get an idea on how to implement authorisation in your controllers.

In Controller file you should put:

if (\Yii::$app->user->isGuest) {
   return $this->redirect(["site/login"]);
}

It's because "identity" is set only on users who are logged in.. So you can't access identity because he is guest..

https://www.yiiframework.com/doc/api/2.0/yii-web-user# $isGuest-detail

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