src/Controller/ResetPasswordController.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Mailer\MailerInterface;
  12. use Symfony\Component\Mime\Address;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  15. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  16. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  18. use Symfony\Component\DependencyInjection\ContainerInterface;
  19. /**
  20.  * @Route("/reset-password")
  21.  */
  22. class ResetPasswordController extends AbstractController
  23. {
  24.     use ResetPasswordControllerTrait;
  25.     private $resetPasswordHelper;
  26.     public $container;
  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(Request $requestMailerInterface $mailerContainerInterface $container): Response
  37.     {
  38.         $form $this->createForm(ResetPasswordRequestFormType::class);
  39.         $form->handleRequest($request);
  40.         if ($form->isSubmitted() && $form->isValid()) {
  41.             $recaptchaResponse $request->request->get('g-recaptcha-response');
  42.             $secretKey $container->getParameter('recaptcha_saas_secret');
  43.             $url 'https://www.google.com/recaptcha/api/siteverify?secret=' $secretKey '&response=' $recaptchaResponse;
  44.             $response file_get_contents($url);
  45.             $response json_decode($responsetrue);
  46.             if (!empty($response['success']) != true) {
  47.                 $this->addFlash('reset_password_error''Invalid CAPTCHA. Please try again.');
  48.                 return $this->render('reset_password/request.html.twig', [
  49.                     'requestForm' => $form->createView(),
  50.                 ]);
  51.             }
  52.             return $this->processSendingPasswordResetEmail(
  53.                 $form->get('email')->getData(),
  54.                 $mailer
  55.             );
  56.         }
  57.         return $this->render('reset_password/request.html.twig', [
  58.             'requestForm' => $form->createView(),
  59.         ]);
  60.     }
  61.     /**
  62.      * Confirmation page after a user has requested a password reset.
  63.      *
  64.      * @Route("/check-email", name="app_check_email")
  65.      */
  66.     public function checkEmail(): Response
  67.     {
  68.         // Generate a fake token if the user does not exist or someone hit this page directly.
  69.         // This prevents exposing whether or not a user was found with the given email address or not
  70.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  71.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  72.         }
  73.         return $this->render('reset_password/check_email.html.twig', [
  74.             'resetToken' => $resetToken,
  75.         ]);
  76.     }
  77.     /**
  78.      * Validates and process the reset URL that the user clicked in their email.
  79.      *
  80.      * @Route("/reset/{token}", name="app_reset_password")
  81.      */
  82.     public function reset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $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('app_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.             if ($user->getIsVerified() == 0) { // For create password action for the user, created by admin
  97.                 $this->getDoctrine()->getManager()->getRepository(User::class)->save(['is_verified' => 1'loginUserId' => $user->getId()], $user->getId());
  98.             }
  99.         } catch (ResetPasswordExceptionInterface $e) {
  100.             $this->addFlash('reset_password_error'sprintf(
  101.                 'There was a problem validating your reset request - %s',
  102.                 $e->getReason()
  103.             ));
  104.             return $this->redirectToRoute('app_forgot_password_request');
  105.         }
  106.         // The token is valid; allow the user to change their password.
  107.         $form $this->createForm(ChangePasswordFormType::class);
  108.         $form->handleRequest($request);
  109.         if ($form->isSubmitted() && $form->isValid()) {
  110.             // A password reset token should be used only once, remove it.
  111.             $this->resetPasswordHelper->removeResetRequest($token);
  112.             // Encode the plain password, and set it.
  113.             $encodedPassword $passwordEncoder->encodePassword(
  114.                 $user,
  115.                 $form->get('plainPassword')->getData()
  116.             );
  117.             $user->setPassword($encodedPassword);
  118.             $this->getDoctrine()->getManager()->flush();
  119.             // The session is cleaned up after the password has been changed.
  120.             $this->cleanSessionAfterReset();
  121.             $this->addFlash('reset_password_success''Your password has been successfully changed.');
  122.             return $this->redirectToRoute('app_landing_page');
  123.         }
  124.         return $this->render('reset_password/reset.html.twig', [
  125.             'resetForm' => $form->createView(),
  126.         ]);
  127.     }
  128.     /**
  129.      * Validates and process the reset URL that the user clicked in their email.
  130.      *
  131.      * @Route("/set-new-password/{id}", name="app_set_new_password")
  132.      */
  133.     public function setNewPassword($id)
  134.     {
  135.         return $this->render('reset_password/set_new_password.html.twig', [
  136.             'userId' => convert_uudecode($id),
  137.         ]);
  138.     }
  139.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  140.     {
  141.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  142.             'email' => $emailFormData,
  143.         ]);
  144.         // Do not reveal whether a user account was found or not.
  145.         if (!$user) {
  146.             $this->addFlash('reset_password_error'sprintf(
  147.                 'Email could not found. Please use your registered email id'
  148.             ));
  149.             return $this->redirectToRoute('app_forgot_password_request');
  150.         }
  151.         try {
  152.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  153.             $this->addFlash('reset_password_success''Check your email for instructions to reset your password');
  154.         } catch (ResetPasswordExceptionInterface $e) {
  155.             // If you want to tell the user why a reset email was not sent, uncomment
  156.             // the lines below and change the redirect to 'app_forgot_password_request'.
  157.             // Caution: This may reveal if a user is registered or not.
  158.             //
  159.             $this->addFlash('reset_password_error'sprintf(
  160.                 'There was a problem handling your password reset request - %s',
  161.                 $e->getReason()
  162.             ));
  163.             return $this->redirectToRoute('app_forgot_password_request');
  164.         }
  165.         $mailConfig =  $this->getParameter('mail');
  166.         $email = (new TemplatedEmail())
  167.             ->from(new Address($mailConfig['mail_from'], $mailConfig['mailer']))
  168.             ->to($user->getEmail())
  169.             ->subject('Your password reset request')
  170.             ->htmlTemplate('reset_password/email.html.twig')
  171.             ->context([
  172.                 'resetToken' => $resetToken,
  173.             ]);
  174.         $mailer->send($email);
  175.         // Store the token object in session for retrieval in check-email route.
  176.         $this->setTokenObjectInSession($resetToken);
  177.         return $this->redirectToRoute('app_forgot_password_request');
  178.     }
  179. }