Take user back to previous page after logging in?

后端 未结 6 1006
故里飘歌
故里飘歌 2021-01-20 16:18

I have a controller called Accounts, with the views signin and signout.

The corresponding functions look like this:

function signin()
{
    if (!empt         


        
6条回答
  •  旧时难觅i
    2021-01-20 16:40

    CakePHP 2.x here

    1. Edit AppController.php

    public function beforeFilter() {
            // redirect url
            if($this->request->here!= '/users/login') {
                $user_id = AuthComponent::user('id');
                if(empty($user_id)) { $this->Session->write('redirect_url_after_login', Router::url($this->request->here, true)); }
    }
    

    This will store the url the user wanted to go before request, only if the url is not /users/login (replace with your url of login) AND if no user is logged.

    2. Edit your login form. Mine was Users/login.ctp. Add an hidden field only if there is a session variable set.

        $redirect_url_after_login = $this->Session->read('redirect_url_after_login');
        if(!empty($redirect_url_after_login))
            echo $this->Form->input('redirect_url_after_login', ['value'=>$redirect_url_after_login, 'type'=>'hidden']);
    

    3. In your login action, add an action to overwrite the loginRedirect variable you may have set before.

    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $redirect_url_after_login = $this->request->data['User']['redirect_url_after_login'];
                if(!empty($redirect_url_after_login)
                    &&filter_var($redirect_url_after_login, FILTER_VALIDATE_URL)
                    &&parse_url($redirect_url_after_login, PHP_URL_HOST)==$_SERVER['HTTP_HOST'])
                        return $this->redirect($redirect_url_after_login);
                $this->Session->delete('redirect_url_after_login');
                return $this->redirect($this->Auth->redirect());
    

    }

    I added a couple of security checks, like "is the redirect url a valid url?" and "is it redirecting towards my domain or an external domain?".

    Note: I know checking $_SERVER['HTTP_HOST'] is not bulletproof, but here we're talking about preventing open redirect vulnerability, so it's enough.

提交回复
热议问题