Я создаю форму смены пароля в CakePHP, которая требует, чтобы пользователь вводил свой текущий пароль, новый пароль и подтверждал новый пароль. После того, как все будет введено, пароль пользователя будет изменен, учитывая, что все записи соответствуют установленным правилам проверки.Правила валидатора CakePHP в UsersTable.php не работают
Однако правила валидации не работают. Пользователю не нужно заполнять все поля, устанавливать новый пароль на определенную длину, следить за тем, чтобы совпадающие поля нового пароля и подтверждения совпадали, и т. Д. Мне кажется, что я не знаю, в чем проблема.
Я приведу все соответствующие коды ниже. Спасибо :)
change_password.ctp (Вид файла)
<div class="users form large-9 medium-9 columns">
<?= $this->form->create() ?>
<fieldset>
<legend> <?= __('Change Password') ?> </legend>
<?= $this->Form->input('current_password', ['type' => 'password']) ?>
<?= $this->Form->input('new_password', ['type' => 'password']) ?>
<?= $this->Form->input('confirm_new_password', ['type' => 'password']) ?>
</fieldset>
<?= $this->Form->button(__('Save')) ?>
<?= $this->Form->end() ?>
</div>
Changepassword() в UsersController
public function changePassword()
{
$user = $this->Users->get($this->Auth->user('id'));
if (!empty($this->request->data)) {
$user = $this->Users->patchEntity($user, [
'password' => $this->request->data['new_password'],
],
['validate' => 'password']
);
if ($this->Users->save($user)) {
$this->Flash->success('The password is successfully changed');
$this->redirect('/users');
} else {
$this->Flash->error('There was an error during the save!');
}
}
$this->set('user', $user);
}
validationPassword() в UsersTable (т.е. правил проверки)
public function validationPassword(Validator $validator)
{
$validator
->add('current_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'=>'Incorrect Password!',
])
->notEmpty('current_password');
$validator
->add('new_password', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The password must be at least 6 characters!',
]
])
->add('new_password',[
'match'=>[
'rule'=> ['compareWith','confirm_new_password'],
'message'=>'The passwords does not match!',
]
])
->notEmpty('new_password');
$validator
->add('confirm_new_password', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The password must be at least 6 characters!',
]
])
->add('confirm_new_password',[
'match'=>[
'rule'=> ['compareWith','new_password'],
'message'=>'The passwords does not match!',
]
])
->notEmpty('confirm_new_password');
return $validator;
}
EDIT: Добавлен файл User.php
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Validation\Validator;
/**
* User Entity.
*
* @property int $id
* @property string $first_name
* @property string $last_name
* @property string $email
* @property string $username
* @property string $password
*/
class User extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $_accessible = [
'*' => true,
'id' => false,
];
/**
* Fields that are excluded from JSON an array versions of the entity.
*
* @var array
*/
protected $_hidden = [
'password'
];
protected function _setPassword($value) {
$hasher = new DefaultPasswordHasher();
return $hasher->hash($value);
}
}
Мой стол Пользователь имеет столбец пароль, который содержит пароль пользователя. Другие поля есть для проверки, но фактически не будут вставлены в таблицу User. Итак, если бы я добавил код для установки других полей, я бы не смог вставить его в свою БД. – skipper
Я пробовал делать то, что вы рекомендовали, и это дает мне ошибку. Потому что у меня нет соответствующих таблиц для new_password, current_password и confirm_new_password – skipper
Вы имели в виду * соответствующие поля *? Правила проверки применяются в функции patchEntity, а не раньше. Я обновил свой ответ –