src/Controller/ResetPasswordController.php line 60

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