Search code examples
phpcakephphttp-redirectcakephp-2.0before-filter

Cakephp redirecting a link that has no referer


I've got a submission page that is an ajax popup. If the user isn't logged in, it'll pop up a modal login/signup dialogue for them. Upon logging in, they'll be directed to the main page, since it doesn't remember what the refer was (since all that was triggered as a login page -- not the actual submission page).

I'm thinking of possibly saving that redirect url in a session so when they successfully login, I can redirect them to the appropriate page in my beforeFilter() or something...

I was thinking of something like this (pseudo):

public function submit() {
    if (!$this->Auth->login()) {
        $this->Session->set('Auth.redirect', '/submit');
    }
}

Then in my beforeFilter check to see if that exists when they login, if it does, delete the Session and redirect them to that url?

Is there a better way to handle this or is mine legit?

My beforeFilter:

public function beforeFilter() {
    $this->Auth->loginRedirect = array('controller' => '', 'action' => 'login');

    $this->Auth->allow(
            'Search',
            'loginSignUpPrompt'
            );
}

Solution

  • Actually the Auth Component already has this functionality built in.

    public function login() {
      if ($this->request->is('post')) {
        if ($this->Auth->login()) {
          return $this->redirect($this->Auth->redirect());
        } else {
          $this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
        }
      }
    }
    

    The default for this method is the page where the user came from. But that can be overridden in the Auth settings if you wanted it to.

    Refer to http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html the section about "Identifying users and logging them in"