src/Controller/ResetPasswordController.php line 54

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\UserType;
  5. use App\Service\EmailManager;
  6. use Symfony\Component\Mime\Address;
  7. use App\Form\ChangePasswordFormType;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use App\Form\ResetPasswordRequestFormType;
  10. use App\Repository\UserRepository;
  11. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\Mailer\MailerInterface;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\HttpFoundation\RedirectResponse;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  21. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  22. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  23. /**
  24.  * @Route("/reinitialiser-mot-de-passe")
  25.  */
  26. class ResetPasswordController extends AbstractController
  27. {
  28.     use ResetPasswordControllerTrait;
  29.     private ResetPasswordHelperInterface $resetPasswordHelper;
  30.     private EntityManagerInterface $entityManager;
  31.     private EmailManager $emailManager;
  32.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerEmailManager $emailManager)
  33.     {
  34.         $this->resetPasswordHelper $resetPasswordHelper;
  35.         $this->entityManager $entityManager;
  36.         $this->emailManager $emailManager;
  37.     }
  38.     /**
  39.      * Display & process form to request a password reset.
  40.      * @param  mixed $request
  41.      * @param  mixed $mailer
  42.      * @param  mixed $translator
  43.      * @param  mixed $userRepository
  44.      * @return Response
  45.      *
  46.      * @Route("", name="app_forgot_password_request", methods={"GET","POST"})
  47.      */
  48.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translatorUserRepository $userRepository): Response
  49.     {
  50.         //$form = $this->createForm(ResetPasswordRequestFormType::class);
  51.         $form $this->createForm(UserType::class, null, [
  52.             'emailReset' => true,
  53.         ]);
  54.         $form->handleRequest($request);
  55.         if ($form->isSubmitted() && $form->isValid()) {
  56.             $user $userRepository->findOneBy(['email' => $form->get('emailReset')->getData()]);
  57.             if (!$user) {
  58.                 $this->addFlash('error''Cet email n\'est pas associé à un compte');
  59.             } else {
  60.                 if ($user->getProvider() != 'email') {
  61.                     $this->addFlash('error''Votre compte a été créé par google');
  62.                 } else {
  63.                     return $this->processSendingPasswordResetEmail(
  64.                         $form->get('emailReset')->getData(),
  65.                         $mailer,
  66.                         $translator
  67.                     );
  68.                 }
  69.             }
  70.         }
  71.         return $this->render('reset_password/request.html.twig', [
  72.             'form' => $form->createView(),
  73.         ]);
  74.     }
  75.     /**
  76.      * Confirmation page after a user has requested a password reset.
  77.      * @return Response
  78.      * @Route("/verification-email", name="app_check_email", methods={"GET","POST"})
  79.      */
  80.     public function checkEmail(): Response
  81.     {
  82.         // Generate a fake token if the user does not exist or someone hit this page directly.
  83.         // This prevents exposing whether or not a user was found with the given email address or not
  84.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  85.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  86.         }
  87.         return $this->render('reset_password/check_email.html.twig', [
  88.             'resetToken' => $resetToken,
  89.         ]);
  90.     }
  91.     /**
  92.      * Validates and process the reset URL that the user clicked in their email.
  93.      * @param  mixed $request
  94.      * @param  mixed $userPasswordHasher
  95.      * @param  mixed $translator
  96.      * @param  mixed $token
  97.      * @return Response
  98.      * @Route("/confirmer/{token}", name="app_reset_password", methods={"GET","POST"})
  99.      */
  100.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  101.     {
  102.         if ($token) {
  103.             // We store the token in session and remove it from the URL, to avoid the URL being
  104.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  105.             $this->storeTokenInSession($token);
  106.             return $this->redirectToRoute('app_reset_password');
  107.         }
  108.         $token $this->getTokenFromSession();
  109.         if (null === $token) {
  110.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  111.         }
  112.         try {
  113.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  114.         } catch (ResetPasswordExceptionInterface $e) {
  115.             $this->addFlash('reset_password_error'sprintf(
  116.                 '%s - %s',
  117.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  118.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  119.             ));
  120.             return $this->redirectToRoute('app_forgot_password_request');
  121.         }
  122.         // The token is valid; allow the user to change their password.
  123.         $form $this->createForm(UserType::class, null, [
  124.             'password' => true,
  125.         ]);
  126.         $form->handleRequest($request);
  127.         if ($form->isSubmitted() && $form->isValid()) {
  128.             // A password reset token should be used only once, remove it.
  129.             $this->resetPasswordHelper->removeResetRequest($token);
  130.             // Encode(hash) the plain password, and set it.
  131.             $encodedPassword $userPasswordHasher->hashPassword(
  132.                 $user,
  133.                 $form->get('password')->getData()
  134.             );
  135.             $user->setPassword($encodedPassword);
  136.             $this->entityManager->flush();
  137.             // The session is cleaned up after the password has been changed.
  138.             $this->cleanSessionAfterReset();
  139.             $this->addFlash('success''Votre mot de passe a bien été réinitialisé');
  140.             return $this->redirectToRoute('app_login');
  141.         }
  142.         return $this->render('reset_password/reset.html.twig', [
  143.             'form' => $form->createView(),
  144.         ]);
  145.     }
  146.     
  147.     /**
  148.      * processSendingPasswordResetEmail
  149.      *
  150.      * @param  mixed $emailFormData
  151.      * @param  mixed $mailer
  152.      * @param  mixed $translator
  153.      * @return RedirectResponse
  154.      */
  155.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  156.     {
  157.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  158.             'email' => $emailFormData,
  159.         ]);
  160.         // Do not reveal whether a user account was found or not.
  161.         if (!$user) {
  162.             return $this->redirectToRoute('app_check_email');
  163.         }
  164.         try {
  165.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  166.         } catch (ResetPasswordExceptionInterface $e) {
  167.             // If you want to tell the user why a reset email was not sent, uncomment
  168.             // the lines below and change the redirect to 'app_forgot_password_request'.
  169.             // Caution: This may reveal if a user is registered or not.
  170.             //
  171.             // $this->addFlash('reset_password_error', sprintf(
  172.             //     '%s - %s',
  173.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  174.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  175.             // ));
  176.             return $this->redirectToRoute('app_check_email');
  177.         }
  178.         $subject 'Réinitialiser votre mot de passe';
  179.         $template 'reset_password.html.twig';
  180.         $data = [
  181.             'resetToken' => $resetToken,
  182.             'user' => $user,
  183.         ];
  184.         $this->emailManager->getSendMail($user$subject$template$data);
  185.         // Store the token object in session for retrieval in check-email route.
  186.         $this->setTokenObjectInSession($resetToken);
  187.         return $this->redirectToRoute('app_check_email');
  188.     }
  189. }