【问题标题】:minLength data validation is not working with Auth component for CakePHPminLength 数据验证不适用于 CakePHP 的 Auth 组件
【发布时间】:2011-02-14 12:08:07
【问题描述】:

假设我有一个用户注册并且我正在使用 Auth 组件(当然允许 /user/register)。

问题是如果我需要在模型中设置一个 minLength 验证规则,它不起作用,因为 Auth 组件对密码进行哈希处理,因此它总是超过我的 minlength 密码,即使它是空白的,它也会通过。

我该如何解决这个问题?提前致谢!

【问题讨论】:

  • 这很奇怪。 minLength 验证规则对我来说非常适合 Auth 组件。我对密码字段有两个验证规则:minLength 和 notEmpty。
  • @bancer:这绝对不是我的经验。你用的是什么版本的蛋糕?你的验证码是什么样的?
  • @mikermcneil:这是蛋糕 1.2。 $validate 数组的一部分:'password' => array( 'minLength' => array( 'rule' => array('minLength', '8') ), 'notEmpty' => array( 'rule' => 'notEmpty', 'required' => true ) ), 'confirm_password' => array( 'minLength' => array( 'rule' => array('minLength', '8'), 'required' => true ), 'notEmpty' => array( 'rule' => 'notEmpty' ), 'comparePasswords' => array( 'rule' => '_comparePasswords' // Protected function below ), ).
  • @mikermcneil:密码比较方法:protected function _comparePasswords(){ $hashedConfirmPassword = Security::hash($this->data['User']['confirm_password'], null, true); if($this->data['User']['password'] == $hashedConfirmPassword){ return true; }else{ return false; } }

标签: authentication cakephp validation


【解决方案1】:

本质上,您必须重命名密码字段(例如,改名为“pw”)以防止 Auth 组件自动对其进行哈希处理。然后,如果密码通过了验证规则,则对其进行散列并将散列保存在 password 键下。这通常在beforeFilter() 回调中完成,正如this article 所描述的那样。

还可以在控制器中验证数据并散列密码。通常不鼓励这种做法,但如果您刚刚开始使用 CakePHP,可能会更容易理解。

// this code would go after: if (!empty($this->data)  
//               and before: $this->User->save($this->data)

// validate the data
$this->User->set($this->data);
if ($this->User->validates()) {

    // hash the password
    $password_hash = $this->Auth->password($this->data['User']['pw'];
    $this->data['User']['password'] = $password_hash;
}

【讨论】:

  • 感谢麦克,它有效!但要做到这一点,Auth 组件很笨重,我们必须采取变通办法。 :(
  • 嗨,迈克,您发布到该文章的链接已失效。有另一个副本吗?谢谢!
  • @mikermcneil:感谢您指出这一点。我已经更新了链接。
【解决方案2】:

hmm.. 这是我认为的最佳做法:保持密码字段不变。包括第二个密码字段“pw2”,以便用户可以重新输入密码。优点:

  • 防止用户输入错误
  • Auth 不会散列 pw2。在模型中,您可以编写自定义密码验证方法(因为您还需要检查两个密码是否相同)
var $validate = array(
  'password' => array(
    'rule' => array('checkPwd')
  )
);
function checkPwd($check) {
  if(!isset($this->data[$this->alias]['password']) || 
     !isset($this->data[$this->alias]['pw2']))
     return 'Where are the passwords?';
  if($this->data[$this->alias]['password'] !== 
    Security::hash($this->data[$this->alias]['pw2'],null,true))
    return 'Passwords are not the same';
  if(strlen($this->data[$this->alias]['pw2']))<10)
    return 'Password not long enough';
  return true;
}

有一点,在表单视图中,为两个密码字段设置 'value'=>''。

【讨论】:

    猜你喜欢
    • 2011-05-09
    • 2021-02-11
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2019-08-22
    • 1970-01-01
    相关资源
    最近更新 更多