密码在编辑时哈希两次 - CakePHP

Alb*_*ert 5 php authentication cakephp-2.0

我有一个用户编辑视图.当人们访问此视图时,密码块中包含哈希密码.

如果单击"保存",它(显然)会再次哈希密码,因为这是在我的用户模型中.

public function beforeSave($options = array()) {
    if(!empty($this->data['User']['password'])) {
        $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

但是我不希望它有两次哈希(因为这意味着密码已经改变).我更改了编辑视图并添加array('value' => '','autocomplete'=>'off')到密码字段.现在当我保存它时,它会在数据库中保存一个空白字符串.我认为它阻止它使用函数中的if(!empty($this->data['User']['password']))语句执行此操作beforeSave.

如何防止密码被双重哈希?

Alb*_*ert 5

解决方案相当简单.只需更改beforeSave中的if语句:

public function beforeSave($options = array()) {
    if(!empty($this->data['User']['password'])) {
        $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

至:

public function beforeSave($options = array()) {
    if(!empty($this->data['User']['password'])) {
        $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
    } else {
        unset($this->data['User']['password']);
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)