vendor/datenwerk/ginger-bundle/Controller/ResetPasswordController.php line 53

Open in your IDE?
  1. <?php
  2. namespace DW\GingerBundle\Controller;
  3. use DW\GingerBundle\Entity\User;
  4. use DW\GingerBundle\Form\Type\ChangePasswordFormType;
  5. use DW\GingerBundle\Form\Type\ResetPasswordRequestFormType;
  6. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Mailer\MailerInterface;
  13. use Symfony\Component\Mime\Address;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  17. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  20. use DW\GingerBundle\Security\UserAuthenticator;
  21. /**
  22.  * @Route("/reset-password")
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private ResetPasswordHelperInterface $resetPasswordHelper;
  28.     private GuardAuthenticatorHandler $guard;
  29.     private UserAuthenticator $authenticator;
  30.     private ParameterBagInterface $parameterBag;
  31.     public function __construct(
  32.         ResetPasswordHelperInterface $resetPasswordHelper,
  33.         GuardAuthenticatorHandler $guard,
  34.         UserAuthenticator $authenticator,
  35.         ParameterBagInterface $parameterBag
  36.     ) {
  37.         $this->resetPasswordHelper $resetPasswordHelper;
  38.         $this->guard $guard;
  39.         $this->authenticator $authenticator;
  40.         $this->parameterBag $parameterBag;
  41.     }
  42.     /**
  43.      * Display & process form to request a password reset.
  44.      *
  45.      * @Route("", name="ginger_forgot_password_request")
  46.      */
  47.     public function request(Request $requestMailerInterface $mailer): Response
  48.     {
  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->getHost()
  56.             );
  57.         }
  58.         return $this->render('@DWGinger/reset_password/request.html.twig', [
  59.             'requestForm' => $form->createView(),
  60.         ]);
  61.     }
  62.     /**
  63.      * Confirmation page after a user has requested a password reset.
  64.      *
  65.      * @Route("/check-email", name="ginger_check_email")
  66.      */
  67.     public function checkEmail(): Response
  68.     {
  69.         // We prevent users from directly accessing this page
  70.         if (!$this->canCheckEmail()) {
  71.             return $this->redirectToRoute('ginger_forgot_password_request');
  72.         }
  73.         return $this->render('@DWGinger/reset_password/check_email.html.twig', [
  74.             'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  75.         ]);
  76.     }
  77.     /**
  78.      * Validates and process the reset URL that the user clicked in their email.
  79.      *
  80.      * @Route("/reset/{token}", name="ginger_reset_password")
  81.      */
  82.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherstring $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('ginger_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.                 'There was a problem validating your reset request - %s',
  99.                 $e->getReason()
  100.             ));
  101.             return $this->redirectToRoute('ginger_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 the plain password, and set it.
  110.             $encodedPassword $passwordHasher->hashPassword(
  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.             //return $this->redirectToRoute('ginger_dashboard');
  119.             // Login user
  120.             return $this->guard->authenticateUserAndHandleSuccess($user$request$this->authenticator'main');
  121.         }
  122.         return $this->render('@DWGinger/reset_password/reset.html.twig', [
  123.             'resetForm' => $form->createView(),
  124.         ]);
  125.     }
  126.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerstring $host 'ginger.at'): RedirectResponse
  127.     {
  128.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  129.             'email' => $emailFormData,
  130.         ]);
  131.         // Marks that you are allowed to see the ginger_check_email page.
  132.         $this->setCanCheckEmailInSession();
  133.         // Do not reveal whether a user account was found or not.
  134.         if (!$user) {
  135.             return $this->redirectToRoute('ginger_check_email');
  136.         }
  137.         try {
  138.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  139.         } catch (ResetPasswordExceptionInterface $e) {
  140.             // If you want to tell the user why a reset email was not sent, uncomment
  141.             // the lines below and change the redirect to 'ginger_forgot_password_request'.
  142.             // Caution: This may reveal if a user is registered or not.
  143.              $this->addFlash('reset_password_error'sprintf(
  144.                  'There was a problem handling your password reset request - %s',
  145.                  $e->getReason()
  146.              ));
  147.             return $this->redirectToRoute('ginger_check_email');
  148.         }
  149.         // If no from_mail is configured on application level, fall back to "noreply@$host".
  150.         $mailerConfig $this->parameterBag->get('dw_ginger.mailer');
  151.         $fromMail str_replace("ginger.dev"$host$mailerConfig['from_mail']);
  152.         $email = (new TemplatedEmail())
  153.             ->from(new Address($fromMail$mailerConfig['from_name']))
  154.             ->to($user->getEmail())
  155.             ->subject('Passwort zurücksetzten')
  156.             ->htmlTemplate('@DWGinger/reset_password/email.html.twig')
  157.             ->context([
  158.                 'resetToken' => $resetToken,
  159.                 'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  160.             ])
  161.         ;
  162.         $mailer->send($email);
  163.         return $this->redirectToRoute('ginger_check_email');
  164.     }
  165. }