src/Controller/ResetPasswordController.php line 38

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 Symfony\Bridge\Twig\Mime\TemplatedEmail;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Mailer\MailerInterface;
  12. use Symfony\Component\Mime\Address;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  16. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  18. #[Route('/reset_password')]
  19. class ResetPasswordController extends AbstractController
  20. {
  21. use ResetPasswordControllerTrait;
  22. private $resetPasswordHelper;
  23. public function __construct(ResetPasswordHelperInterface $resetPasswordHelper)
  24. {
  25. $this->resetPasswordHelper = $resetPasswordHelper;
  26. }
  27. /**
  28. * Display & process form to request a password reset.
  29. */
  30. #[Route('', name: 'app_forgot_password_request')]
  31. public function request(Request $request, MailerInterface $mailer): Response
  32. {
  33. $form = $this->createForm(ResetPasswordRequestFormType::class);
  34. $form->handleRequest($request);
  35. if ($form->isSubmitted() && $form->isValid()) {
  36. return $this->processSendingPasswordResetEmail(
  37. $form->get('email')->getData(),
  38. $mailer
  39. );
  40. }
  41. return $this->render('reset_password/request.html.twig', [
  42. 'requestForm' => $form->createView(),
  43. ]);
  44. }
  45. /**
  46. * Confirmation page after a user has requested a password reset.
  47. */
  48. #[Route('/check-email', name: 'app_check_email')]
  49. public function checkEmail(): Response
  50. {
  51. // Generate a fake token if the user does not exist or someone hit this page directly.
  52. // This prevents exposing whether or not a user was found with the given email address or not
  53. if (null === ($resetToken = $this->getTokenObjectFromSession())) {
  54. $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  55. }
  56. return $this->render('reset_password/check_email.html.twig', [
  57. 'resetToken' => $resetToken,
  58. ]);
  59. }
  60. /**
  61. * Validates and process the reset URL that the user clicked in their email.
  62. */
  63. #[Route('/reset/{token}', name: 'app_reset_password')]
  64. public function reset(Request $request, UserPasswordHasherInterface $passwordHasher, string $token = null): Response
  65. {
  66. if ($token) {
  67. // We store the token in session and remove it from the URL, to avoid the URL being
  68. // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  69. $this->storeTokenInSession($token);
  70. return $this->redirectToRoute('app_reset_password');
  71. }
  72. $token = $this->getTokenFromSession();
  73. if (null === $token) {
  74. throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  75. }
  76. try {
  77. $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  78. } catch (ResetPasswordExceptionInterface $e) {
  79. $this->addFlash('reset_password_error', sprintf(
  80. 'There was a problem validating your reset request - %s',
  81. $e->getReason()
  82. ));
  83. return $this->redirectToRoute('app_forgot_password_request');
  84. }
  85. // The token is valid; allow the user to change their password.
  86. $form = $this->createForm(ChangePasswordFormType::class);
  87. $form->handleRequest($request);
  88. if ($form->isSubmitted() && $form->isValid()) {
  89. // A password reset token should be used only once, remove it.
  90. $this->resetPasswordHelper->removeResetRequest($token);
  91. // Encode the plain password, and set it.
  92. $hashedPassword = $passwordHasher->hashPassword( // encodePassword
  93. $user,
  94. $form->get('plainPassword')->getData()
  95. );
  96. $user->setPassword($hashedPassword);
  97. $this->getDoctrine()->getManager()->flush();
  98. // The session is cleaned up after the password has been changed.
  99. $this->cleanSessionAfterReset();
  100. return $this->redirectToRoute('successpage');
  101. }
  102. return $this->render('reset_password/reset.html.twig', [
  103. 'resetForm' => $form->createView(),
  104. ]);
  105. }
  106. #[Route('/success', name: 'successpage')]
  107. public function successPassword(): Response
  108. {
  109. // Generate a fake token if the user does not exist or someone hit this page directly.
  110. // This prevents exposing whether or not a user was found with the given email address or not
  111. if (null === ($resetToken = $this->getTokenObjectFromSession())) {
  112. $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  113. }
  114. return $this->render('reset_password/success.html.twig', [
  115. 'resetToken' => $resetToken,
  116. ]);
  117. }
  118. private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer): RedirectResponse
  119. {
  120. $user = $this->getDoctrine()->getRepository(User::class)->findOneBy([
  121. 'email' => $emailFormData,
  122. ]);
  123. // Do not reveal whether a user account was found or not.
  124. if (!$user) {
  125. return $this->redirectToRoute('app_check_email');
  126. }
  127. try {
  128. $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  129. } catch (ResetPasswordExceptionInterface $e) {
  130. // If you want to tell the user why a reset email was not sent, uncomment
  131. // the lines below and change the redirect to 'app_forgot_password_request'.
  132. // Caution: This may reveal if a user is registered or not.
  133. //
  134. // $this->addFlash('reset_password_error', sprintf(
  135. // 'There was a problem handling your password reset request - %s',
  136. // $e->getReason()
  137. // ));
  138. return $this->redirectToRoute('app_check_email');
  139. }
  140. $email = (new TemplatedEmail())
  141. ->from(new Address('platzhalter@k-zwoelf.com', 'K12 Backup'))
  142. ->to($user->getEmail())
  143. ->subject('Buchungstool Platzhalter – Passwort zurücksetzen')
  144. ->htmlTemplate('reset_password/email.html.twig')
  145. ->context([
  146. 'resetToken' => $resetToken,
  147. ]);
  148. $mailer->send($email);
  149. // Store the token object in session for retrieval in check-email route.
  150. $this->setTokenObjectInSession($resetToken);
  151. return $this->redirectToRoute('app_check_email');
  152. }
  153. }