src/UserBundle/Controller/ResetPasswordController.php line 51

Open in your IDE?
  1. <?php
  2. namespace App\UserBundle\Controller;
  3. use App\BaseBundle\Controller\AbstractController;
  4. use App\BaseBundle\SystemConfiguration;
  5. use App\CMSBundle\Service\SiteSettingService;
  6. use App\UserBundle\Entity\User;
  7. use App\UserBundle\Form\ChangePasswordFormType;
  8. use App\UserBundle\Form\ResetPasswordRequestFormType;
  9. use App\UserBundle\Security\CustomAuthenticator;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  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\Component\Security\Http\Authentication\UserAuthenticatorInterface;
  20. use Symfony\Component\Security\Http\FirewallMapInterface;
  21. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  22. use Symfony\Contracts\Translation\TranslatorInterface;
  23. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  24. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  25. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  26. /**
  27. * @Route("/reset-password")
  28. */
  29. class ResetPasswordController extends AbstractController
  30. {
  31. use ResetPasswordControllerTrait;
  32. use TargetPathTrait;
  33. private ResetPasswordHelperInterface $resetPasswordHelper;
  34. private EntityManagerInterface $em;
  35. public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, EntityManagerInterface $em)
  36. {
  37. $this->resetPasswordHelper = $resetPasswordHelper;
  38. $this->em = $em;
  39. }
  40. /**
  41. * Display & process form to request a password reset.
  42. * @Route("", name="app_user_forgot_password_request")
  43. */
  44. public function request(Request $request, MailerInterface $mailer, TranslatorInterface $translator): Response
  45. {
  46. $form = $this->createForm(ResetPasswordRequestFormType::class);
  47. $form->handleRequest($request);
  48. if ($form->isSubmitted() && $form->isValid()) {
  49. return $this->processSendingPasswordResetEmail(
  50. $form->get('email')->getData(),
  51. $mailer,
  52. $translator
  53. );
  54. }
  55. $breadcrumbs = [
  56. [
  57. "title" => $translator->trans("home_txt"),
  58. "url" => $this->generateUrl("fe_home"),
  59. ],
  60. [
  61. "title" => $translator->trans("forgot_password_question_txt"),
  62. "url" => null,
  63. ],
  64. ];
  65. return $this->render('user/reset_password/request.html.twig', [
  66. 'form' => $form->createView(),
  67. "breadcrumbs" => $breadcrumbs
  68. ]);
  69. }
  70. /**
  71. * Confirmation page after a user has requested a password reset.
  72. * @Route("/check-email", name="app_user_check_email")
  73. */
  74. public function checkEmail(): Response
  75. {
  76. // Generate a fake token if the user does not exist or someone hit this page directly.
  77. // This prevents exposing whether or not a user was found with the given email address or not
  78. if (null === ($resetToken = $this->getTokenObjectFromSession())) {
  79. $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  80. }
  81. return $this->render('user/reset_password/check_email.html.twig', [
  82. 'resetToken' => $resetToken,
  83. ]);
  84. }
  85. /**
  86. * Validates and process the reset URL that the user clicked in their email.
  87. * @Route("/reset/{token}", name="app_user_reset_password")
  88. */
  89. public function reset(
  90. Request $request,
  91. UserPasswordHasherInterface $userPasswordHasher,
  92. TranslatorInterface $translator,
  93. UserAuthenticatorInterface $userAuthenticator,
  94. CustomAuthenticator $authenticator,
  95. FirewallMapInterface $firewallMap,
  96. string $token = null
  97. ): Response
  98. {
  99. if ($token) {
  100. // We store the token in session and remove it from the URL, to avoid the URL being
  101. // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  102. $this->storeTokenInSession($token);
  103. return $this->redirectToRoute('app_user_reset_password');
  104. }
  105. $token = $this->getTokenFromSession();
  106. if (null === $token) {
  107. throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  108. }
  109. try {
  110. $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  111. } catch (ResetPasswordExceptionInterface $e) {
  112. $this->addFlash('error', sprintf(
  113. '%s - %s',
  114. $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [],
  115. 'ResetPasswordBundle'),
  116. $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  117. ));
  118. return $this->redirectToRoute('app_user_forgot_password_request');
  119. }
  120. // The token is valid; allow the user to change their password.
  121. $form = $this->createForm(ChangePasswordFormType::class);
  122. $form->handleRequest($request);
  123. if ($form->isSubmitted() && $form->isValid()) {
  124. // A password reset token should be used only once, remove it.
  125. $this->resetPasswordHelper->removeResetRequest($token);
  126. // Encode(hash) the plain password, and set it.
  127. $encodedPassword = $userPasswordHasher->hashPassword(
  128. $user,
  129. $form->get('plainPassword')->getData()
  130. );
  131. $user->setPassword($encodedPassword);
  132. $this->em->flush();
  133. // The session is cleaned up after the password has been changed.
  134. $this->cleanSessionAfterReset();
  135. $userAuthenticator->authenticateUser($user, $authenticator, $request);
  136. return $this->onAuthenticationSuccess($request, $firewallMap);
  137. }
  138. $breadcrumbs = [
  139. [
  140. "title" => $translator->trans("home_txt"),
  141. "url" => $this->generateUrl("fe_home"),
  142. ],
  143. [
  144. "title" => $translator->trans("reset_password_txt"),
  145. "url" => null,
  146. ],
  147. ];
  148. return $this->render('user/reset_password/reset.html.twig', [
  149. 'form' => $form->createView(),
  150. 'breadcrumbs' => $breadcrumbs,
  151. ]);
  152. }
  153. private function processSendingPasswordResetEmail(
  154. string $emailFormData,
  155. MailerInterface $mailer,
  156. TranslatorInterface $translator,
  157. SiteSettingService $siteSettingService
  158. ): RedirectResponse
  159. {
  160. $user = $this->em->getRepository(User::class)->findOneBy([
  161. 'email' => $emailFormData,
  162. "enabled" => true,
  163. "deleted" => null,
  164. ]);
  165. // Do not reveal whether a user account was found or not.
  166. if (!$user) {
  167. return $this->redirectToRoute('app_user_check_email');
  168. }
  169. try {
  170. $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  171. } catch (ResetPasswordExceptionInterface $e) {
  172. // If you want to tell the user why a reset email was not sent, uncomment
  173. // the lines below and change the redirect to 'app_forgot_password_request'.
  174. // Caution: This may reveal if a user is registered or not.
  175. //
  176. // $this->addFlash('error', sprintf(
  177. // '%s - %s',
  178. // $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  179. // $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  180. // ));
  181. return $this->redirectToRoute('app_user_check_email');
  182. }
  183. $email = (new TemplatedEmail())
  184. ->from(new Address($siteSettingService->getByConstantName('email-from'), $siteSettingService->getByConstantName('website-title')))
  185. ->to($user->getEmail())
  186. ->subject($siteSettingService->getByConstantName('website-title') . ' | Your password reset request')
  187. ->htmlTemplate('user/reset_password/email.html.twig')
  188. ->context([
  189. 'user' => $user,
  190. 'resetToken' => $resetToken,
  191. ]);
  192. $mailer->send($email);
  193. // Store the token object in session for retrieval in check-email route.
  194. $this->setTokenObjectInSession($resetToken);
  195. return $this->redirectToRoute('app_user_check_email');
  196. }
  197. private function onAuthenticationSuccess(Request $request, FirewallMapInterface $firewallMap): ?Response
  198. {
  199. $firewallConfig = $firewallMap->getFirewallConfig($request);
  200. if ($targetPath = $this->getTargetPath($request->getSession(), $firewallConfig->getName())) {
  201. return new RedirectResponse($targetPath);
  202. }
  203. return new RedirectResponse($this->generateUrl('fe_home'));
  204. }
  205. }