src/Controller/ResetPasswordController.php line 57

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 App\Service\EmailService;
  7. use Doctrine\ORM\EntityManagerInterface;
  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\PasswordHasher\Hasher\UserPasswordHasherInterface;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Contracts\Translation\TranslatorInterface;
  15. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  16. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  18. /**
  19. * @Route("/reset-password")
  20. */
  21. class ResetPasswordController extends AbstractController
  22. {
  23. use ResetPasswordControllerTrait;
  24. private $resetPasswordHelper;
  25. private $entityManager;
  26. public function __construct(
  27. ResetPasswordHelperInterface $resetPasswordHelper,
  28. EntityManagerInterface $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. */
  38. public function request(Request $request, EmailService $emailService, TranslatorInterface $translator): 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. $emailService,
  46. $translator,
  47. );
  48. }
  49. return $this->render('reset_password/request.html.twig', [
  50. 'requestForm' => $form->createView(),
  51. ]);
  52. }
  53. /**
  54. * Confirmation page after a user has requested a password reset.
  55. *
  56. * @Route("/check-email", name="app_check_email")
  57. */
  58. public function checkEmail(): Response
  59. {
  60. // Generate a fake token if the user does not exist or someone hit this page directly.
  61. // This prevents exposing whether or not a user was found with the given email address or not
  62. if (null === ($resetToken = $this->getTokenObjectFromSession())) {
  63. $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  64. }
  65. return $this->render('reset_password/check_email.html.twig', [
  66. 'resetToken' => $resetToken,
  67. ]);
  68. }
  69. /**
  70. * Validates and process the reset URL that the user clicked in their email.
  71. *
  72. * @Route("/reset/{token}", name="app_reset_password")
  73. */
  74. public function reset(
  75. Request $request,
  76. UserPasswordHasherInterface $userPasswordHasher,
  77. TranslatorInterface $translator,
  78. ?string $token = null,
  79. ): Response {
  80. if ($token) {
  81. // We store the token in session and remove it from the URL, to avoid the URL being
  82. // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  83. $this->storeTokenInSession($token);
  84. return $this->redirectToRoute('app_reset_password');
  85. }
  86. $token = $this->getTokenFromSession();
  87. if (null === $token) {
  88. throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  89. }
  90. try {
  91. $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  92. } catch (ResetPasswordExceptionInterface $e) {
  93. $this->addFlash('reset_password_error', sprintf(
  94. '%s - %s',
  95. $translator->trans(
  96. ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE,
  97. [],
  98. 'ResetPasswordBundle',
  99. ),
  100. $translator->trans($e->getReason(), [], 'ResetPasswordBundle'),
  101. ));
  102. return $this->redirectToRoute('app_forgot_password_request');
  103. }
  104. // The token is valid; allow the user to change their password.
  105. $form = $this->createForm(ChangePasswordFormType::class);
  106. $form->handleRequest($request);
  107. if ($form->isSubmitted() && $form->isValid()) {
  108. // A password reset token should be used only once, remove it.
  109. $this->resetPasswordHelper->removeResetRequest($token);
  110. // Encode(hash) the plain password, and set it.
  111. $encodedPassword = $userPasswordHasher->hashPassword(
  112. $user,
  113. $form->get('plainPassword')->getData(),
  114. );
  115. $user->setPassword($encodedPassword);
  116. $this->entityManager->flush();
  117. // The session is cleaned up after the password has been changed.
  118. $this->cleanSessionAfterReset();
  119. return $this->redirectToRoute('homepage');
  120. }
  121. return $this->render('reset_password/reset.html.twig', [
  122. 'resetForm' => $form->createView(),
  123. ]);
  124. }
  125. private function processSendingPasswordResetEmail(
  126. string $emailFormData,
  127. EmailService $emailService,
  128. ): RedirectResponse {
  129. $user = $this->entityManager->getRepository(User::class)->findOneBy([
  130. 'email' => $emailFormData,
  131. ]);
  132. // Do not reveal whether a user account was found or not.
  133. if (!$user) {
  134. return $this->redirectToRoute('app_check_email');
  135. }
  136. try {
  137. $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  138. } catch (ResetPasswordExceptionInterface $e) {
  139. // If you want to tell the user why a reset email was not sent, uncomment
  140. // the lines below and change the redirect to 'app_forgot_password_request'.
  141. // Caution: This may reveal if a user is registered or not.
  142. //
  143. // $this->addFlash('reset_password_error', sprintf(
  144. // '%s - %s',
  145. // $translator->trans(
  146. // ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
  147. // [],
  148. // 'ResetPasswordBundle',
  149. // ),
  150. // $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  151. // ));
  152. return $this->redirectToRoute('app_check_email');
  153. }
  154. $emailService->resetPasswordEmail($user, $resetToken);
  155. // Store the token object in session for retrieval in check-email route.
  156. $this->setTokenObjectInSession($resetToken);
  157. return $this->redirectToRoute('app_check_email');
  158. }
  159. }