src/Controller/ResetPasswordController.php line 85

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Entity\Customer;
  5. use Symfony\Component\Mime\Address;
  6. use App\Form\ChangePasswordFormType;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use App\Form\ResetPasswordRequestFormType;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\Mailer\MailerInterface;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use Symfony\Contracts\Translation\TranslatorInterface;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  21. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  22. /**
  23. * @Route("/reset-password")
  24. */
  25. class ResetPasswordController extends AbstractController
  26. {
  27. use ResetPasswordControllerTrait;
  28. private ResetPasswordHelperInterface $resetPasswordHelper;
  29. private EntityManagerInterface $entityManager;
  30. public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, EntityManagerInterface $entityManager)
  31. {
  32. $this->resetPasswordHelper = $resetPasswordHelper;
  33. $this->entityManager = $entityManager;
  34. }
  35. /**
  36. * Display & process form to request a password reset.
  37. *
  38. * @Route("", name="app_forgot_password_request")
  39. */
  40. public function request(Request $request, MailerInterface $mailer): Response
  41. {
  42. $form = $this->createForm(ResetPasswordRequestFormType::class);
  43. $form->handleRequest($request);
  44. if ($form->isSubmitted() && $form->isValid()) {
  45. /** @var string $email */
  46. $email = $form->get('email')->getData();
  47. return $this->processSendingPasswordResetEmail($email, $mailer);
  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(Request $request, UserPasswordHasherInterface $userPasswordHasher, TranslatorInterface $translator, string $token = null): Response
  75. {
  76. if ($token) {
  77. // We store the token in session and remove it from the URL, to avoid the URL being
  78. // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  79. $this->storeTokenInSession($token);
  80. return $this->redirectToRoute('app_reset_password');
  81. }
  82. $token = $this->getTokenFromSession();
  83. if (null === $token) {
  84. throw $this->createNotFoundException('Ce lien a expiré.');
  85. }
  86. try {
  87. /** @var User $user */
  88. $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  89. } catch (ResetPasswordExceptionInterface $e) {
  90. $this->addFlash('reset_password_error', sprintf(
  91. '%s - %s',
  92. $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  93. $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  94. ));
  95. return $this->redirectToRoute('app_forgot_password_request');
  96. }
  97. // The token is valid; allow the user to change their password.
  98. $form = $this->createForm(ChangePasswordFormType::class);
  99. $form->handleRequest($request);
  100. if ($form->isSubmitted() && $form->isValid()) {
  101. // A password reset token should be used only once, remove it.
  102. $this->resetPasswordHelper->removeResetRequest($token);
  103. // Encode(hash) the plain password, and set it.
  104. /** @var string $plainPassword */
  105. $plainPassword = $form->get('plainPassword')->getData();
  106. $encodedPassword = $userPasswordHasher->hashPassword($user, $plainPassword);
  107. $user->setPassword($encodedPassword);
  108. $this->entityManager->flush();
  109. // The session is cleaned up after the password has been changed.
  110. $this->cleanSessionAfterReset();
  111. if (in_array('ROLE_ADMIN', $user->getRoles())) {
  112. return $this->redirectToRoute('admin_index');
  113. }
  114. if ($user instanceof Customer) {
  115. return $this->redirectToRoute('customer_dashboard', ['id' => $user->getId()]);
  116. }
  117. }
  118. return $this->render('reset_password/reset.html.twig', [
  119. 'resetForm' => $form->createView(),
  120. ]);
  121. }
  122. /**
  123. * @param string $emailFormData
  124. * @param MailerInterface $mailer
  125. * @return RedirectResponse
  126. * @throws TransportExceptionInterface
  127. */
  128. private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer): RedirectResponse
  129. {
  130. $user = $this->entityManager->getRepository(User::class)->findOneBy([
  131. 'email' => $emailFormData,
  132. ]);
  133. // Do not reveal whether a user account was found or not.
  134. if (!$user) {
  135. return $this->redirectToRoute('app_check_email');
  136. }
  137. try {
  138. $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  139. } catch (ResetPasswordExceptionInterface $e) {
  140. return $this->redirectToRoute('app_check_email');
  141. }
  142. $email = (new TemplatedEmail())
  143. ->from(new Address('no-reply@nibuco.fr', 'Livraison Nibuco'))
  144. ->to($user->getEmail())
  145. ->subject('Réinitialisation de votre mot de pass')
  146. ->htmlTemplate('reset_password/email.html.twig')
  147. ->context([
  148. 'resetToken' => $resetToken,
  149. ]);
  150. $mailer->send($email);
  151. // Store the token object in session for retrieval in check-email route.
  152. $this->setTokenObjectInSession($resetToken);
  153. return $this->redirectToRoute('app_check_email');
  154. }
  155. }