src/Controller/ResetPasswordController.php line 67

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\Exception\TransportExceptionInterface;
  13. use Symfony\Component\Mailer\MailerInterface;
  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. #[Route('/reset-password')]
  22. class ResetPasswordController extends AbstractController
  23. {
  24.     use ResetPasswordControllerTrait;
  25.     private ResetPasswordHelperInterface $resetPasswordHelper;
  26.     private EntityManagerInterface $entityManager;
  27.     /**
  28.      * @param ResetPasswordHelperInterface $resetPasswordHelper
  29.      * @param EntityManagerInterface $entityManager
  30.      */
  31.     public function __construct(
  32.         ResetPasswordHelperInterface $resetPasswordHelper,
  33.         EntityManagerInterface $entityManager
  34.     ) {
  35.         $this->resetPasswordHelper $resetPasswordHelper;
  36.         $this->entityManager $entityManager;
  37.     }
  38.     /**
  39.      * Display & process form to request a password reset.
  40.      * @param Request $request
  41.      * @param MailerInterface $mailer
  42.      * @param TranslatorInterface $translator
  43.      * @return Response
  44.      * @throws TransportExceptionInterface
  45.      */
  46.     #[Route('/'name'app_forgot_password_request')]
  47.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  48.     {
  49.         $form $this->createForm(ResetPasswordRequestFormType::class);
  50.         $form->handleRequest($request);
  51.         if ($form->isSubmitted() && $form->isValid()) {
  52.             return $this->processSendingPasswordResetEmail(
  53.                 $form->get('email')->getData(),
  54.                 $mailer,
  55.                 $translator
  56.             );
  57.         }
  58.         return $this->render('reset_password/request.html.twig', [
  59.             'requestForm' => $form->createView(),
  60.         ]);
  61.     }
  62.     /**
  63.      * Confirmation page after a user has requested a password reset.
  64.      */
  65.     #[Route('/check-email'name'app_check_email')]
  66.     public function checkEmail(): Response
  67.     {
  68.         // Generate a fake token if the user does not exist or someone hit this page directly.
  69.         // This prevents exposing whether or not a user was found with the given email address or not
  70.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  71.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  72.         }
  73.         return $this->render('reset_password/check_email.html.twig', [
  74.             'resetToken' => $resetToken,
  75.         ]);
  76.     }
  77.     /**
  78.      * Validates and process the reset URL that the user clicked in their email.
  79.      */
  80.     #[Route('/reset/{token}'name'app_reset_password')]
  81.     public function reset(
  82.         Request $request,
  83.         UserPasswordHasherInterface $userPasswordHasher,
  84.         TranslatorInterface $translator,
  85.         string $token null
  86.     ): Response {
  87.         if ($token) {
  88.             // We store the token in session and remove it from the URL, to avoid the URL being
  89.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  90.             $this->storeTokenInSession($token);
  91.             return $this->redirectToRoute('app_reset_password');
  92.         }
  93.         $token $this->getTokenFromSession();
  94.         if (null === $token) {
  95.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  96.         }
  97.         try {
  98.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  99.         } catch (ResetPasswordExceptionInterface $e) {
  100.             $this->addFlash('reset_password_error'sprintf(
  101.                 '%s - %s',
  102.                 $translator->trans(
  103.                     ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE,
  104.                     [],
  105.                     'ResetPasswordBundle'
  106.                 ),
  107.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  108.             ));
  109.             return $this->redirectToRoute('app_forgot_password_request');
  110.         }
  111.         // The token is valid; allow the user to change their password.
  112.         $form $this->createForm(ChangePasswordFormType::class);
  113.         $form->handleRequest($request);
  114.         if ($form->isSubmitted() && $form->isValid()) {
  115.             // A password reset token should be used only once, remove it.
  116.             $this->resetPasswordHelper->removeResetRequest($token);
  117.             // Encode(hash) the plain password, and set it.
  118.             $encodedPassword $userPasswordHasher->hashPassword(
  119.                 $user,
  120.                 $form->get('plainPassword')->getData()
  121.             );
  122.             $user->setPassword($encodedPassword);
  123.             $this->entityManager->flush();
  124.             // The session is cleaned up after the password has been changed.
  125.             $this->cleanSessionAfterReset();
  126.             return $this->redirectToRoute('login');
  127.         }
  128.         return $this->render('reset_password/reset.html.twig', [
  129.             'resetForm' => $form->createView(),
  130.         ]);
  131.     }
  132.     /**
  133.      * @param string $emailFormData
  134.      * @param MailerInterface $mailer
  135.      * @param TranslatorInterface $translator
  136.      * @return RedirectResponse
  137.      * @throws TransportExceptionInterface
  138.      */
  139.     private function processSendingPasswordResetEmail(
  140.         string $emailFormData,
  141.         MailerInterface $mailer,
  142.         TranslatorInterface $translator
  143.     ): RedirectResponse {
  144.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  145.             'email' => $emailFormData,
  146.         ]);
  147.         // Do not reveal whether a user account was found or not.
  148.         if (!$user) {
  149.             return $this->redirectToRoute('app_check_email');
  150.         }
  151.         try {
  152.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  153.         } catch (ResetPasswordExceptionInterface $e) {
  154.             return $this->redirectToRoute('app_check_email');
  155.         }
  156.         $email = (new TemplatedEmail())
  157.             ->from(new Address('[email protected]''[email protected]'))
  158.             ->to($user->getEmail())
  159.             ->subject('Vaš zahtev za resetovanje lozinke')
  160.             ->htmlTemplate('reset_password/email.html.twig')
  161.             ->context([
  162.                 'resetToken' => $resetToken,
  163.             ]);
  164.         $mailer->send($email);
  165.         // Store the token object in session for retrieval in check-email route.
  166.         $this->setTokenObjectInSession($resetToken);
  167.         return $this->redirectToRoute('app_check_email');
  168.     }
  169. }