Why is the CakePHP authentication component not hashing my password?

Eric picture Eric · Mar 6, 2009 · Viewed 11.7k times · Source

I'm using CakePHP 1.2 with Auth and ACL components.

In my user register action, the password is coming in unhashed. Specifically, this expression:

if ($this->data['User']['password'] !=
    $this->Auth->password($this->data['User']['confirm_password']))

This is evaluating to true, even when I submit identical values for password and confirm_password. I know that password is unhashed because when I remove the call to Auth->password, the expression evaluates to false.

I expected the Auth module to automagically hash the password. What am I doing wrong?

Here is my view:

<?php
    echo $form->create('User', array('action' => 'register'));

    echo $form->input('email',
                      array('after' => $form->error(
                        'email_unique', 'This email is already registered.')));
    echo $form->input('password');
    echo $form->input('confirm_password', array('type' => 'password'));
    echo $form->end('Register');
?>

Here is my register action from the user controller:

function register(){
    if ($this->data) {
        if ($this->data['User']['password'] !=
            $this->Auth->password($this->data['User']['confirm_password'])) {

            $this->Session->setFlash(__('Password and Confirm Password must match.', true));
            $this->data['User']['password'] = '';
            $this->data['User']['confirm_password'] = '';
        }
        else{
            $this->User->create();
            if ($this->User->save($this->data)){
                $this->redirect(array('action' => 'index'), null, true);
            }
            else {
                $this->data['User']['password'] = '';
                $this->data['User']['confirm_password'] = '';
                $this->Session->setFlash(__('Some problem saving your information.', true));
            }
        }
    }
}

And here is my appController where I include the Auth and Acl modules:

class AppController extends Controller {
    var $components = array('Acl', 'Auth');

    function beforeFilter(){
        if (isset($this->Auth)) {
            $this->Auth->allow('display');
            $this->Auth->fields =
              array(
                'username' => 'email',
                'password' => 'password');
            $this->Auth->authorize = 'actions';
        }
    }
}

What am I doing wrong?

Answer

Eric picture Eric · Mar 7, 2009

CakePHP won't hash passwords unless username contains a submitted value. I'm replacing the username field with email. However, I remapped those fields by setting the Auth->fields array. However, I was doing that in the appController instead of userController. So moving this line:

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

out of appController into userController solved it.
Now the question becomes "Why can't I reset the Auth->fields in appController?"