src/Controller/ResetPasswordController.php line 52

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Entity\UserProfile;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  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\Security\Core\Encoder\UserPasswordEncoderInterface;
  16. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  17. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. use Symfony\Contracts\Translation\TranslatorInterface;
  20. use App\Utils\MailSpool;
  21. use App\Repository\TcMailLogRepository;
  22. use App\Command\ExecuteCommand;
  23. /**
  24.  * @Route("/reset-password")
  25.  */
  26. class ResetPasswordController extends AbstractController
  27. {
  28.     use ResetPasswordControllerTrait;
  29.     private $resetPasswordHelper;
  30.     private $translator;
  31.     private $mailSpool;
  32.     private $executeCommand;
  33.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperTranslatorInterface $translatorMailSpool $mailSpoolExecuteCommand $executeCommand)
  34.     {
  35.         $this->resetPasswordHelper $resetPasswordHelper;
  36.         $this->translator $translator;
  37.         $this->mailSpool $mailSpool;
  38.         $this->executeCommand $executeCommand;
  39.     }
  40.     /**
  41.      * Display & process form to request a password reset.
  42.      *
  43.      * @Route("", name="app_forgot_password_request")
  44.      */
  45.     public function request(Request $requestMailerInterface $mailer): Response
  46.     {
  47.         $form $this->createForm(ResetPasswordRequestFormType::class);
  48.         $form->handleRequest($request);
  49.         if ($form->isSubmitted() && $form->isValid()) {
  50.             return $this->processSendingPasswordResetEmail(
  51.                 $form->get('email')->getData(),
  52.                 $mailer
  53.             );
  54.         }
  55.         return $this->render('authentication/password_reset.html.twig', [
  56.             'requestForm' => $form->createView(),
  57.         ]);
  58.     }
  59.     /**
  60.      * Confirmation page after a user has requested a password reset.
  61.      *
  62.      * @Route("/check-email", name="app_check_email")
  63.      */
  64.     public function checkEmail(): Response
  65.     {
  66.         // Generate a fake token if the user does not exist or someone hit this page directly.
  67.         // This prevents exposing whether or not a user was found with the given email address or not
  68.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  69.             return $this->redirectToRoute('app_forgot_password_request');
  70.         }
  71.         return $this->render('authentication/check_email.html.twig', [
  72.             'resetToken' => $resetToken,
  73.         ]);
  74.     }
  75.     /**
  76.      * Validates and process the reset URL that the user clicked in their email.
  77.      *
  78.      * @Route("/reset/{token}", name="app_reset_password")
  79.      */
  80.     public function reset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $token null): Response
  81.     {
  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('No reset password token found in the URL or in the session.');
  91.         }
  92.         try {
  93.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  94.         } catch (ResetPasswordExceptionInterface $e) {
  95.             $this->addFlash('reset_password_error'sprintf(
  96.                 $e->getReason()
  97.             ));
  98.             return $this->redirectToRoute('app_forgot_password_request');
  99.         }
  100.         // The token is valid; allow the user to change their password.
  101.         $form $this->createForm(ChangePasswordFormType::class);
  102.         $form->handleRequest($request);
  103.         if ($form->isSubmitted() && $form->isValid()) {
  104.             // A password reset token should be used only once, remove it.
  105.             $this->resetPasswordHelper->removeResetRequest($token);
  106.             // Encode the plain password, and set it.
  107.             $encodedPassword $passwordEncoder->encodePassword(
  108.                 $user,
  109.                 $form->get('plainPassword')->getData()
  110.             );
  111.             $user->setPassword($encodedPassword);
  112.             $this->getDoctrine()->getManager()->flush();
  113.             // The session is cleaned up after the password has been changed.
  114.             $this->cleanSessionAfterReset();
  115.             return $this->redirectToRoute('app_landing_page');
  116.         }
  117.         return $this->render('authentication/new_password.html.twig', [
  118.             'resetForm' => $form->createView(),
  119.         ]);
  120.     }
  121.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  122.     {
  123.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  124.             'email' => $emailFormData,
  125.         ]);
  126.         // Do not reveal whether a user account was found or not.
  127.         if (!$user) {
  128.             $this->addFlash('reset_password_error'sprintf(
  129.                 'Email could not found. Please use your registered email id'
  130.             ));
  131.             return $this->redirectToRoute('app_forgot_password_request');
  132.         }
  133.         try {
  134.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  135.         } catch (ResetPasswordExceptionInterface $e) {
  136.             // If you want to tell the user why a reset email was not sent, uncomment
  137.             // the lines below and change the redirect to 'app_forgot_password_request'.
  138.             // Caution: This may reveal if a user is registered or not.
  139.             $this->addFlash('reset_password_error'sprintf(
  140.                 $e->getReason()
  141.             ));
  142.             return $this->redirectToRoute('app_forgot_password_request');
  143.         }
  144.         $users $this->getDoctrine()->getRepository(UserProfile::class)->findOneBy([
  145.             'user' => $user->getId(),
  146.         ]);
  147.         $details['firstname']=$users->getFirstName();
  148.         $details['lastname']=$users->getLastName();
  149.         $mail $this->getParameter('mail');
  150.       
  151.         $email = (new TemplatedEmail())
  152.             ->from(new Address($mail['mail_from'],$mail['mailer']))
  153.             ->to($user->getEmail())
  154.             ->subject('Your password reset request')
  155.             ->htmlTemplate('reset_password/email.html.twig')
  156.             ->context([
  157.                 'resetToken' => $resetToken,'detail' => $details
  158.             ])
  159.         ;
  160.         $mailer->send($email);
  161.         // Store the token object in session for retrieval in check-email route.
  162.         $this->setTokenObjectInSession($resetToken);
  163.         $mailSend = [];
  164.         $mailSend['user_id'] = $user->getId();
  165.         $mailSend['mail_type'] = "reset_password";
  166.         $mailSend['email'] = $mail['mail_to'];
  167.         $mailSend['email_template'] = "email.html.twig";
  168.         $mailSend['subject'] = "reset password";
  169.         $mailData $this->mailSpool->insertIntoSpool($mailSend);
  170.         $this->executeCommand->processShellCmd('mail:send');
  171.         return $this->redirectToRoute('app_check_email');
  172.     }
  173. }