Symfony 4 - Reset password

Symfony 4 - Reset password

Créons un reset password pour notre projet Symfony 4 afin de pouvoir changer son mot de passe directement sur son compte

 

App\Controller\AccountController.php

<?php

use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Form\FormError;

use App\Form\ProfileType;

use App\Entity\User;

public function editAction(Request $request)

    {

    	$em = $this->getDoctrine()->getManager();

        $user = $this->getUser();

    	$form = $this->createForm(ResetPasswordType::class, $user);

    	$form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $passwordEncoder = $this->get('security.password_encoder');

            $oldPassword = $request->request->get('etiquettebundle_user')['oldPassword'];

            // Si l'ancien mot de passe est bon

            if ($passwordEncoder->isPasswordValid($user, $oldPassword)) {

                $newEncodedPassword = $passwordEncoder->encodePassword($user, $user->getPlainPassword());

                $user->setPassword($newEncodedPassword);

                

                $em->persist($user);

                $em->flush();

                $this->addFlash('notice', 'Votre mot de passe à bien été changé !');

                return $this->redirectToRoute('profile');

            } else {

                $form->addError(new FormError('Ancien mot de passe incorrect'));

            }

        }

    	

    	return $this->render('account/edit.html.twig', array(

    		'form' => $form->createView(),

    	));

    }

 

In my Form type

App\Form\AccountType.php

use Symfony\Component\Form\Extension\Core\Type\PasswordType;

use Symfony\Component\Form\Extension\Core\Type\RepeatedType;

use Symfony\Component\Form\Extension\Core\Type\SubmitType;


        $builder

            ->add('oldPassword', PasswordType::class, array(

                'mapped' => false

            ))

            ->add('plainPassword', RepeatedType::class, array(

                'type' => PasswordType::class,

                'invalid_message' => 'Les deux mots de passe doivent être identiques',

                'options' => array(

                    'attr' => array(

                        'class' => 'password-field'

                    )

                ),

                'required' => true,

            ))

            ->add('submit', SubmitType::class, array(

                'attr' => array(

                    'class' => 'btn btn-primary btn-block'

                )

            ))

        ;

 

21/08/2020