views:

70

answers:

2

How do I run validation checks on a password field in CakePHP, seeing that the password is hashed before I get a chance to run any checks on it?

A: 

It works this way for me (in the model):

  public $validate = array(
        'password' => array(
            'minLength' => array(
                'rule' => array('minLength', '8')
            )
         )
    );

If you want to do more validations then create a custom validation method in the appropriate model. In the custom validation method hash password this way: Security::hash($this->data['User']['password'], null, true)

bancer
Of course this works, as it **ALWAYS** will since the password is hashed prior to validation and the hash is always longer than 8 characters. This does nothing to enforce the unhashed password being 8 characters or longer. Try testing your form with a single digit password - it will validate.
Abba Bryant
Actually, I had to mention that I have 'confirm_password' field in the same form with the same validation rule. I created this form so long time ago that I forgot that I labeled it 'Password' in the views and the real field 'password' I labeled 'Confirm password'. So, when I enter one character for the password validation fails.
bancer
+2  A: 

If you only have a single password field in your form, you will need to create a custom hash function that either does nothing, or, better, preserves the original password somewhere.

Most likely though you have two password fields in your form where the user is required to confirm the password. In this case, you perform your password validation rules on the second password field. This can automatically happen in a custom validation rule, remember that you have access to all other fields inside a validation function via $this->data. You can then confirm that the two passwords are identical as described here.

deceze
The problem I seem to have is that the password is hashed before it gets to the validation stage, so that the validations that i run only only apply to the hashed password.
chustar
@chustar That's why you do the validation **on the `password2` field,** which is not automatically hashed.
deceze
This blog post details how to create a custom hash function, as deceze mentions, to work around this issue: http://teknoid.wordpress.com/2008/10/08/demystifying-auth-features-in-cakephp-12/ (Start reading from the second code example.)
deizel