CakePHP login form with password confirmation using Auth component

In: development

14 Dec 2009

Every time I start CakePHP project, I find that I’ve forgotten how to set up the user auth system of logins, creating accounts, etc. There seems to be only a few examples of it on the internet, so I thought I’d post up my solution. It uses the Auth component and follows normal user creation convention. By “normal user creation convention,” I mean that you require an email address that’s used as the login name, a password field, a confirm-password field, and checks to make sure the passwords match.

First, create your db table:

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `email` varchar(60) default NULL,
  `firstname` varchar(30) default NULL,
  `lastname` varchar(30) default NULL,
  `password` varchar(40) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Next, create models/user.php and add validation definitions. Modify the validation parameters as neede. You’ll also need a function that checks whether the two password fields match.

class User extends AppModel {
  var $name = 'User';
  var $useTable = 'users';


  var $validate = array(
    'email' => array(
      'kosher' => array(
        'rule' => 'email',
        'message' => 'Please make sure your email is entered correctly.'
      ),
      'unique' => array(
        'rule' => 'isUnique',
        'message' => 'An account with that email already exists.'
      ),
      'required' => array(
        'rule' => 'notEmpty',
        'message' => 'Please Enter your email.'
      )
    ),
    'passwd' => array(
      'min' => array(
        'rule' => array('minLength', 6),
        'message' => 'Usernames must be at least 6 characters.'
      ),
      'required' => array(
        'rule' => 'notEmpty',
        'message'=>'Please enter a password.'
      ),
    ),
    'passwd_confirm' => array(
      'required'=>'notEmpty',
      'match'=>array(
        'rule' => 'validatePasswdConfirm',
        'message' => 'Passwords do not match'
      )
    ),
    'firstname' => array(
      'required' => array(
        'rule' => 'notEmpty',
        'message'=>'Please enter your first name.'
      ),
      'max' => array(
        'rule' => array('maxLength', 30),
        'message' => 'First name must be fewer than 30 characters'
      )
    ),
    'lastname' => array(
      'required' => array(
        'rule' => 'notEmpty',
        'message' => 'Please enter your last name.'
      ),
      'max' => array(
        'rule' => array('maxLength', 30),
        'message' => 'Last name must be fewer than 30 characters'
      )
    )
  );

  function validatePasswdConfirm($data)
  {
    if ($this->data['User']['passwd'] !== $data['passwd_confirm'])
    {
      return false;
    }
    return true;
  }

  function beforeSave()
  {
    if (isset($this->data['User']['passwd']))
    {
      $this->data['User']['password'] = Security::hash($this->data['User']['passwd'], null, true);
      unset($this->data['User']['passwd']);
    }

    if (isset($this->data['User']['passwd_confirm']))
    {
      unset($this->data['User']['passwd_confirm']);
    }

    return true;
}

}

Create the controllers/user_controller.php file:

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

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

    $this->Auth->allow('register');
  }

  function index() {

  }

  function login() {

  }

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

  function register() {
    if (!empty($this->data)) {
      $this->User->create();
      if($this->User->save($this->data))
      {
        $this->Session->setFlash("Account created!");
        $this->redirect('/');
      }
    }
  }

}

Create the login.ctp view:

$session->flash('auth');
echo $form->create('User', array('action' => 'login'));
echo $form->input('email');
echo $form->input('password');
echo $form->end('Login');
echo $html->link('Sign up', array('controller'=>'users', 'action'=>'register'));

Create the register.ctp view:

echo $form->create('User', array('action' => 'register'));
echo $form->input('email');
echo $form->input('firstname');
echo $form->input('lastname');
echo $form->input('passwd');
echo $form->input('passwd_confirm', array('type' => 'password'));
echo $form->submit();
echo $form->end();

Notice that we named the field “passwd” and not “password”? This is because Cake recognizes it as being a password and automatically hashes it. Although you could set up your app this way, it makes it complicated to do validation on it. Instead, we just use “passwd” and assign the value to “password” in our beforeSave function.

That’s it! Your basic user login/registration should be working now. Customize it according to your app’s needs.

8 Responses to CakePHP login form with password confirmation using Auth component

Avatar

Shax

November 7th, 2010 at 1:24 pm

Thnx for the info

Avatar

David

August 25th, 2011 at 7:40 am

Nice and really insightful

Avatar

Dan

September 9th, 2011 at 10:19 pm

This helps a lot, thanks so much

Avatar

suryak

March 22nd, 2012 at 3:50 am

thanx good work

Avatar

mayank

April 18th, 2012 at 3:37 am

I really helpful

Avatar

Mohini

November 21st, 2012 at 12:03 am

Thanks for sharing this.

This one really helped.

Avatar

Nimesh

February 7th, 2013 at 1:29 am

Hi
Thnk u,
because it is very useful and more important for cakephp understanding,

Avatar

Ravi

February 7th, 2013 at 1:31 am

Thanks.
Its solve my problem.
keep it up.:)

Comment Form

About this blog

I'm Jon Chin. I love technology, food, and learning. I served a mission in the Philippines and loved it. You probably can't type on my keyboard because I don't have qwerty installed--I use Colemak. I'm obsessed with learning about North Korea and abandoned anything.

Photostream