vendor/roothirsch/core-bundle/Security/Controller/ResetPasswordController.php line 53

Open in your IDE?
  1. <?php
  2. namespace Roothirsch\CoreBundle\Security\Controller;
  3. use Roothirsch\CoreBundle\Controller\FrontendController;
  4. use Roothirsch\CoreBundle\Entity\User;
  5. use Roothirsch\CoreBundle\Messaging\MessagingService;
  6. use Roothirsch\CoreBundle\Security\Form\ResetPasswordFormType;
  7. use Roothirsch\CoreBundle\Security\Form\ResetPasswordRequestFormType;
  8. use EasyCorp\Bundle\EasyAdminBundle\Factory\AdminContextFactory;
  9. use Roothirsch\CoreBundle\Translation\Services\CoreTranslator;
  10. use Roothirsch\CoreBundle\Translation\Services\LegacyTranslator;
  11. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Mailer\MailerInterface;
  17. use Symfony\Component\Mime\Address;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  21. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  23. /**
  24. * @Route("/reset-password")
  25. */
  26. class ResetPasswordController extends AbstractController
  27. {
  28. use ResetPasswordControllerTrait;
  29. private $resetPasswordHelper;
  30. /** @var MessagingService */
  31. private $messaging;
  32. /** @var CoreTranslator */
  33. private $translationService;
  34. public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, MessagingService $messagingService, CoreTranslator $translator)
  35. {
  36. $this->resetPasswordHelper = $resetPasswordHelper;
  37. $this->messaging = $messagingService;
  38. $this->translationService = $translator;
  39. }
  40. /**
  41. * Display & process form to request a password reset.
  42. *
  43. * @Route("", name="app_forgot_password_request")
  44. */
  45. public function request(
  46. Request $request,
  47. MailerInterface $mailer
  48. ): Response {
  49. $form = $this->createForm(ResetPasswordRequestFormType::class);
  50. $form->handleRequest($request);
  51. if ($form->isSubmitted() && $form->isValid()) {
  52. return $this->processSendingPasswordResetEmail(
  53. $form->get('email')->getData(),
  54. $mailer,
  55. $request->getLocale()
  56. );
  57. }
  58. return $this->render(
  59. 'security/reset_password/request.html.twig', [
  60. 'requestForm' => $form->createView()
  61. ]
  62. );
  63. }
  64. /**
  65. * Confirmation page after a user has requested a password reset.
  66. *
  67. * @Route("/check-email", name="app_check_email")
  68. */
  69. public function checkEmail(): Response
  70. {
  71. // Generate a fake token if the user does not exist or someone hit this page directly.
  72. // This prevents exposing whether or not a user was found with the given email address or not
  73. if (null === ($resetToken = $this->getTokenObjectFromSession())) {
  74. $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  75. }
  76. return $this->render(
  77. 'security/reset_password/check_email.html.twig', [
  78. 'resetToken' => $resetToken,
  79. ]
  80. );
  81. }
  82. /**
  83. * Validates and process the reset URL that the user clicked in their email.
  84. *
  85. * @Route("/reset/{token}", name="app_reset_password")
  86. */
  87. public function reset(
  88. Request $request,
  89. UserPasswordEncoderInterface $passwordEncoder,
  90. string $token = null
  91. ): Response {
  92. if ($token) {
  93. // We store the token in session and remove it from the URL, to avoid the URL being
  94. // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  95. $this->storeTokenInSession($token);
  96. return $this->redirectToRoute('app_reset_password');
  97. }
  98. $token = $this->getTokenFromSession();
  99. if (null === $token) {
  100. throw $this->createNotFoundException('Beim Aufruf wurde kein Schlüssel übergeben.');
  101. }
  102. try {
  103. $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  104. } catch (ResetPasswordExceptionInterface $e) {
  105. $this->addFlash(
  106. 'reset_password_error', sprintf(
  107. 'Beim Versuch Ihr Passwort zurückzusetzen ist ein Problem aufgetreten - %s',
  108. $e->getReason()
  109. )
  110. );
  111. return $this->redirectToRoute('app_forgot_password_request');
  112. }
  113. // The token is valid; allow the user to change their password.
  114. $form = $this->createForm(ResetPasswordFormType::class);
  115. $form->handleRequest($request);
  116. if ($form->isSubmitted() && $form->isValid()) {
  117. // A password reset token should be used only once, remove it.
  118. $this->resetPasswordHelper->removeResetRequest($token);
  119. // Encode the plain password, and set it.
  120. $encodedPassword = $passwordEncoder->encodePassword(
  121. $user,
  122. $form->get('plainPassword')->getData()
  123. );
  124. $user->setPassword($encodedPassword);
  125. $this->getDoctrine()->getManager()->flush();
  126. // The session is cleaned up after the password has been changed.
  127. $this->cleanSessionAfterReset();
  128. $this->addFlash('success', $this->translationService->translate('notification.passwort_reset.success', 'Das neue Passwort wurde gespeichert. Sie können sich jetzt anmelden.'));
  129. return $this->redirectToRoute('home');
  130. }
  131. return $this->render(
  132. 'security/reset_password/reset.html.twig', [
  133. 'resetForm' => $form->createView(),
  134. ]
  135. );
  136. }
  137. private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, $locale='de'): RedirectResponse
  138. {
  139. $user = $this->getDoctrine()->getRepository(User::class)->findOneBy(
  140. [
  141. 'email' => $emailFormData,
  142. ]
  143. );
  144. // Do not reveal whether a user account was found or not.
  145. if (!$user) {
  146. return $this->redirectToRoute('app_check_email');
  147. }
  148. try {
  149. $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  150. } catch (ResetPasswordExceptionInterface $e) {
  151. // If you want to tell the user why a reset email was not sent, uncomment
  152. // the lines below and change the redirect to 'app_forgot_password_request'.
  153. // Caution: This may reveal if a user is registered or not.
  154. //
  155. // $this->addFlash('reset_password_error', sprintf(
  156. // 'There was a problem handling your password reset request - %s',
  157. // $e->getReason()
  158. // ));
  159. return $this->redirectToRoute('app_check_email');
  160. }
  161. $email = $this->messaging->createTranslatedEmail('security/reset_password/email.html.twig', [
  162. 'resetToken' => $resetToken,
  163. ], $locale);
  164. $email
  165. ->to($user->getEmail())
  166. ->subject(
  167. $this->translationService->translate('email.passwort_reset.user_email.subject', 'Ihre Anfrage zum Zurücksetzen des Passworts')
  168. );
  169. $mailer->send($email);
  170. // Store the token object in session for retrieval in check-email route.
  171. $this->setTokenObjectInSession($resetToken);
  172. return $this->redirectToRoute('app_check_email');
  173. }
  174. }