Yii Framework Forum

Before Action Loop


(Garrett) #1

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


(Jaimez) #2

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


(Alirz23) #3

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