There are several good user authentication/registration/login systems available for CakePHP (especially version 1.2), but I decided to roll my own. This offers a good learning exercise, in addition to the benefit of knowing where all your code is and what it's doing.

The latest little addition I've made to the code allows you to redirect the user back to where they wanted to go before they logged in. For example, I want to add a recipe into my online multi-user cookbook web application. If I click an "Add Recipe" button and get taken to a login form, I don't want to then be redirected to the front page once I'm logged in - I want to go straight back to adding a recipe.

The basic logic of the login system is

  • A function in /app/app_controller.php to check if the user is logged in. If they're not logged in, redirect them to the login page.
  • A login form to talk to a controller and model which do all the processing/checking to see if the details are correct.
  • A line of code at the end of all this to redirect the user to the front page (or members area).

By adding a tiny snippet of code to the check-if-user-is-logged-in function, and revising the redirect after login, the user will get a much more pleasant experience:

function checkIfLoggedIn() 
{
  if(!$this -> Session -> check('user')) 
  {
    $this -> Session -> write('lastPageVisited', $this -> params['url']['url']);
    $this -> redirect('/users/login', null, true);
  }
}

Then when, in your controller, you decide that the user is all logged in (in this example you'd set the user variable in the session), use the following snippet:

$this -> redirect('/' . $this -> Session -> read('lastPageVisited'), null, true);

Pretty rough and ready (forgive the prepending slash), but it works for my needs. If you do this, you'll probably want to check the lastPageVisited variable to ensure it exists.

Do you use CakePHP and go about this a different way? Would love to hear different methods...