Ph: 786-539-6996

Updating user passwords with Cakephp

If wee need to create a form to change the user password, specifically for users, with the classic structure like:

a) Write your old password: Input box

b) New password: Input box name=’np1′

c) Write again your new password: Input box name=’np2′

We can create a simple Javascript code to check if both new passwords are the same, but, in Users Controller, we have to check after the submit, if the old password the user has written, is the same as the password encrypted.

Sometimes, instead of use the email to change the password, we need to allow our users to update the password:

In that case, in order to check if the user is the owner of the account and to avoid mistakes, we need to show two steps:

a) Check if he knows the previous password. Our task here: Check this password against the encrypted password in our database.

b) Write and rewrite the new password. Our Task here: We have to check if both new passwords are the same.

An useful function could be:

//In Users Controller, where we are receiving the data from the form Edit User Password:

if ($this->request->is([‘patch’, ‘post’, ‘put’])) {

$password=$this->request->getData(‘oldpassword’);//Getting the old password the user has written in the form

$newpassword=$this->request->getData(‘np1’);    //getting the new password

$hashedPassword=$user->password;  //getting the previous/older password from pour database

$check=$this->Users->check($password,$hashedPassword);
if( $check == FALSE)  {  $this->Flash->error(__(‘Wrong Current Password. Try again’));  }

else {…

//Here we allow the data to be updated

}

//In Users Table:

public function check($password, $hashedPassword){
return password_verify($password, $hashedPassword);
}

With that structure, we can reuse our function any time we want to check the same. We do not need to know the real password encrypted, just by comparison both encrypted strings, we can decide if are the same or not.

More info in the official page, here,

And here

May 4th, 2019 | aesio

Leave a Reply

Your email address will not be published. Required fields are marked *

Time Programmer Corp Since 2014 ®