Cakephp, Auth and Empty Password Problem

Auth component is excellent one that i love in Cakephp for authentication but one problem i faced with this, empty password problem. That is – to add a new user, it takes empty password if we use password field. Model validation doesn’t work for password field if we put no value in password field, because – auth component create a hashed password after the form submission with empty value, so it can pass Model validation easily. I solved it another way – here is it.

Don’t use the name ‘password’ for the password field instead use another name, let it is ‘passwd’. It’s better to use confirm password field. Lets add user view code is as below


echo $form->create('User');
echo $form->input('username');
echo $form->input('passwd');
echo $form->input('passwd_confirm');
echo $form->end('Submit');


As we don’t have password field in form, we need to create the value for password field in controller. Lets create this in beforeSave method and call this from add method. Here is a sample code to handle password stuffs in user controller –

function beforeSave()
if (!empty($this->data['User']['passwd']))
$this->data['User']['password'] = $this->Auth->password($this->data['User']['passwd']);
return true;

function admin_add() {
if (!empty($this->data)) {
if ($this->User->save($this->data)) {

This will process the password by beforeSave call. Now its the time for add validation in Model. Here is the validation which will check if the username is a valid email address, uniqe, password field is minimum 6 characters in length, matching of password and confirm password. I’ve created a custom method to check the match of password and cofirm password. here are the validation and custom method codes for user Model –

var $validate = array(
'username' => array(
'email' => array(
'rule' => 'email',
'required' => true,
'message' => 'Username should be a valid email'
'unique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken'
) ,
'passwd' => array(
'rule' => array('minLength', '6'),
'message' => 'Password should be atleast 6 characters long',
'required' => true,
'allowEmpty' => false,
'on' => 'create'
'passwd_confirm' => array(
'rule' => 'matchpwd',
'message' => 'Confirm password doesnt match'

* This method will be called to check password match
function matchpwd($data){
if ($this->data['User']['passwd']!=$data['passwd_confirm'] ) {
return false;
return true;

One small note, in database, we must have fields – username, password in users table. That’s it
Posted in CakePhp Tagged: CakePhp