PasswordBehavior

This behavior encrypts passwords for your data model on-the-fly and handles the case of updating a record with a blank password (which usually means leave the password as-is):




class PasswordBehavior extends CBehavior

{

  public $password_field = 'password';


  public function attach($component)

  {

    $component->attachEventHandler('onBeforeSave', array(&$this, 'encryptPassword'));

    $component->attachEventHandler('onBeforeValidate', array(&$this, 'validatePassword'));

  }


  public function validatePassword($event)

  {

    $sender = &$event->sender;

    $password = $sender->{$this->password_field};


    if($sender->isNewRecord && empty($password)) {

      $sender->addError('password', 'Password cannot be blank');

      return false;

    }


    return true;

  }


  public function encryptPassword($event)

  {

    $sender = &$event->sender;

    $sender->{$this->password_field} = md5($sender->{$this->password_field});

    return true;

  }

}



It handles the case where the record is new, and triggers a validation error if the password is blank. I’ve yet to put in a password confirmation check, coming soon.

"handles the case of updating a record with a blank password"

I can not see this here… also does it handle the case of updating at all? When updating, it should not re-encrypt the password again.

Also, perhaps you should not do validation in here as you never know how the user want’s their passwords validated.

besides that, good job! Good to see an example of attachEventHandler()

Yeah, good points. I changed the algorithm a little and came up with a solution which is pretty much identical to other encrypt password solutions, so this thread can probably die an ignoble death. :P