cakephp密码验证

aWe*_*per 7 php passwords cakephp

var $validate = array(
  'password' => array(
      'passwordlength' => array('rule' => array('between', 8, 50),'message' => 'Enter 8-50 chars'),
      'passwordequal' => array('checkpasswords','message' => 'Passwords dont match') 
  )
);

function checkpasswords()
{
   return strcmp($this->data['Airline']['password'],$this->data['Airline']['confirm password']);
}
Run Code Online (Sandbox Code Playgroud)

此代码无效,即使匹配也始终显示错误消息.此外,当我进行编辑时,我得到了跟随错误,因为没有密码字段.有没有修复

Undefined index:  password [APP/models/airline.php, line 25]
Run Code Online (Sandbox Code Playgroud)

dec*_*eze 12

您使用的是AuthComponent吗?请注意它会散列所有传入的密码字段(但不是"密码确认"字段,请检查debug($this->data)),因此字段将永远不会相同.阅读手册并使用AuthComponent::password进行检查.


话虽如此,这是我使用的东西:

public $validate = array(
    'password' => array(
        'confirm' => array(
            'rule' => array('password', 'password_control', 'confirm'),
            'message' => 'Repeat password',
            'last' => true
        ),
        'length' => array(
            'rule' => array('password', 'password_control', 'length'),
            'message' => 'At least 6 characters'
        )
    ),
    'password_control' => array(
        'notempty' => array(
            'rule' => array('notEmpty'),
            'allowEmpty' => false,
            'message' => 'Repeat password'
        )
    )
);

public function password($data, $controlField, $test) {
    if (!isset($this->data[$this->alias][$controlField])) {
        trigger_error('Password control field not set.');
        return false;
    }

    $field = key($data);
    $password = current($data);
    $controlPassword = $this->data[$this->alias][$controlField];

    switch ($test) {
        case 'confirm' :
            if ($password !== Security::hash($controlPassword, null, true)) {
                $this->invalidate($controlField, 'Repeat password');
                return false;
            }
            return true;

        case 'length' :
            return strlen($controlPassword) >= 6;

        default :
            trigger_error("Unknown password test '$test'.");
    }
}
Run Code Online (Sandbox Code Playgroud)

这很糟糕,原因如下:

  • 与表格紧密耦合,总是希望存在一个字段password_control.如果您的数据中没有,则需要使用字段白名单或禁用验证,即:$this->User->save($this->data, true, array('field1', 'field2')).
  • 以AuthComponent的方式手动哈希密码(因为没有对模型中组件的干净访问).如果更改AuthComponent中使用的算法,则还需要在此处进行更改.

话虽如此,它透明地验证并生成密码和密码控制字段的正确错误消息,而无需控制器中的任何其他代码.


aWe*_*per 5

这是错误

'passwordequal' => array('checkpasswords','message' => 'Passwords dont match') 
Run Code Online (Sandbox Code Playgroud)

我改成了

'passwordequal'  => array('rule' =>'checkpasswords','message' => 'Passwords dont match')
Run Code Online (Sandbox Code Playgroud)

strcmp函数也有错误,因为它会在上面的代码中一直返回0(即False)

if(strcmp($this->data['Airline']['password'],$this->data['Airline']['confirm_password']) ==0 )
{
    return true;
}
return false;
Run Code Online (Sandbox Code Playgroud)

  • 哦,可怕的冗余!在这种情况下你应该使用`return strcmp(...)== 0`. (5认同)