« Going To CakeFest!
» What’s In Chris’ Brain: January 2008 Edition

Uncategorized

Simple User Registration in CakePHP 1.2, Part II

01.22.08 | 27 Comments

I got a question in the comments about my previous post on simple user registration about how to do some of the necessary validation for registration in the model. I thought I'd show some code I did to do exactly that.

The key to all this stuff is using a second form field for doing the validation. Here's some sample code for you, based on the latest straight-from-svn version of Cake PHP 1.2 (r6402)

PHP:
  1. <?php
  2.  
  3. /**
  4. * Class used for user authentication on the league website
  5. *
  6. */
  7.  
  8. class User extends AppModel
  9. {
  10.     var $name = 'User';
  11.  
  12.     var $validate = array(
  13.         'id' => array('rule' => 'blank',
  14.                       'on' => 'create'),
  15.         'username' => array('rule' => 'alphanumeric',
  16.                             'required' => true,
  17.                             'message' => 'Please enter a username'),
  18.         'password' => array('rule' => array('confirmPassword', 'password'),
  19.                             'message' => 'Passwords do not match'),
  20.         'password_confirm' => array('rule' => 'alphanumeric',
  21.                                     'required' => true)
  22.     );
  23.  
  24.     function confirmPassword($data) {
  25.         $valid = false;
  26.        
  27.         if ($data['password'] == Security::hash(Configure::read('Security.salt') . $this->data['User']['password_confirm'])) {
  28.             $valid = true;
  29.         }
  30.        
  31.         return $valid;
  32.     }
  33.  
  34. }
  35. ?>

So, let's talk about what's in there.

  • make sure that the username is alphanumeric and has been entered
  • make sure the password exists and run the custom validation function 'confirmPassword' on the data being posted in
  • make sure that our confirm password field exists and is alphanumeric

The only tricky thing when I made this was figuring out how to compare the two password fields, and where to get the proper hashing from. Initially I thought that I could somehow import the Auth component in there but a quick chat with gwoo showed me how stupid that was when I could just duplicate how the component itself is hashing the password field. That's what is going in with the use of Security::hash(...).

Hope that helps.

Tags: ,

27 Comments

have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

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>

:

:


« Going To CakeFest!
» What’s In Chris’ Brain: January 2008 Edition