user required to be logged in for every page

Hi

I was having a little trouble achieving this in Yii2. I think a little bit is due to the change in directory structure or I just forgot where everything goes :lol:

I have a site that is basically a passowrd protected site. Only the sign up page is visible to the public. What’s the most efficient way to make sure someone is logged in? I know I can write my own controller, but I have a lot of controllers and don’t really want to have to go into each one and change


class EventController extends Controller 

to


class EventController extends MyNewerController

Also, I don’t know where the “base” Yii Controller is anymore :wub:

Hi,

You don’t need custom controller for that, just Access Control.

You should implement behaviors() function in your controller, something like this:




public function behaviors()

{

    return [

        'access' => [

            'class' => AccessControl::className(),

            'rules' => [

                [

                    'allow' => true,

                    'roles' => ['@'], // '@' means authenticated user

                ],

            ],

            'denyCallback' => function ($rule, $action) {

                throw new \yii\web\ForbiddenHttpException('You are not allowed to access this page');

            }

        ],

    ];

}



As a result only authenticated users will be able to access all actions in controller where this behavior is attached. If login and signup are on that controller you should allow guest to access them.

It’s well explained in Yii docs.

this looks like I need to attach this code to each controller though? Rather than the behaviour cascade across all controllers?

Try to attach the filter to the application class/object.

As the documentation says: "An action filter will participate in the action execution workflow by responding to the beforeAction and afterAction events triggered by modules and controllers.". And yii\web\Application is a subclass of yii\base\Module (and therefore is a module).

Fortunately there’s no such thing as “base” Controller in Yii2 application templates, except yii\base\Controller which is a part of the framework core. You can create one in ten seconds if necessary but extension/module developers cannot rely anymore on the presence of a base Controller class (which makes their extension useless for you if your application doesn’t have one, has one but with a different name, or requires multiple controller base classes for different types of controllers).