src/Controller/ResetPasswordController.php line 50

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\ResetPasswordRequest;
  4. use App\Entity\User;
  5. use App\Enum\SiteEnum;
  6. use App\Form\ChangePasswordFormType;
  7. use App\Form\ResetPasswordRequestFormType;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Mailer\MailerInterface;
  16. use Symfony\Component\Mime\Address;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  19. use Symfony\Contracts\Translation\TranslatorInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  21. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelper;
  23. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  24. /**
  25.  * @Route("/reset-password")
  26.  */
  27. class ResetPasswordController extends AbstractController
  28. {
  29.     use ResetPasswordControllerTrait;
  30.     private array $fromAddress = [];
  31.     public function __construct(
  32.         private ResetPasswordHelperInterface $resetPasswordHelper,
  33.         private EntityManagerInterface $entityManager,
  34.         private ParameterBagInterface $parameterBag,
  35.     ) {
  36.         if ($parameterBag->has('email_from')) {
  37.             $this->fromAddress $parameterBag->get('email_from');
  38.         }
  39.     }
  40.     /**
  41.      * Display & process form to request a password reset.
  42.      * @Route("", name="app_forgot_password_request")
  43.      */
  44.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  45.     {
  46.         $form $this->createForm(ResetPasswordRequestFormType::class);
  47.         $form->handleRequest($request);
  48.         if ($form->isSubmitted() && $form->isValid()) {
  49.             /** @var string $email */
  50.             $email $form->get('email')->getData();
  51.             return $this->processSendingPasswordResetEmail($email$mailer$translator$request);
  52.         }
  53.         return $this->render('reset_password/request.html.twig', [
  54.             'requestForm' => $form->createView(),
  55.         ]);
  56.     }
  57.     /**
  58.      * Confirmation page after a user has requested a password reset.
  59.      * @Route("/check-email", name="app_check_email")
  60.      */
  61.     public function checkEmail(): Response
  62.     {
  63.         // Generate a fake token if the user does not exist or someone hit this page directly.
  64.         // This prevents exposing whether or not a user was found with the given email address or not
  65.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  66.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  67.         }
  68.         return $this->render('reset_password/check_email.html.twig', [
  69.             'resetToken' => $resetToken,
  70.         ]);
  71.     }
  72.     /**
  73.      * Validates and process the reset URL that the user clicked in their email.
  74.      * @Route("/reset/{token}", name="app_reset_password")
  75.      */
  76.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translator, ?string $token null): Response
  77.     {
  78.         if ($token) {
  79.             // We store the token in session and remove it from the URL, to avoid the URL being
  80.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  81.             $this->storeTokenInSession($token);
  82.             return $this->redirectToRoute('app_reset_password');
  83.         }
  84.         $token $this->getTokenFromSession();
  85.         if (null === $token) {
  86.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  87.         }
  88.         try {
  89.             /** @var User $user */
  90.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  91.         } catch (ResetPasswordExceptionInterface $e) {
  92.             $this->addFlash('warning'sprintf(
  93.                 '%s - %s',
  94.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  95.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  96.             ));
  97.             return $this->redirectToRoute('app_forgot_password_request');
  98.         }
  99.         // The token is valid; allow the user to change their password.
  100.         $form $this->createForm(ChangePasswordFormType::class);
  101.         $form->handleRequest($request);
  102.         if ($form->isSubmitted() && $form->isValid()) {
  103.             // A password reset token should be used only once, remove it.
  104.             $this->resetPasswordHelper->removeResetRequest($token);
  105.             /** @var string $plainPassword */
  106.             $plainPassword $form->get('plainPassword')->getData();
  107.             // Encode(hash) the plain password, and set it.
  108.             $user->setPassword($passwordHasher->hashPassword($user$plainPassword));
  109.             $this->entityManager->flush();
  110.             // The session is cleaned up after the password has been changed.
  111.             $this->cleanSessionAfterReset();
  112.             $this->addFlash('success''reset_password.reset.success');
  113.             return $this->redirectToRoute('admin_dashboard');
  114.         }
  115.         return $this->render('reset_password/reset.html.twig', [
  116.             'resetForm' => $form->createView(),
  117.         ]);
  118.     }
  119.     private function processSendingPasswordResetEmail(
  120.         string $emailFormData,
  121.         MailerInterface $mailer,
  122.         TranslatorInterface $translator,
  123.         Request $request): RedirectResponse
  124.     {
  125.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  126.             'email' => $emailFormData,
  127.         ]);
  128.         // Do not reveal whether a user account was found or not.
  129.         if (!$user) {
  130.             return $this->redirectToRoute('app_check_email');
  131.         }
  132.         try {
  133.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  134.         } catch (ResetPasswordExceptionInterface $e) {
  135.             // If you want to tell the user why a reset email was not sent, uncomment
  136.             // the lines below and change the redirect to 'app_forgot_password_request'.
  137.             // Caution: This may reveal if a user is registered or not.
  138.             //
  139.             // $this->addFlash('reset_password_error', sprintf(
  140.             //     '%s - %s',
  141.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  142.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  143.             // ));
  144.             return $this->redirectToRoute('app_check_email');
  145.         }
  146.         $from $this->fromAddress['no_reply_'.$request->getLocale()];
  147.         $email = (new TemplatedEmail())
  148.             ->from(new Address($from$from))
  149.             ->to((string) $user->getEmail())
  150.             ->subject($translator->trans('reset_password.email.subject'))
  151.             ->htmlTemplate('reset_password/email.html.twig')
  152.             ->context([
  153.                 'resetToken' => $resetToken,
  154.             ])
  155.         ;
  156.         if (SiteEnum::SITE_STR_ES !== $request->getLocale() && array_key_exists($request->getLocale(), SiteEnum::getReversedLanguages())) {
  157.             $email->getHeaders()->addTextHeader('X-Transport'$request->getLocale());
  158.         }
  159.         $mailer->send($email);
  160.         // Store the token object in session for retrieval in check-email route.
  161.         $this->setTokenObjectInSession($resetToken);
  162.         return $this->redirectToRoute('app_check_email');
  163.     }
  164. }