Cakephp 3 Redirect when session expires

92 Views Asked by At

I use the AuthComponent and I want when the session expires and the user press a link or refreshes, to redirect him on the login page.

However for some actions I don't want above redirect, even if user is logged out, as they are used as an API by another application also.

For example, I want to allow the 'view' action for logged-out users, but redirect the 'index' action.

My AppController.php is:

$this->loadComponent('Auth', [
            'authorize' => [
                'Acl.Actions' => ['actionPath' => 'controllers/']
            ],
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'username',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'plugin' => false,
                'controller' => 'Users',
                'action' => 'login'
            ],
            'loginRedirect' => [
                'controller' => 'Pages',
                'action'     => 'index',
                'plugin'     => 'Pages'
            ],
            'logoutRedirect' => [
                'plugin' => false,
                'controller' => 'Users',
                'action'     => 'login'
            ],

        ]);

If I add below, 'index' is also working if user is logged-out, even though it should be in deny state.

MyController.php

 public function beforeFilter(\Cake\Event\Event $event)
    {
    $this->Auth->allow('view');

The only way I managed to do what I want is to add it in the controller action as:

MyController.php

public function index()
    {
        
        if (empty($this->auth_user['username'])) {
            return $this->redirect($this->Auth->logout());
        }

Is there a better way to do this?

0

There are 0 best solutions below