Before Action Loop

I have created a beforeAction behaviour in components to check if user is logged in before each request.

It was originally looping and I did some research and tried to resolve it by comparing the current route with the ‘site/login’ action.

I now get this error and cant seem to solve it.

<?php

namespace app\components;
use yii\base\Behavior;
use yii\web\Controller;
use yii\helpers\Url;
use Yii;

class CheckUserSession extends Behavior
{

    public function events()
    {
        return [
            \yii\web\Application::EVENT_BEFORE_REQUEST => 'checkUserSession',
        ];
    }

    public function checkUserSession()
    {

        if (Yii::$app->user->isGuest && Yii::$app->controller->getRoute() != 'site/login') {
            $this->redirect(['site/login']);
            return false;
        }

        return true; 
    }   
}

?>

Any help would be much appreciated.

Thanks

Try to call getRoute() this way:
if (Yii::$app->user->isGuest && $this->getRoute() != 'site/login') {

reason you getting this error is because your event is being called EVENT_BEFORE_REQUEST at that point the controller has not been mounted and it is null by default, that is what the error says what you need is EVENT_BEFORE_ACTION.

I would suggest you look into builtin authorization which handles this use case very well don’t reinvent the wheel here is link to docs

https://www.yiiframework.com/doc/guide/2.0/en/security-authorization

1 Like