src/Controller/ResetPasswordController.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\Security\ChangePasswordFormType;
  5. use App\Form\Security\ResetPasswordRequestFormType;
  6. use App\Manager\UserManager;
  7. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\JsonResponse;
  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\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  19. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  21. /**
  22.  * @Route("/reset-password")
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private $resetPasswordHelper;
  28.     private $site_parameters;
  29.     private $translator;
  30.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper$site_parameters,TranslatorInterface $translator)
  31.     {
  32.         $this->resetPasswordHelper $resetPasswordHelper;
  33.         $this->site_parameters=$site_parameters;
  34.         $this->translator=$translator;
  35.     }
  36.     /**
  37.      * Display & process form to request a password reset.
  38.      *
  39.      * @Route("", name="app_forgot_password_request")
  40.      */
  41.     public function request(Request $requestMailerInterface $mailer): Response
  42.     {
  43.         $form $this->createForm(ResetPasswordRequestFormType::class);
  44.         $form->handleRequest($request);
  45.         if ($form->isSubmitted() && $form->isValid()) {
  46.             return $this->processSendingPasswordResetEmail(
  47.                 $form->get('email')->getData(),
  48.                 $mailer
  49.             );
  50.         }
  51.         return $this->render('security/reset_password/request.html.twig', [
  52.             'requestForm' => $form->createView(),
  53.         ]);
  54.     }
  55.     /**
  56.      * Confirmation page after a user has requested a password reset.
  57.      *
  58.      * @Route("/check-email", name="app_check_email")
  59.      */
  60.     public function checkEmail(): Response
  61.     {
  62.         // Generate a fake token if the user does not exist or someone hit this page directly.
  63.         // This prevents exposing whether or not a user was found with the given email address or not
  64.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  65.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  66.         }
  67.         return $this->render('security/reset_password/check_email.html.twig', [
  68.             'resetToken' => $resetToken,
  69.         ]);
  70.     }
  71.     /**
  72.      * Validates and process the reset URL that the user clicked in their email.
  73.      *
  74.      * @Route("/reset/{token}", name="app_reset_password")
  75.      */
  76.     public function reset(Request $request,UserManager $managerstring $token null): Response
  77.     {
  78.         if ($token) {
  79.             // We store the token in session and remove it from the URL, to avoid the URL being
  80.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  81.             $this->storeTokenInSession($token);
  82.             return $this->redirectToRoute('app_reset_password');
  83.         }
  84.         $token $this->getTokenFromSession();
  85.         if (null === $token) {
  86.             return $this->redirectToRoute('app_forgot_password_request');
  87.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  88.         }
  89.         try {
  90.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  91.         } catch (ResetPasswordExceptionInterface $e) {
  92.             $this->addFlash('reset_password_error'sprintf(
  93.                 'There was a problem validating your reset request - %s',
  94.                 $e->getReason()
  95.             ));
  96.             return $this->redirectToRoute('app_forgot_password_request');
  97.         }
  98.         // The token is valid; allow the user to change their password.
  99.         $form $this->createForm(ChangePasswordFormType::class);
  100.         $form->handleRequest($request);
  101.         if ($form->isSubmitted() && $form->isValid() and $request->isXmlHttpRequest()) {
  102.             // A password reset token should be used only once, remove it.
  103.             $this->resetPasswordHelper->removeResetRequest($token);
  104.             // Encode the plain password, and set it.
  105.             $user->setPassword($manager->encodePassword($user$form->get('plainPassword')->getData()));
  106.             $this->getDoctrine()->getManager()->flush();
  107.             // The session is cleaned up after the password has been changed.
  108.             $this->cleanSessionAfterReset();
  109.             return new JsonResponse('sucesss');
  110.         }
  111.         return $this->render('security/reset_password/reset.html.twig', [
  112.             'resetForm' => $form->createView(),
  113.         ]);
  114.     }
  115.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  116.     {
  117.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  118.             'email' => $emailFormData,
  119.         ]);
  120.         // Do not reveal whether a user account was found or not.
  121.         if (!$user) {
  122.             return $this->redirectToRoute('app_check_email');
  123.         }
  124.         try {
  125.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  126.         } catch (ResetPasswordExceptionInterface $e) {
  127.             // If you want to tell the user why a reset email was not sent, uncomment
  128.             // the lines below and change the redirect to 'app_forgot_password_request'.
  129.             // Caution: This may reveal if a user is registered or not.
  130.             //
  131.             // $this->addFlash('reset_password_error', sprintf(
  132.             //     'There wasThere was a problem validating your reset request - The link in your email is expired. Please try to reset your password again. a problem handling your password reset request - %s',
  133.             //     $e->getReason()
  134.             // ));
  135.             return $this->redirectToRoute('app_check_email');
  136.         }
  137.         $email = (new TemplatedEmail())
  138.             ->from(new Address($this->site_parameters['admin_email_address'], $this->site_parameters['admin_email_name']))
  139.             ->to($emailFormData)
  140.             ->subject($this->translator->trans('reset_password.email.subject',[],'security'))
  141.             //->htmlTemplate('user/email_registration.html.twig')
  142.             ->text($this->translator->trans('reset_password.email.body',[
  143.                 '%expiration_date%'=>$resetToken->getExpiresAt()->format('d/m/Y H:i'),
  144.                 '%url%'=>$this->generateUrl("app_reset_password",['token'=> $resetToken->getToken()],0)
  145.             ],'security'))
  146.         ;
  147.         $mailer->send($email);
  148.         // Store the token object in session for retrieval in check-email route.
  149.         $this->setTokenObjectInSession($resetToken);
  150.         return $this->redirectToRoute('app_check_email');
  151.     }
  152. }