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.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Slashdot
  • Facebook
  • Google Bookmarks