23 Mar 2009 @ 10:57 AM 

In today’s article, I am going to discuss how simple it is to setup a login system with CakePHP.  As the title says, it should be less than 10 minutes.  In theory if you copy and paste the code below, it should be fully functional in less than 5.

Ready, set, let’s bake.

Step 1, create a users table:

The above is a very basic users table.  We will be using an email address for the login instead of a username.  We’ll do this to demonstrate more features of the Auth setup in CakePHP.

Step 2, update your users_controller.php:

/**
 *  The AuthComponent provides the needed functionality
 *  for login, so you can leave this function blank.
 */
 function login() {}
 
 function logout() {
  $this->redirect($this->Auth->logout());
 }

The above is just a snippet of our users controller.  As you can see, we create a blank login function because CakePHP takes care of everything for us.  Our logout function, logs us out and redirects back to the login page that we will specify shortly.

Step 3, create app/views/users/login.ctp:

<?php
    if  ($session->check('Message.auth')) $session->flash('auth');
    echo $form->create('User', array('action' => 'login'));
    echo $form->input('email');
    echo $form->input('password');
    echo $form->end('Login');
?>

This code creates a basic form with email address and password.  If an auth message exists, it will be displayed above the form.  This is usually where our error messages are displayed about invalid login or access denied, etc…

Step 4, this step can be completed in an individual controller if you only require security in one controller, however, if you need it on multiple controllers, I would suggest adding this to your app_controller.php.

class AppController extends Controller {
 var $components = array('Auth');
 function beforeFilter() {
  $this->Auth->userModel = 'User';
  $this->Auth->fields = array('username' => 'email', 'password' => 'password');
  $this->Auth->loginAction = array('admin' => false, 'controller' => 'users', 'action' => 'login');
  $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
 }
}

As it always seems to be with CakePHP, the above contains some more simple code.  We start by including the Auth Component.  Then in our beforeFilter() function we tell CakePHP how to configure our security.  The first line tells Cake to use the User model.  Next, we configure it to use email and password as the fields oppose to the default of username and password.  It’s important to note, if you wish to change only one of the fields, you are still required to update both.  Next we tell CakePHP to redirect to the users controller and the login function when we are not logged in.  Finally, we tell CakePHP when we have successfully logged in to redirect to the index function of our users controller.

A couple of things to note, we do not specify any allow() pages.  This means that by default ALL of our functions require authorization.

Because we’ve specified the above in our app_controller, we can easily override the defaults on individual controllers for more flexibility.  For example, here is a snippet of code from a users_controller.php that allows the add function, because we want people to be able to register without logging in:

function beforeFilter() {
  $this->Auth->allow('add');
  parent::beforeFilter();
 }

The above code, tells CakePHP to allow the add function in our users_controller.php.  Then it calls the parent beforeFilter function to setup the remaining Auth code.

That’s it, authorization is setup.  I remember feeling overwhelmed by creating a login script with Auth when I first started.  It wasn’t until I tried it that I realized how easy it was, hopefully you will feel the same way now.

  • Share/Bookmark

Other useful articles

Posted By: Jamie
Last Edit: 23 Mar 2009 @ 10:57 AM

EmailPermalink
Tags
Tags: , ,
Categories: CakePHP


 

Responses to this post » (10 Total)

 
  1. qwant says:

    I run into a problem at step 2: I don’t have a users_controller.php file in my cakephp directory. Any suggestions?

  2. Julien says:

    big time saver, thanks a lot for this little tutorial!

    J.

  3. Frederick D. says:

    Thanks very much for the clear article. I have implemented this successfully. Would you do me a favor please? Would you advise me on some sample code to display the user name after a successful login?

    This is what I’ve tried in my users_controller.php file:

    function login() {
    $this->Session->setFlash(‘Please enter your Username and Password.’);
    if ($this->Auth->user()) {
    $this->Session->setFlash(‘You are now logged in.’);
    }
    }

    I get the message “Please enter…” when the login.ctp file is rendered, but I do not get the message on the way out. What am I doing wrong? Plus, I would like the userid in the success message.

    Thanks in advance!

  4. Thanks a lot for the code. Its working perfectly.

    Cheers,
    Arya

  5. wow gold says:

    Looks like your question thing at the end of the post worked. Also not having to sign in is nice too. Good job. Nice list. Thanks.

  6. Hey,,,
    you need to specify which link user will click to get to the login/registration pages

  7. eqxyubrv says:

    eqxyubrv…

    eqxyubrv…

  8. Kevin says:

    Nice article! But, there shouldn’t be any logic in your view. ;)

  9. Kevin says:

    Well, I won’t say there shouldn’t be any logic, but ya might as well keep it in your controller if you can. :P

Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


 Last 50 Posts
 Back
Change Theme...
  • Users » 14
  • Posts/Pages » 75
  • Comments » 231
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight