Redirecting to current page after logged in using cakephp 3.4.7

360 Views Asked by At

Recently I upgraded cakephp 3.3.4 to cakephp 3.4.7, in old version If loggedin in current page it's redirecting to current page only as I aspect, but after upgraded It's redirecting into home page, I don't know what's the problem. please anybody help me out here

public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'authorize' => ['Controller'],
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ],
                'scope' => ['userStatus' => '1']
            ]
        ],
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'unauthorizedRedirect' => $this->referer(),
        'logoutRedirect'       => [
                'controller' => 'Users',
                'action'     => 'login'

        ]
    ]);
}

login function:

public function login()
{
    if($this->Auth->user()){
        $this->Flash->error(__('You are already logged in!'));
        return $this->redirect($this->Auth->redirectUrl());
    }
    else{
        if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error('Your username or password is incorrect.');
      }
   }
}
1

There are 1 best solutions below

7
On BEST ANSWER

Redirect to current page:

if ( $this->request->is( 'post' ) ) {
    if ( $this->Auth->login() ) {
       $this->redirect($this->Auth->redirectUrl());
   } else {
      $this->Flash->error(__('Your username or password is incorrect.'));
   }
 }

If you're trying to redirect to a specific place on login, make sure you've set loginRedirect when you initialize the Auth Component in Appcontroller.

public function initialize()
{
    parent::initialize();

    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ]
            ]
        ],
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login',
            'prefix' => false
        ],
        'unauthorizedRedirect' => $this->referer(),
         /* You need this part */
        'loginRedirect' => [
            'controller' => 'dashboard',
            'action' => 'index'
         ]
    ]);

}

source: https://book.cakephp.org/3.0/en/controllers/components/authentication.html#redirecting-users-after-login