CakePHP 3 formularz zmiany hasła
Pokażę jak w CakePHP 3 zrobić formularz zmiany hasła. Najpierw w pliku UsersTable.php (zakładam, że za użytkowników i ich logowanie odpowiada model Users w metodzie validationDefault dodajemy następującą regułę walidacji dla pola password. Sprawdzamy czy pole password i password1 (tzn. powtórz hasło) są takie same oraz czy stare hasło zgdza się z tym przechowywanym w bazie.
$validator
->scalar('password')
->maxLength('password', 255)
->requirePresence('password', 'create')
->notEmpty('password')
->sameAs('password','password2',__('Passwords not equal.'))
->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 does not match the current password!'),
]);
oraz na górze pliku należy dodać:
use Cake\Auth\DefaultPasswordHasher; use Cake\Validation\Validator;W pliku changepassword.ctp dodajemy formularz.
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Change Password') ?></legend>
<?php
echo $this->Form->control('old_password', ['type'=>'password']);
echo $this->Form->control('password', ['type'=>'password', 'value' => '']);
echo $this->Form->control('password2', ['type'=>'password']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
W kontrolerze natomiast obsłużymy zmianę hasła.
public function changepassword()
{
$user =$this->Users->get($this->Auth->user('id'));
if (!empty($this->request->data)) {
$user = $this->Users->patchEntity($user, [
'old_password' => $this->request->data['old_password'],
'password' => $this->request->data['password1'],
'password2' => $this->request->data['password2']
]
);
if ($this->Users->save($user)) {
$this->Flash->success('The password is successfully changed');
$this->redirect('/index');
} else {
$this->Flash->error('There was an error during the save!');
}
}
$this->set('user',$user);
}
