src/Controller/ResetPasswordController.php line 47

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\Utils\Constants;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  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. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  22. use Symfony\Component\Mime\Email;
  23. /**
  24. * @Route("/reset-password")
  25. */
  26. class ResetPasswordController extends AbstractController
  27. {
  28. use ResetPasswordControllerTrait;
  29. private $resetPasswordHelper;
  30. private $entityManager;
  31. public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, EntityManagerInterface $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 $request, MailerInterface $mailer, TranslatorInterface $translator, UserPasswordHasherInterface $passwordHasher): Response
  42. {
  43. $form = $this->createForm(ResetPasswordRequestFormType::class);
  44. $form->handleRequest($request);
  45. if ($form->isSubmitted() && $form->isValid()) {
  46. return $this->processSendingPasswordResetEmail(
  47. $form->get('email')->getData(),
  48. $mailer,
  49. $translator,
  50. $passwordHasher
  51. );
  52. }
  53. return $this->render('reset_password/request.html.twig', [
  54. 'requestForm' => $form->createView(),
  55. ]);
  56. }
  57. /**
  58. * Confirmation page after a user has requested a password reset.
  59. *
  60. * @Route("/check-email", name="app_check_email")
  61. */
  62. public function checkEmail(): Response
  63. {
  64. // Generate a fake token if the user does not exist or someone hit this page directly.
  65. // This prevents exposing whether or not a user was found with the given email address or not
  66. if (null === ($resetToken = $this->getTokenObjectFromSession())) {
  67. $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  68. }
  69. return $this->render('reset_password/check_email.html.twig', [
  70. 'resetToken' => $resetToken
  71. ]);
  72. }
  73. /**
  74. * Validates and process the reset URL that the user clicked in their email.
  75. *
  76. * @Route("/reset/{token}", name="app_reset_password")
  77. */
  78. public function reset(Request $request, UserPasswordHasherInterface $userPasswordHasher, TranslatorInterface $translator, ?string $token = null): Response
  79. {
  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(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  96. $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  97. ));
  98. return $this->redirectToRoute('app_forgot_password_request');
  99. }
  100. // The token is valid; allow the user to change their password.
  101. $form = $this->createForm(ChangePasswordFormType::class);
  102. $form->handleRequest($request);
  103. if ($form->isSubmitted() && $form->isValid()) {
  104. // A password reset token should be used only once, remove it.
  105. $this->resetPasswordHelper->removeResetRequest($token);
  106. // Encode(hash) the plain password, and set it.
  107. $encodedPassword = $userPasswordHasher->hashPassword(
  108. $user,
  109. $form->get('plainPassword')->getData()
  110. );
  111. $user->setPassword($encodedPassword);
  112. $this->entityManager->flush();
  113. // The session is cleaned up after the password has been changed.
  114. $this->cleanSessionAfterReset();
  115. return $this->redirectToRoute('app_login');
  116. }
  117. return $this->render('reset_password/reset.html.twig', [
  118. 'resetForm' => $form->createView(),
  119. ]);
  120. }
  121. private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator, UserPasswordHasherInterface $passwordHasher): RedirectResponse
  122. {
  123. $user = $this->entityManager->getRepository(User::class)->findOneBy([
  124. 'email' => $emailFormData,
  125. ]);
  126. // Do not reveal whether a user account was found or not.
  127. if (!$user) {
  128. $this->addFlash(
  129. 'user_email_not_fount_notice',
  130. "L'utilisateur est introuvable!"
  131. );
  132. return $this->redirectToRoute('app_login');
  133. }
  134. if ($passwordHasher->isPasswordValid($user, Constants::VISITOR_DEFAULT_PASSWORD_PREFIX."_".$emailFormData)) {
  135. $this->addFlash(
  136. 'visitor_not_allowed_notice',
  137. "Action non permise aux visiteurs!"
  138. );
  139. return $this->redirectToRoute('app_login');
  140. }
  141. try {
  142. $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  143. } catch (ResetPasswordExceptionInterface $e) {
  144. // If you want to tell the user why a reset email was not sent, uncomment
  145. // the lines below and change the redirect to 'app_forgot_password_request'.
  146. // Caution: This may reveal if a user is registered or not.
  147. //
  148. // $this->addFlash('reset_password_error', sprintf(
  149. // '%s - %s',
  150. // $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  151. // $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  152. // ));
  153. dd($e->getMessage());
  154. return $this->redirectToRoute('app_check_email');
  155. }
  156. $email = (new TemplatedEmail())
  157. ->from(new Address($this->getParameter('cofina_sender_mail'), 'Cofina Mail Bot'))
  158. ->to($user->getEmail())
  159. ->subject('Demande de réinitialisation de mot de passe')
  160. ->htmlTemplate('reset_password/email.html.twig')
  161. ->context([
  162. 'resetToken' => $resetToken,
  163. 'baseUrl' => $_ENV['BASE_URL']
  164. ])
  165. ;
  166. try {
  167. $mailer->send($email);
  168. } catch (TransportExceptionInterface $e) {
  169. dd($e->getMessage());
  170. }
  171. // Store the token object in session for retrieval in check-email route.
  172. $this->setTokenObjectInSession($resetToken);
  173. return $this->redirectToRoute('app_check_email');
  174. }
  175. }