src/Controller/ResetPasswordController.php line 48

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\MailerService;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Psr\Log\LoggerInterface;
  9. use App\Controller\base\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\Routing\Annotation\Route;
  15. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. /**
  21. * @Route("/reset-password")
  22. */
  23. class ResetPasswordController extends AbstractController
  24. {
  25. use ResetPasswordControllerTrait;
  26. private $resetPasswordHelper;
  27. private $entityManager;
  28. private $mailerService;
  29. private $logger;
  30. public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, EntityManagerInterface $entityManager, MailerService $mailerService, LoggerInterface $logger)
  31. {
  32. $this->resetPasswordHelper = $resetPasswordHelper;
  33. $this->entityManager = $entityManager;
  34. $this->mailerService = $mailerService;
  35. $this->logger = $logger;
  36. }
  37. /**
  38. * Display & process form to request a password reset.
  39. *
  40. * @Route("", name="app_forgot_password_request")
  41. */
  42. public function request(Request $request, MailerInterface $mailer, TranslatorInterface $translator): Response
  43. {
  44. $form = $this->createForm(ResetPasswordRequestFormType::class);
  45. $form->handleRequest($request);
  46. if ($form->isSubmitted() && $form->isValid()) {
  47. $inputValue = $form->get('username')->getData();
  48. $fieldName = filter_var($inputValue, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
  49. return $this->processSendingPasswordResetEmail(
  50. $fieldName,
  51. $form->get('username')->getData(),
  52. $mailer,
  53. $translator,
  54. $request
  55. );
  56. }
  57. return $this->render('reset_password/request.html.twig', [
  58. 'requestForm' => $form->createView(),
  59. ]);
  60. }
  61. /**
  62. * Confirmation page after a user has requested a password reset.
  63. *
  64. * @Route("/check-email", name="app_check_email")
  65. */
  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. */
  82. public function reset(Request $request, UserPasswordHasherInterface $userPasswordEncoder, TranslatorInterface $translator, string $token = null): Response
  83. {
  84. if ($token) {
  85. // We store the token in session and remove it from the URL, to avoid the URL being
  86. // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  87. $this->storeTokenInSession($token);
  88. return $this->redirectToRoute('app_reset_password');
  89. }
  90. $token = $this->getTokenFromSession();
  91. if (null === $token) {
  92. throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  93. }
  94. try {
  95. $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  96. } catch (ResetPasswordExceptionInterface $e) {
  97. $this->addFlash('reset_password_error', sprintf(
  98. '%s - %s',
  99. $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  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 = $userPasswordEncoder->hashPassword(
  112. $user,
  113. $form->get('plainPassword')->getData()
  114. );
  115. $user->setPassword($encodedPassword);
  116. $user->setLastLogin(new \DateTime('now', new \DateTimeZone('America/New_York')));
  117. $hatchManager = $this->getDoctrine()->getManager();
  118. $hatchManager->persist($user);
  119. $hatchManager->flush();
  120. // The session is cleaned up after the password has been changed.
  121. $this->cleanSessionAfterReset();
  122. $this->addFlash('success', 'Password successfully updated!');
  123. return $this->redirectToRoute('app_login');
  124. }
  125. return $this->render('reset_password/reset.html.twig', [
  126. 'resetForm' => $form->createView(),
  127. ]);
  128. }
  129. private function processSendingPasswordResetEmail(string $fieldName, string $fieldData, MailerInterface $mailer, TranslatorInterface $translator, Request $request): RedirectResponse
  130. {
  131. /** @var User $user */
  132. $user = $this->entityManager->getRepository(User::class)->findOneBy([
  133. $fieldName => $fieldData,
  134. ]);
  135. // Do not reveal whether a user account was found or not.
  136. if (!$user) {
  137. return $this->redirectToRoute('app_check_email');
  138. }
  139. try {
  140. $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  141. } catch (ResetPasswordExceptionInterface $e) {
  142. $this->logger->error($e->getMessage());
  143. $this->logger->error($e->getTraceAsString());
  144. return $this->redirectToRoute('app_check_email');
  145. }
  146. try {
  147. $locationId = $user->getDefaultLocation() ? $user->getDefaultLocation()->getId() : $user->getActiveLocations()->first()->getId();
  148. $this->mailerService
  149. ->setSubject('Kipu Compliance: Reset password request')
  150. ->setTo($user->getEmail(), $user->getUsername())
  151. ->setContext([
  152. 'resetToken' => $resetToken,
  153. ])
  154. ->setHtmlTemplate('emails/reset_password.html.twig')
  155. ->setLocationId($locationId)
  156. ->setEmailRecipient($user)
  157. ->send();
  158. $this->logger->info('Reset password email sent: ' . $user->getEmail());
  159. // Store the token object in session for retrieval in check-email route.
  160. $this->setTokenObjectInSession($resetToken);
  161. } catch (\Exception $e) {
  162. $this->logger->error($e->getMessage());
  163. $this->logger->error($e->getTraceAsString());
  164. }
  165. return $this->redirectToRoute('app_check_email');
  166. }
  167. }