Calls to Yii::$app->user->[anything] are yielding an "Undefined variable: user" error

31 views Asked by At

I recently migrated a few Yii2 sites to Cloudways, running php7.4 on the server. (I'm holding off on upgrading to php8 until these issues are resolved.)

For some reason, I'm getting an error "Undefined variable: user" every time I call Yii::$app->user->[anything]. So I can no longer user Yii::$app->user->isAdmin or Yii::$app->user->isGuest. Even if the user logs in, these calls produce the "Undefined variable: user" error.

Any leads would be appreciated. Thanks!

In 'web.php':

'components' => [
    'user' => [
        'identityClass' => 'app\models\User',
        'class' => 'app\components\User', // extend User component
        'enableAutoLogin' => true,
    ],

and

'modules' => [
    'user' => [
        'class' => 'dektrium\user\Module',
        'enableUnconfirmedLogin' => true,
        'cost' => 12,
        'rememberFor' => 1209600,
        'admins' => ['xxxxx','xxxxx'],
        'modelMap' => [
            'User' => 'app\models\User',
            'RegistrationForm' => 'app\models\RegistrationForm',
        ],
    ],

In /components/User.php

class User extends \yii\web\User
{
    public function getUsername()
    {
        return Yii::$app->user->identity->username;
    }

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

    public function getIsAdmin()
    {
        $roles = Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
        return in_array('admin',array_keys($roles));
    }
}

In /models/User.php

class User extends BaseUser
{

    public function getUsername()
    {
        return $this->profile->name;
    }

    public function getAuthorname()
    {
        return $this->getUsername();
    }

    public function getAvatar()
    {

        return $this->profile->getAvatarUrl(75);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->auth_key = \Yii::$app->security->generateRandomString();
            }
            return true;
        }
        return false;
    }
}
0

There are 0 answers