src/Controller/ResetPasswordController.php line 42

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 Symfony\Contracts\Translation\TranslatorInterface;
  19. /**
  20.  * @Route("/reset-password")
  21.  */
  22. class ResetPasswordController extends AbstractController {
  23.     use ResetPasswordControllerTrait;
  24.     private $resetPasswordHelper;
  25.     private $translator;
  26.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperTranslatorInterface $translator) {
  27.         $this->resetPasswordHelper $resetPasswordHelper;
  28.         $this->translator $translator;
  29.     }
  30.     /**
  31.      * Display & process form to request a password reset.
  32.      *
  33.      * @Route("", name="app_forgot_password_request")
  34.      */
  35.     public function request(Request $requestMailerInterface $mailer): Response {
  36.         $form $this->createForm(ResetPasswordRequestFormType::class);
  37.         $form->handleRequest($request);
  38.         if ($form->isSubmitted() && $form->isValid()) {
  39.             return $this->processSendingPasswordResetEmail(
  40.                             $form->get('email')->getData(),
  41.                             $mailer
  42.             );
  43.         }
  44.         return $this->render('reset_password/request.html.twig', [
  45.                     'requestForm' => $form->createView(),
  46.         ]);
  47.     }
  48.     /**
  49.      * Confirmation page after a user has requested a password reset.
  50.      *
  51.      * @Route("/check-email", name="app_check_email")
  52.      */
  53.     public function checkEmail(): Response {
  54.         // We prevent users from directly accessing this page
  55.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  56.             return $this->redirectToRoute('app_forgot_password_request');
  57.         }
  58.         return $this->render('reset_password/check_email.html.twig', [
  59.                     'resetToken' => $resetToken,
  60.         ]);
  61.     }
  62.     /**
  63.      * Validates and process the reset URL that the user clicked in their email.
  64.      *
  65.      * @Route("/reset/{token}", name="app_reset_password")
  66.      */
  67.     public function reset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $token null): Response {
  68.         if ($token) {
  69.             $this->storeTokenInSession($token);
  70.             return $this->redirectToRoute('app_reset_password');
  71.         }
  72.         $token $this->getTokenFromSession();
  73.         if (null === $token) {
  74.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  75.         }
  76.         try {
  77.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  78.         } catch (ResetPasswordExceptionInterface $e) {
  79.             $this->addFlash('reset_password_error'sprintf(
  80.                             'There was a problem validating your reset request - %s',
  81.                             $e->getReason()
  82.             ));
  83.             return $this->redirectToRoute('app_forgot_password_request');
  84.         }
  85.         $form $this->createForm(ChangePasswordFormType::class);
  86.         $form->handleRequest($request);
  87.         if ($form->isSubmitted() && $form->isValid()) {
  88.             $this->resetPasswordHelper->removeResetRequest($token);
  89.             $encodedPassword $passwordEncoder->encodePassword(
  90.                     $user,
  91.                     $form->get('plainPassword')->getData()
  92.             );
  93.             $user->setPassword($encodedPassword);
  94.             $this->getDoctrine()->getManager()->flush();
  95.             $this->cleanSessionAfterReset();
  96.             return $this->redirectToRoute('app_home');
  97.         }
  98.         return $this->render('reset_password/reset.html.twig', [
  99.                     'resetForm' => $form->createView(),
  100.         ]);
  101.     }
  102.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse {
  103.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  104.             'email' => $emailFormData,
  105.         ]);
  106.         if (!$user) {
  107.             return $this->redirectToRoute('app_check_email');
  108.         }
  109.         try {
  110.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  111.         } catch (ResetPasswordExceptionInterface $e) {
  112.             return $this->redirectToRoute('app_check_email');
  113.         }
  114.         $email = (new TemplatedEmail())
  115.                 ->from(new Address('[email protected]'$this->translator->trans('FLANNERY_MAIL_BOT')))
  116.                 ->to($user->getEmail())
  117.                 ->subject($this->translator->trans('YOUR_PASSWORD_RESET_REQUEST'))
  118.                 ->htmlTemplate('reset_password/email.html.twig')
  119.                 ->context([
  120.             'resetToken' => $resetToken,
  121.                 ])
  122.         ;
  123.         $mailer->send($email);
  124.         $this->setTokenObjectInSession($resetToken);
  125.         return $this->redirectToRoute('app_check_email');
  126.     }
  127. }