src/Controller/ResetPasswordController.php line 44

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Foodtruck;
  4. use App\Entity\User;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use App\Service\FoodtruckService;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  15. use Symfony\Component\Mailer\MailerInterface;
  16. use Symfony\Component\Mime\Address;
  17. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Contracts\Translation\TranslatorInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  21. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  23. #[Route('/reset-password')]
  24. class ResetPasswordController extends AbstractController
  25. {
  26. use ResetPasswordControllerTrait;
  27. private $resetPasswordHelper;
  28. private $entityManager;
  29. public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, EntityManagerInterface $entityManager)
  30. {
  31. $this->resetPasswordHelper = $resetPasswordHelper;
  32. $this->entityManager = $entityManager;
  33. }
  34. /**
  35. * Display & process form to request a password reset.
  36. */
  37. #[Route('', name: 'app_forgot_password_request')]
  38. public function request(Request $request, MailerInterface $mailer, TranslatorInterface $translator, FoodtruckService $foodtruckService): Response
  39. {
  40. //Détection du foodtruck
  41. $foodtruck = $foodtruckService->controleFoodtruck($request);
  42. if(is_object($foodtruck))
  43. {
  44. } else {
  45. $foodtruck = new Foodtruck;
  46. }
  47. $form = $this->createForm(ResetPasswordRequestFormType::class);
  48. $form->handleRequest($request);
  49. if ($form->isSubmitted() && $form->isValid()) {
  50. return $this->processSendingPasswordResetEmail(
  51. $form->get('email')->getData(),
  52. $mailer,
  53. $translator,
  54. $foodtruck
  55. );
  56. }
  57. return $this->render('reset_password/request.html.twig', [
  58. 'requestForm' => $form->createView(),
  59. // 'foodtruck' => $foodtruck,
  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(Request $request, UserPasswordHasherInterface $passwordHasher, TranslatorInterface $translator, string $token = null): Response
  82. {
  83. if ($token) {
  84. // We store the token in session and remove it from the URL, to avoid the URL being
  85. // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  86. $this->storeTokenInSession($token);
  87. return $this->redirectToRoute('app_reset_password');
  88. }
  89. $token = $this->getTokenFromSession();
  90. if (null === $token) {
  91. throw $this->createNotFoundException('Aucun token de changement de mot de passe trouvé dans l\'URL ou dans la session.');
  92. }
  93. try {
  94. $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  95. } catch (ResetPasswordExceptionInterface $e) {
  96. $this->addFlash('reset_password_error', sprintf(
  97. '%s - %s',
  98. $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  99. $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  100. ));
  101. return $this->redirectToRoute('app_forgot_password_request');
  102. }
  103. // The token is valid; allow the user to change their password.
  104. $form = $this->createForm(ChangePasswordFormType::class);
  105. $form->handleRequest($request);
  106. if ($form->isSubmitted() && $form->isValid()) {
  107. // A password reset token should be used only once, remove it.
  108. $this->resetPasswordHelper->removeResetRequest($token);
  109. // Encode(hash) the plain password, and set it.
  110. $encodedPassword = $passwordHasher->hashPassword(
  111. $user,
  112. $form->get('plainPassword')->getData()
  113. );
  114. $user->setPassword($encodedPassword);
  115. $this->entityManager->flush();
  116. // The session is cleaned up after the password has been changed.
  117. $this->cleanSessionAfterReset();
  118. return $this->redirectToRoute('app_login');
  119. }
  120. return $this->render('reset_password/reset.html.twig', [
  121. 'resetForm' => $form->createView(),
  122. ]);
  123. }
  124. private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator, Foodtruck $foodtruck): RedirectResponse
  125. {
  126. $user = $this->entityManager->getRepository(User::class)->findOneBy([
  127. 'email' => $emailFormData,
  128. ]);
  129. // Do not reveal whether a user account was found or not.
  130. if (!$user) {
  131. return $this->redirectToRoute('app_check_email');
  132. }
  133. try {
  134. $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  135. } catch (ResetPasswordExceptionInterface $e) {
  136. // If you want to tell the user why a reset email was not sent, uncomment
  137. // the lines below and change the redirect to 'app_forgot_password_request'.
  138. // Caution: This may reveal if a user is registered or not.
  139. //
  140. // $this->addFlash('reset_password_error', sprintf(
  141. // '%s - %s',
  142. // $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  143. // $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  144. // ));
  145. return $this->redirectToRoute('app_check_email');
  146. }
  147. $email = (new TemplatedEmail())
  148. ->from(new Address($this->getParameter('MAILER_FROM_ADDRESS'), 'FSM Security'))
  149. ->to($user->getEmail())
  150. ->subject('Demande de réinitialisation de votre mot de passe pour accéder au foodtruck '.$foodtruck->getLibelle().'')
  151. ->htmlTemplate('reset_password/email.html.twig')
  152. ->context([
  153. 'resetToken' => $resetToken,
  154. 'foodtruck' => $foodtruck,
  155. ])
  156. ;
  157. $mailer->send($email);
  158. // Store the token object in session for retrieval in check-email route.
  159. $this->setTokenObjectInSession($resetToken);
  160. return $this->redirectToRoute('app_check_email');
  161. }
  162. }