src/Controller/ResetPasswordController.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Users;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Psr\Log\LoggerInterface;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  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. /**
  23.  * @Route("/reset-password")
  24.  */
  25. class ResetPasswordController extends AbstractController
  26. {
  27.     use ResetPasswordControllerTrait;
  28.     private ResetPasswordHelperInterface $resetPasswordHelper;
  29.     private EntityManagerInterface $entityManager;
  30.     private LoggerInterface $logger;
  31.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerLoggerInterface $logger)
  32.     {
  33.         $this->resetPasswordHelper $resetPasswordHelper;
  34.         $this->entityManager $entityManager;
  35.         $this->logger $logger;
  36.     }
  37.     /**
  38.      * Display & process form to request a password reset.
  39.      *
  40.      * @Route("", name="app_forgot_password_request")
  41.      * @throws TransportExceptionInterface
  42.      */
  43.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  44.     {
  45.         $form $this->createForm(ResetPasswordRequestFormType::class);
  46.         $form->handleRequest($request);
  47.         if ($form->isSubmitted() && $form->isValid()) {
  48.             return $this->processSendingPasswordResetEmail(
  49.                 $form->get('mail')->getData(),
  50.                 $mailer,
  51.                 $translator
  52.             );
  53.         }
  54.         return $this->render('reset_password/request.html.twig', [
  55.             'requestForm' => $form->createView(),
  56.         ]);
  57.     }
  58.     /**
  59.      * Confirmation page after a user has requested a password reset.
  60.      *
  61.      * @Route("/check-email", name="app_check_email")
  62.      */
  63.     public function checkEmail(): Response
  64.     {
  65.         // Generate a fake token if the user does not exist or someone hit this page directly.
  66.         // This prevents exposing whether or not a user was found with the given email address or not
  67.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  68.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  69.         }
  70.         return $this->render('reset_password/check_email.html.twig', [
  71.             'resetToken' => $resetToken,
  72.         ]);
  73.     }
  74.     /**
  75.      * Validates and process the reset URL that the user clicked in their email.
  76.      *
  77.      * @Route("/reset/{token}", name="app_reset_password")
  78.      */
  79.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  80.     {
  81.         if ($token) {
  82.             // We store the token in session and remove it from the URL, to avoid the URL being
  83.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  84.             $this->storeTokenInSession($token);
  85.             return $this->redirectToRoute('app_reset_password');
  86.         }
  87.         $token $this->getTokenFromSession();
  88.         if (null === $token) {
  89.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  90.         }
  91.         try {
  92.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  93.         } catch (ResetPasswordExceptionInterface $e) {
  94.             $this->addFlash('reset_password_error'sprintf(
  95.                 '%s - %s',
  96.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  97.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  98.             ));
  99.             return $this->redirectToRoute('app_forgot_password_request');
  100.         }
  101.         // The token is valid; allow the user to change their password.
  102.         $form $this->createForm(ChangePasswordFormType::class);
  103.         $form->handleRequest($request);
  104.         if ($form->isSubmitted() && $form->isValid()) {
  105.             // A password reset token should be used only once, remove it.
  106.             $this->resetPasswordHelper->removeResetRequest($token);
  107.             // Encode(hash) the plain password, and set it.
  108.             $encodedPassword $userPasswordHasher->hashPassword(
  109.                 $user,
  110.                 $form->get('plainPassword')->getData()
  111.             );
  112.             $user->setPassword($encodedPassword);
  113.             $this->entityManager->flush();
  114.             // The session is cleaned up after the password has been changed.
  115.             $this->cleanSessionAfterReset();
  116.             return $this->redirectToRoute('app_core_homepage');
  117.         }
  118.         return $this->render('reset_password/reset.html.twig', [
  119.             'resetForm' => $form->createView(),
  120.         ]);
  121.     }
  122.     /**
  123.      * @throws TransportExceptionInterface
  124.      */
  125.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  126.     {
  127.         $user $this->entityManager->getRepository(Users::class)->findOneBy([
  128.             'mail' => $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($this->getParameter('mailFrom'), 'Contact Mokanda'))
  150.             ->to($user->getMail())
  151.             ->subject('Your password reset request')
  152.             ->htmlTemplate('reset_password/email.html.twig')
  153.             ->context([
  154.                 'resetToken' => $resetToken,
  155.             ]);
  156.         try {
  157.             $mailer->send($email);
  158.             $this->logger->info("mail sent");
  159.         } catch (TransportExceptionInterface $exception){
  160.             $this->logger->info("Sending mail error ", [$exception->getMessage()]);
  161.         }
  162.         // Store the token object in session for retrieval in check-email route.
  163.         $this->setTokenObjectInSession($resetToken);
  164.         return $this->redirectToRoute('app_check_email');
  165.     }
  166. }