I’ve been using this tutorial to rewrite my login/logout functionality to handle authentication and matching passwords in the model.
It now adds the user perfectly, but upon login the username/password fields are rejected. It seems the login function is looking for a differently hashed password than my new hashPasswords() function is storing. Any suggestions on what the problem could be?
It’s a fairly standard setup. Thanks for any help!
Pertinent Sections of code:
User Model:
var $validate = array(
'password' => array(
'The Password must be filled' =>array(
'rule' => 'notEmpty',
'message' => 'Please supply a valid password.'
),
'The Password must be between 5 and 15 characters' => array(
'rule' => array('between', 5, 15),
'message' => 'The password must be between 5 and 15 characters.'
),
'The passwords do not match' => array(
'rule' => 'matchPasswords',
'message' => 'The passwords do not match.'
)
),
function hashPasswords($data) {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = Security::hash($this->data['User']['password'], NULL, TRUE);
return $data;
}
return $data;
}
function beforeSave() {
$this->hashPasswords(NULL, TRUE);
return TRUE;
}
Users Controller:
function beforeFilter() {
parent::beforeFilter();
if ($this->action == 'add' || $this->action == 'edit' ) {
$this->Auth->authenticate = $this->User;
}
}
function add() {
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your Account Has Been Created.');
$this->redirect(array('action' => 'homepage'));
}
}
}
function login() {
}
I haven’t seen the video, but –
When $this->data[‘User’] has a ‘username’ and ‘password’ array, and is used to save a user – cake actually hashes the password. What may potentially be happening is your hashed password being hashed again – check out the cake documentation on hashPassword
As far as password matching goes – it is actually far easier to do this on the client side where they aren’t hashed (lots of Jquery functions out there that validate forms). You can even go as far as writing a simple:
If you want validate in the model, then certainly write a custom validation rule – but again the password will be hashed for you – you only need to compare the non-hashed versions and see if they match, returning true if they do.
Also – everyone has completely different ways of authenticating users – first and foremost read the documentation – there’s an excellent tutorial for a simple Authenticated / ACL application which takes about 30 mins to go through and should be anyones starting point.