src/Controller/ResetPasswordController.php line 40

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Mailer\MailerInterface;
  12. use Symfony\Component\Mime\Address;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  15. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  16. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  18. use Rollerworks\Component\PasswordStrength\Validator\Constraints as RollerworksPassword;
  19. use Symfony\Component\Validator\Validator\ValidatorInterface;
  20. #[Route(path'/reset-password')]
  21. class ResetPasswordController extends AbstractController
  22. {
  23.     use ResetPasswordControllerTrait;
  24.     private $resetPasswordHelper;
  25.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper)
  26.     {
  27.         $this->resetPasswordHelper $resetPasswordHelper;
  28.     }
  29.     /**
  30.      * Display & process form to request a password reset.
  31.      */
  32.     #[Route(path''name'app_forgot_password_request')]
  33.     public function request(Request $requestMailerInterface $mailer): Response
  34.     {
  35.         $form $this->createForm(ResetPasswordRequestFormType::class);
  36.         $form->handleRequest($request);
  37.         if ($form->isSubmitted() && $form->isValid()) {
  38.             return $this->processSendingPasswordResetEmail(
  39.                 $form->get('username')->getData(),
  40.                 $mailer
  41.             );
  42.         }
  43.         return $this->render(
  44.             'reset_password/request.html.twig', [
  45.                     'requestForm' => $form->createView(),
  46.                         ]
  47.         );
  48.     }
  49.     /**
  50.      * Confirmation page after a user has requested a password reset.
  51.      */
  52.     #[Route(path'/check-email'name'app_check_email')]
  53.     public function checkEmail(): Response
  54.     {
  55.         // We prevent users from directly accessing this page
  56.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  57.             return $this->redirectToRoute('app_forgot_password_request');
  58.         }
  59.         return $this->render(
  60.             'reset_password/check_email.html.twig', [
  61.                     'resetToken' => $resetToken,
  62.                         ]
  63.         );
  64.     }
  65.     /**
  66.      * Reset after init
  67.      */
  68.     #[Route(path'/reset/changePassword'name'changepassword')]
  69.     public function changePassword(Request $requestUserPasswordEncoderInterface $passwordEncoder)
  70.     {
  71.         $user $this->getUser();
  72.         $form $this->createForm(ChangePasswordFormType::class);
  73.         $form->handleRequest($request);
  74.         if ($form->isSubmitted() && $form->isValid()) {
  75.             $plainPassword $form->get('plainPassword')->getData();
  76.             if(preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/'$plainPassword)) {
  77.                 $encodedPassword $passwordEncoder->encodePassword(
  78.                     $user,
  79.                     $form->get('plainPassword')->getData()
  80.                 );
  81.                 $user->setPassword($encodedPassword);
  82.                 $user->setForcePasswordChange(false);
  83.                 $this->getDoctrine()->getManager()->flush();
  84.                 // The session is cleaned up after the password has been changed.
  85.                 $this->cleanSessionAfterReset();
  86.                 return $this->redirectToRoute('app_login');
  87.             } else{
  88.                 //TODO: translate
  89.                 $this->addFlash('error''mot de passe trop faible');
  90.             }
  91.         }
  92.         return $this->render(
  93.             'reset_password/reset.html.twig', [
  94.                     'resetForm' => $form->createView(),
  95.                         ]
  96.         );
  97.     }
  98.     /**
  99.      * Validates and process the reset URL that the user clicked in their email.
  100.      */
  101.     #[Route(path'/reset/{token}'name'app_reset_password')]
  102.     public function reset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $token null): Response
  103.     {
  104.         if ($token) {
  105.             // We store the token in session and remove it from the URL, to avoid the URL being
  106.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  107.             $this->storeTokenInSession($token);
  108.             return $this->redirectToRoute('app_reset_password');
  109.         }
  110.         $token $this->getTokenFromSession();
  111.         if (null === $token) {
  112.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  113.         }
  114.         try {
  115.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  116.         } catch (ResetPasswordExceptionInterface $e) {
  117.             $this->addFlash(
  118.                     //TODO: translate
  119.                 'reset_password_error',
  120.                 'Problème lors de la validation du lien. Réeffectuez un demande de mot de passe.'
  121.                     
  122.                 
  123.             );
  124.             return $this->redirectToRoute('app_forgot_password_request');
  125.         }
  126.         // The token is valid; allow the user to change their password.
  127.         $form $this->createForm(ChangePasswordFormType::class);
  128.         $form->handleRequest($request);
  129.         if ($form->isSubmitted() && $form->isValid()) {
  130.             if(preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/'$form->get('plainPassword')->getData())) {
  131.                 // A password reset token should be used only once, remove it.
  132.                 $this->resetPasswordHelper->removeResetRequest($token);
  133.                 // Encode the plain password, and set it.
  134.                 $encodedPassword $passwordEncoder->encodePassword(
  135.                     $user,
  136.                     $form->get('plainPassword')->getData()
  137.                 );
  138.                 $user->setPassword($encodedPassword);
  139.                 $this->getDoctrine()->getManager()->flush();
  140.                 // The session is cleaned up after the password has been changed.
  141.                 $this->cleanSessionAfterReset();
  142.                 //TODO: translate
  143.                 $this->addFlash('success''Mot de passe mis à jour, veuillez vous connecter');
  144.                 return $this->redirectToRoute('app_login');
  145.             }else{
  146.                 $this->addFlash('error''Mot de passe incorrect');
  147.             }
  148.         }
  149.         return $this->render(
  150.             'reset_password/reset.html.twig', [
  151.                     'resetForm' => $form->createView(),
  152.                         ]
  153.         );
  154.     }
  155.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  156.     {
  157.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy(
  158.             [
  159.                     'username' => $emailFormData,
  160.                     'isActive' => true
  161.                 ]
  162.         );
  163.         // Do not reveal whether a user account was found or not.
  164.         if (!$user instanceof \App\Entity\User) {
  165.             return $this->redirectToRoute('app_check_email');
  166.         }
  167.         try {
  168.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  169.         } catch (ResetPasswordExceptionInterface $e) {
  170. //             If you want to tell the user why a reset email was not sent, uncomment
  171. //             the lines below and change the redirect to 'app_forgot_password_request'.
  172. //             Caution: This may reveal if a user is registered or not.
  173.             
  174.              $this->addFlash('reset_password_error'sprintf(
  175.                  'Une demande de réinitialisation vient d\'être faite. Vous ne pouvez en refaire une avant une heure.',
  176.                  $e->getReason()
  177.              ));
  178.             return $this->redirectToRoute('app_check_email');
  179.         }
  180.         $email = (new TemplatedEmail())
  181.             ->from(new Address($this->getParameter('emailSender')['address'],  $this->getParameter('emailSender')['adressName']))
  182.             ->to($user->getEmail())
  183.                 //TODO: titre translation
  184.             ->subject('Réinitialisation du mot de passe')
  185.             ->htmlTemplate('email/fr/requestChange.html.twig')
  186.             ->context(
  187.                 [
  188.                     'resetToken' => $resetToken,
  189.                     ]
  190.             );
  191.         $mailer->send($email);
  192.         // Store the token object in session for retrieval in check-email route.
  193.         $this->setTokenObjectInSession($resetToken);
  194.         return $this->redirectToRoute('app_check_email');
  195.     }
  196. }