src/Controller/ResetPasswordController.php line 53

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 Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Mailer\MailerInterface;
  13. use Symfony\Component\Mime\Email;
  14. use Symfony\Component\Mime\Address;
  15. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  19. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  21. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  22. use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
  23. /**
  24.  * @Route("/reset-password")
  25.  */
  26. class ResetPasswordController extends AbstractController
  27. {
  28.     use ResetPasswordControllerTrait;
  29.     private ResetPasswordHelperInterface $resetPasswordHelper;
  30.     private EntityManagerInterface $entityManager;
  31.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  32.     {
  33.         $this->resetPasswordHelper $resetPasswordHelper;
  34.         $this->entityManager $entityManager;
  35.     }
  36.     /**
  37.      * Display & process form to request a password reset.
  38.      *
  39.      * @Route("", name="app_forgot_password_request")
  40.      */
  41.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  42.     {
  43.         
  44.         $form $this->createForm(ResetPasswordRequestFormType::class);
  45.         $form->handleRequest($request);
  46.         if ($form->isSubmitted() && $form->isValid()) {
  47.             
  48.             return $this->processSendingPasswordResetEmail(
  49.                 $form->get('email')->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_login');
  117.         }
  118.         return $this->render('reset_password/reset.html.twig', [
  119.             'resetForm' => $form->createView(),
  120.         ]);
  121.     }
  122.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  123.     {
  124.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  125.             'email' => $emailFormData,
  126.         ]);
  127.         
  128.         // Do not reveal whether a user account was found or not.
  129.         if (!$user) {
  130.             
  131.             return $this->redirectToRoute('app_check_email');
  132.         }
  133.         try {
  134.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  135.         } catch (ResetPasswordExceptionInterface $e) {
  136.             // If you want to tell the user why a reset email was not sent, uncomment
  137.             // the lines below and change the redirect to 'app_forgot_password_request'.
  138.             // Caution: This may reveal if a user is registered or not.
  139.             //
  140.             // $this->addFlash('reset_password_error', sprintf(
  141.             //     '%s - %s',
  142.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  143.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  144.             // ));
  145.             return $this->redirectToRoute('app_check_email');
  146.         }
  147.         
  148.         $email = (new TemplatedEmail())
  149.             ->from(new Address('contact@devapps.tn''Salah'))
  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.                 
  159.         // Store the token object in session for retrieval in check-email route.
  160.         $this->setTokenObjectInSession($resetToken);
  161.         return $this->redirectToRoute('app_check_email');
  162.     }
  163. }