4
votes

I have a User Model, a UsersController and an AccountController which uses the User Model (the account controller is used when an account is created, login, logout).

Everything works fine, except the beforeSave function in AccountController. I'm trying to use beforeSave to hash my password but it doesn't work (the password is saved un-hashed in the database).

public function beforeSave() {
    parent::beforeSave();   

    if (isset($this->request->data['User']['password'])) {
        $this->request->data['User']['password'] = sha1($this->request->data['User']['password']);
    }

    return true;
}

A few notes:

  • I use "sha1" to hash the password because I'm converting an old system to CakePHP (the old system used sha1 to hash the passwords)
  • Even if I return false; the save function is still executed (which I thought should not be the case
  • calling debug($this->request->data) gives me nothing
  • I added the same beforeSave function in my UsersController but it didn't work as well

I think in my case beforeSave is not being called, I just can't figure out why.


Solved: The beforeSave function has to go inside the model, this is my beforeSave function now:

public function beforeSave($options = array()) {
        parent::beforeSave();
        $this->data['User']['password'] = sha1($this->data['User']['password']);
        return true;
    }
1
Not so relevant to your question... But do you really want to hash your password this way? Why don't you use AuthComponent::password($this->request->data['User']['password']) for that? That makes sure you use your apps configured hashing strategy for the passwords, and prevents trouble if you'd ever decide to switch to another hashing methodJoep
Ah ok, so I can change the hashing method in a config file so that sha1() is being used?Christian Strang
Cookbook on AuthComponent::password And, yeah, you should be able to configure that somewhere, probably core.php or something (I'm not sure where that option is in 2.1)Joep
Thank you! I will definitely look into this.Christian Strang

1 Answers

3
votes

beforeSave is a Model callback, so define it in your Model(s).