password hashing before save

Just wondering where you guys typically do your password hashing in your User model.

I was thinking that onAfterSave() would be the best place to do it, but then I was thinking about if an admin modifies a User record – you don’t want the password rehashing if he hasn’t changed it.

thoughts? :D

See here:

http://www.yiiframework.com/forum/index.php?/topic/3886-jformvalidate-extension-validate-required-field-even-when-it-shouldnt/page__view__findpost__p__21875

thanks Mike, a simple solution is usually the best! :g:

I have resolved this a bit different:




public function beforeSave() {

     if ($this->isNewRecord) // <---- the difference

         $this->password=md5($this->password);

     return true;

 }



@ricardograna:

But this way you overwrite any existing password in db, even if the password field is empty.




$hash = new CSecurityManager;

$hash->encrypt($this->password);



It will be not empty, because beforeSave is after the execution of required validation.

Just hash for the new records. For update the password, I usually do it in another specific form.

In this case it works, of course. I usually use the same model also for update forms where an empty password field indicates "no change".