views:

530

answers:

1

I am having trouble getting the Auth component do the redirects I want in a CakePHP 1.2.6 app.

I have a login form that appears on all pages and I want to keep the user on the page he logs in on. For example, if he is viewing another user's profile, I want to keep him there after logging in, not redirect him to the $this->Auth->loginRedirect action. Also, another thing about my app is that I have no "authenticated access only" pages, every page is accessible to everyone, but if you're logged in you get additional features.

What I understood from reading the documentation is that I need to set autoRedirect to false to get the code in the login() function to be executed:

class UsersController extends AppController {    
    var $name = 'Users';
    var $helpers = array('Html', 'Form','Text');

    function beforeFilter() {
        $this->Auth->autoRedirect = false;
    }

    function login() {
        $this->redirect($this->referer());
    }

    function logout() {
        $this->redirect($this->Auth->logout());
    }

    /* [...] */
}

This currently breaks my authentication. I've noticed (from the logs) that if I leave the redirect in the login function and set autoRedirect to false, the password field in $this->data in the login() function appears as empty.

Below, I've posted the contents of AppController that relate to the Auth component:

public function beforeFilter() {

    $this->Auth->fields = array(
        'username' => 'email',             
        'password' => 'password'            
    );

    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');     
    $this->Auth->loginRedirect = array('controller' => 'usercars', 'action' => 'homepage');

    $this->allowAccess();

    // build wishlist if the user is logged in
    if ($currentUser = $this->Auth->user()) {
        $wishlists = $this->buildWishlist($currentUser);
        $this->set('wishlists', $wishlists);
    }

}

private function allowAccess() {
      if(in_array($this->name, /* all my controller names */)) {
          $this->Auth->allow('*');
      }
}

I can't seem to understand what I'm doing wrong.

+2  A: 

Add parent::beforeFilter(); to beforeFilter in the user controller:

function beforeFilter() {
    $this->Auth->autoRedirect = false;
    parent::beforeFilter();
}

You can also replace the redirect with this to the login method of your user controller:

$this->redirect($this->Auth->redirect());

Auth->redirect() returns the url where the user landed before being taken to the login page or Auth->loginRedirect.

GJ
Thanks :D. Calling the parent totally slipped my mind.
Alex Ciminian