Web Development. Client Satisfaction. Web Consultancy. Professional. UX. Fast. Responsive Design. Dynamic. Interactive. Innovative. Ecommerce. Wordpress plugins. Prestashop modules. You name it.

How To Make Change Password In Symfony

How To Make Change Password In Symfony

Even if there are a lot of tutorials out there on how to change password in symfony, it took some time to find a nice method to check if the old password written by the user is the same with the one from database. If you will try to encode password and check if the old password from form is the same with the one from database it will return everytime false because symfony even if will use the same method to encrypt, it will return other string then one from database so you have to check in other way.

In controller add the following function:

public function change_user_password(Request $request, UserPasswordEncoderInterface $passwordEncoder) {
   $old_pwd = $request->get('old_password'); 
  $new_pwd = $request->get('new_password'); 
  $new_pwd_confirm = $request->get('new_password_confirm');

  $user = $this->getUser();
  $checkPass = $passwordEncoder->isPasswordValid($user, $old_pwd);

  if($checkPass === true) {
        	
  } else {
    return new jsonresponse(array('error' => 'The current password is incorrect.'));
  }
}

isPasswordValid() function will make this validation for you, if the confirm old password is the same with the one from the database the function will return true, then you can encode the new password and change it in the database. 

$new_pwd_encoded = $passwordEncoder->encodePassword($user, $new_pwd_confirm); 

The above line of code will encode the password using the enctype method you privede in the security.yml file. Once you have the new password encoded you can proceed to update the user row with the new password. This is how you can implement change password functionality in symfony let me know if this method worked for you too, if not, I will try to help you.  

Leave a Reply

avatar
  Subscribe  
Notify of