我正在使用cakephp 3创建一个应用程序,现在我想创建一个允许用户更改密码的功能。问题是密码的验证不起作用。我不知道我是否做得正确。
这是chage_password.ctp文件:
<div class="users form large-9 medium-9 columns">
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Actualice su contraseña') ?></legend>
<?= $this->Form->input('password1',['type'=>'password' ,'label'=>'Ingrese Contraseña']) ?>
<?= $this->Form->input('password2',['type' => 'password' , 'label'=>'Reescriba su Contraseña'])?>
</fieldset>
<?= $this->Form->button(__('Agregar')) ?>
<?= $this->Form->end() ?>
以下是UsersControler.php中的changePassword函数:
public function changePassword($id)
{
$user_data=$this->Users->get($id);
if (!empty($this->request->data)) {
$user = $this->Users->patchEntity($user_data, [
'password' => $this->request->data['password1']
],
['validate' => 'password']
);
$time = Time::now();
$user->set('fecha_cambio_password',$time);
if ($this->Users->save($user)) {
$this->Flash->success('Contraseña Actualizada');
$this->redirect('/users/login');
} else {
debug($user);die;
$this->Flash->error('No se pudo actualizar la contraseña!');
}
}
}
最后在UsersTable.php验证:
public function validationPassword(Validator $validator)
{
$validator
->add('password1', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'El largo minimo es 6',
]
])
->add('password1',[
'match'=>[
'rule'=> ['compareWith','password2'],
'message'=>'Los campos no coinciden',
]
])
->notEmpty('password1');
$validator
->add('password2', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'El largo minimo es 6',
]
])
->add('password2',[
'match'=>[
'rule'=> ['compareWith','password1'],
'message'=>'Los campos no coinciden',
]
])
->notEmpty('password2');
return $validator;
}
答案 0 :(得分:4)
我找到了解决方案!
您需要在patchEntity()方法的第二个参数中传递密码字段
$user = $this->Users->patchEntity($user, [
'old_password' => $this->request->data['old_password'],
'password' => $this->request->data['password1'],
'password1' => $this->request->data['password1'],
'password2' => $this->request->data['password2']
],
['validate' => 'password']
);
要检查旧密码,您需要修改当前验证器,如下所示:
public function validationPassword(Validator $validator )
{
$validator
->add('old_password','custom',[
'rule'=> function($value, $context){
$user = $this->get($context['data']['id']);
if ($user) {
if ((new DefaultPasswordHasher)->check($value, $user->password)) {
return true;
}
}
return false;
},
'message'=>'The old password is not correct!',
])
->notEmpty('old_password');
$validator
->add('password1', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'Min value is 6',
]
])
->add('password1',[
'match'=>[
'rule'=> ['compareWith','password2'],
'message'=>'Los campos no coinciden',
]
])
->notEmpty('password1');
$validator
->add('password2', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'El largo minimo es 6',
]
])
->add('password2',[
'match'=>[
'rule'=> ['compareWith','password1'],
'message'=>'Los campos no coinciden',
]
])
->notEmpty('password2');
return $validator;
}
干杯!