CakePHP: Clearing password field on failed submission

后端 未结 3 1239
南旧
南旧 2021-02-09 15:34

Greetings,

I am setting up a pretty standard registration form with password field.

The problem is, after a failed submission (due to empty field, incorrect form

3条回答
  •  孤独总比滥情好
    2021-02-09 15:58

    You may run into another problem down the road with cakePHP password validation.

    The problem is that cake hashes passwords first, then does validation, which can cause the input to fail even if it is valid according to your rules. This is why the password is returned to the input field hashed instead of normal.


    to fix this, instead of using the special field name 'password', use a different name like 'tmp_pass'. This way, cakePHP Auth won't automatically hash the field.

    Here's a sample form

    echo $form->create('Vendor', array('action' => 'register'));
    echo $form->input('email');
    echo $form->input( 'tmp_pass', array( 'label' => 'Password','type'=>'password' ));
    echo $form->end('Register');
    

    In your Vendor model, don't assign validation rules to 'password' instead assign these rules to 'tmp_pass', for example

    var $validate = array('email' => 'email', 'password' => ... password rules... );
    

    becomes

    var $validate = array('email' => 'email', 'tmp_pass' => ... password rules... );
    

    Finally, in your Vendor model, implement beforeSave().

    First, see if the data validates ('tmp_pass' will be validated against your rules).

    If successful, manually hash tmp_pass and put it in $this->data['Vendor']['password'] then return true. If unsuccessful, return false.

    function beforeSave() {
        if($this->validates()){
            $this->data['Vendor']['password'] = sha1(Configure::read('Security.salt') . $this->data['User']['tmp_pass']);
            return true;
        }
        else
            return false;
    }
    

提交回复
热议问题