Last active
November 5, 2015 19:30
-
-
Save mtancoigne/4d7c6d38976e8deac60e to your computer and use it in GitHub Desktop.
Password check for password change in cakePHPx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// in Model/Entity/User.php | |
public function comparePassword($password) | |
{ | |
return (new DefaultPasswordHasher)->check($password, $this->password); | |
} | |
// In user/<someview>.ctp | |
echo $this->Form->create($user, ['action' => 'update_password']); | |
echo $this->Form->input('current_password', ['type' => 'password', 'label' => __d('users', 'Current password')]); | |
echo $this->Form->input('password', ['type' => 'password', 'value' => '', 'label' => __d('users', 'New password')]); | |
echo $this->Form->input('password_confirm', ['type' => 'password', 'value' => '', 'label' => __d('users', 'Confirmation')]); | |
// In Controller/UserController.php | |
/** | |
* Update the password in DB | |
* | |
* @return void Redirects | |
*/ | |
public function updatePassword() | |
{ | |
if ($this->request->is(['patch', 'post', 'put'])) { | |
// Getting user data | |
$user = $this->Users->get($this->Auth->user('id')); | |
// Checking old password | |
if ($user->comparePassword($this->request->data['current_password'])) { | |
$user = $this->Users->patchEntity($user, $this->request->data); | |
// Saving new password. Validation and hashing is made in UserTable. | |
if ($this->Users->save($user)) { | |
$this->Flash->success(__('Your password has been updated.')); | |
return $this->redirect(['action' => 'updatePassword']); | |
} else { | |
$errors = $user->errors(); | |
$errorMessages = []; | |
array_walk_recursive($errors, function ($a) use (&$errorMessages) { | |
$errorMessages[] = $a; | |
}); | |
$this->Flash->error(__('An error occured. Please, try again.'), ['params' => ['errors' => $errorMessages]]); | |
return $this->redirect(['action' => 'updatePassword']); | |
} | |
} else { | |
$this->Flash->error(__d('users', 'Sorry, you have entered the wrong password.')); | |
return $this->redirect(['action' => 'updatePassword']); | |
} | |
} else { | |
// Not really useful | |
$this->Flash->error(__d('users', 'To access this page, you need to fill the form first.')); | |
return $this->redirect(['action' => 'updatePassword']); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment