使用cakephp 3.4.7登录后重定向到当前页面

时间:2017-05-24 06:21:19

标签: cakephp cakephp-3.0 cakephp-3.4

最近我将cakephp 3.3.4升级到cakephp 3.4.7,旧版本如果登录到当前页面,它只是作为我的方面重定向到当前页面,但是升级后它重定向到主页,我不知道问题是什么。请有人帮帮我

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'

        ]
    ]);
}

登录功能:

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 个答案:

答案 0 :(得分:0)

重定向到当前页面:

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

如果您在登录时尝试重定向到特定位置,请确保在Appcontroller中初始化Auth组件时设置了loginRedirect。

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'
         ]
    ]);

}

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