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

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\Security\Form\ResetPasswordFormType;
  6. use Roothirsch\CoreBundle\Security\Form\ResetPasswordRequestFormType;
  7. use EasyCorp\Bundle\EasyAdminBundle\Factory\AdminContextFactory;
  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\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  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.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper)
  28.     {
  29.         $this->resetPasswordHelper $resetPasswordHelper;
  30.     }
  31.     /**
  32.      * Display & process form to request a password reset.
  33.      *
  34.      * @Route("", name="app_forgot_password_request")
  35.      */
  36.     public function request(
  37.         Request $request,
  38.         MailerInterface $mailer
  39.     ): Response {
  40.         $form $this->createForm(ResetPasswordRequestFormType::class);
  41.         $form->handleRequest($request);
  42.         if ($form->isSubmitted() && $form->isValid()) {
  43.             return $this->processSendingPasswordResetEmail(
  44.                 $form->get('email')->getData(),
  45.                 $mailer
  46.             );
  47.         }
  48.         return $this->render(
  49.             'security/reset_password/request.html.twig', [
  50.                 'requestForm' => $form->createView()
  51.             ]
  52.         );
  53.     }
  54.     /**
  55.      * Confirmation page after a user has requested a password reset.
  56.      *
  57.      * @Route("/check-email", name="app_check_email")
  58.      */
  59.     public function checkEmail(): Response
  60.     {
  61.         // Generate a fake token if the user does not exist or someone hit this page directly.
  62.         // This prevents exposing whether or not a user was found with the given email address or not
  63.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  64.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  65.         }
  66.         return $this->render(
  67.             'security/reset_password/check_email.html.twig', [
  68.                 'resetToken' => $resetToken,
  69.             ]
  70.         );
  71.     }
  72.     /**
  73.      * Validates and process the reset URL that the user clicked in their email.
  74.      *
  75.      * @Route("/reset/{token}", name="app_reset_password")
  76.      */
  77.     public function reset(
  78.         Request $request,
  79.         UserPasswordEncoderInterface $passwordEncoder,
  80.         string $token null
  81.     ): Response {
  82.         if ($token) {
  83.             // We store the token in session and remove it from the URL, to avoid the URL being
  84.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  85.             $this->storeTokenInSession($token);
  86.             return $this->redirectToRoute('app_reset_password');
  87.         }
  88.         $token $this->getTokenFromSession();
  89.         if (null === $token) {
  90.             throw $this->createNotFoundException('Beim Aufruf wurde kein Schlüssel übergeben.');
  91.         }
  92.         try {
  93.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  94.         } catch (ResetPasswordExceptionInterface $e) {
  95.             $this->addFlash(
  96.                 'reset_password_error'sprintf(
  97.                     'Beim Versuch Ihr Passwort zurückzusetzen ist ein Problem aufgetreten - %s',
  98.                     $e->getReason()
  99.                 )
  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(ResetPasswordFormType::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 the plain password, and set it.
  110.             $encodedPassword $passwordEncoder->encodePassword(
  111.                 $user,
  112.                 $form->get('plainPassword')->getData()
  113.             );
  114.             $user->setPassword($encodedPassword);
  115.             $this->getDoctrine()->getManager()->flush();
  116.             // The session is cleaned up after the password has been changed.
  117.             $this->cleanSessionAfterReset();
  118.             $this->addFlash('success''Das neue Passwort wurde gespeichert. Sie können sich jetzt anmelden.');
  119.             return $this->redirectToRoute('home');
  120.         }
  121.         return $this->render(
  122.             'security/reset_password/reset.html.twig', [
  123.                 'resetForm' => $form->createView(),
  124.             ]
  125.         );
  126.     }
  127.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  128.     {
  129.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy(
  130.             [
  131.                 'email' => $emailFormData,
  132.             ]
  133.         );
  134.         // Do not reveal whether a user account was found or not.
  135.         if (!$user) {
  136.             return $this->redirectToRoute('app_check_email');
  137.         }
  138.         try {
  139.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  140.         } catch (ResetPasswordExceptionInterface $e) {
  141.             // If you want to tell the user why a reset email was not sent, uncomment
  142.             // the lines below and change the redirect to 'app_forgot_password_request'.
  143.             // Caution: This may reveal if a user is registered or not.
  144.             //
  145.             // $this->addFlash('reset_password_error', sprintf(
  146.             //     'There was a problem handling your password reset request - %s',
  147.             //     $e->getReason()
  148.             // ));
  149.             return $this->redirectToRoute('app_check_email');
  150.         }
  151.         $email = (new TemplatedEmail())
  152.             ->to($user->getEmail())
  153.             ->subject('Your password reset request')
  154.             ->htmlTemplate('security/reset_password/email.html.twig')
  155.             ->context(
  156.                 [
  157.                     'resetToken' => $resetToken,
  158.                 ]
  159.             );
  160.         $mailer->send($email);
  161.         // Store the token object in session for retrieval in check-email route.
  162.         $this->setTokenObjectInSession($resetToken);
  163.         return $this->redirectToRoute('app_check_email');
  164.     }
  165. }