src/Controller/ResetPasswordController.php line 44

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 App\Repository\UserRepository;
  7. use App\Service\MailService;
  8. use App\String\Constant;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Mailer\MailerInterface;
  16. use Symfony\Component\Mime\Address;
  17. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Contracts\Translation\TranslatorInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  21. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  23. #[Route('/reset-password')]
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private ResetPasswordHelperInterface $resetPasswordHelper;
  28.     private EntityManagerInterface $entityManager;
  29.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  30.     {
  31.         $this->resetPasswordHelper $resetPasswordHelper;
  32.         $this->entityManager $entityManager;
  33.     }
  34.     /**
  35.      * Display & process form to request a password reset.
  36.      */
  37.     #[Route(''name'app_forgot_password_request')]
  38.     public function request(Request $requestMailService $mailerTranslatorInterface $translator): Response
  39.     {
  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.                 $translator
  47.             );
  48.         }
  49.         return $this->render('reset_password/request.html.twig', [
  50.             'requestForm' => $form->createView(),
  51.         ]);
  52.     }
  53.     /**
  54.      * Confirmation page after a user has requested a password reset.
  55.      */
  56.     #[Route('/check-email'name'app_check_email')]
  57.     public function checkEmail(): Response
  58.     {
  59.         // Generate a fake token if the user does not exist or someone hit this page directly.
  60.         // This prevents exposing whether or not a user was found with the given email address or not
  61.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  62.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  63.         }
  64.         return $this->render('reset_password/check_email.html.twig', [
  65.             'resetToken' => $resetToken,
  66.         ]);
  67.     }
  68.     /**
  69.      * Validates and process the reset URL that the user clicked in their email.
  70.      */
  71.     #[Route('/reset/{token}'name'app_reset_password')]
  72.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  73.     {
  74.         if ($token) {
  75.             // We store the token in session and remove it from the URL, to avoid the URL being
  76.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  77.             $this->storeTokenInSession($token);
  78.             if ($request->get('accountclaim')) {
  79.                 return $this->redirectToRoute('app_reset_password', [
  80.                     'accountclaim' => true
  81.                 ]);
  82.             }
  83.             return $this->redirectToRoute('app_reset_password');
  84.         }
  85.         $token $this->getTokenFromSession();
  86.         if (null === $token) {
  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.                 '%s - %s',
  94.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  95.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  96.             ));
  97.             return $this->redirectToRoute('app_forgot_password_request');
  98.         }
  99.         // The token is valid; allow the user to change their password.
  100.         $form $this->createForm(ChangePasswordFormType::class);
  101.         $form->handleRequest($request);
  102.         if ($form->isSubmitted() && $form->isValid()) {
  103.             // A password reset token should be used only once, remove it.
  104.             $this->resetPasswordHelper->removeResetRequest($token);
  105.             // Encode(hash) the plain password, and set it.
  106.             $encodedPassword $userPasswordHasher->hashPassword(
  107.                 $user,
  108.                 $form->get('plainPassword')->getData()
  109.             );
  110.             $user->setPassword($encodedPassword);
  111.             $this->entityManager->flush();
  112.             // The session is cleaned up after the password has been changed.
  113.             $this->cleanSessionAfterReset();
  114.             return $this->redirectToRoute('app_login');
  115.         }
  116.         if ($request->get('accountclaim')) {
  117.             return $this->render('reset_password/reset_account_claim.html.twig', [
  118.                 'resetForm' => $form->createView(),
  119.             ]);
  120.         }
  121.         return $this->render('reset_password/reset.html.twig', [
  122.             'resetForm' => $form->createView(),
  123.         ]);
  124.     }
  125.     private function processSendingPasswordResetEmail(string $emailFormDataMailService $mailServiceTranslatorInterface $translator): RedirectResponse
  126.     {
  127.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  128.             'email' => $emailFormData,
  129.         ]);
  130.         // Do not reveal whether a user account was found or not.
  131.         if (!$user) {
  132.             return $this->redirectToRoute('app_check_email');
  133.         }
  134.         try {
  135.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  136.         } catch (ResetPasswordExceptionInterface $e) {
  137.             // If you want to tell the user why a reset email was not sent, uncomment
  138.             // the lines below and change the redirect to 'app_forgot_password_request'.
  139.             // Caution: This may reveal if a user is registered or not.
  140.             //
  141.             // $this->addFlash('reset_password_error', sprintf(
  142.             //     '%s - %s',
  143.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  144.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  145.             // ));
  146.             return $this->redirectToRoute('app_check_email');
  147.         }
  148.         $mailService->sendPasswordResetEmail($user$resetToken); // Send reset password email
  149.         // Store the token object in session for retrieval in check-email route.
  150.         $this->setTokenObjectInSession($resetToken);
  151.         return $this->redirectToRoute('app_check_email');
  152.     }
  153.     #[Route('/bulk-reset'name'app_send_bulk_reset_password')]
  154.     public function bulkReset(Request $requestMailerInterface $mailerTranslatorInterface $translatorUserRepository $userRepository): Response
  155.     {
  156.         $form $this->createForm(ResetPasswordRequestFormType::class);
  157.         $form->handleRequest($request);
  158.         $emails = ["[email protected]"];
  159.         //for ($i = 726; $i < 728; $i++) {
  160.         //    $user = $userRepository->findOneBy(['id' => $i]);
  161.         //    if ($user) {
  162.         //        array_push($emails, $user->getEmail());
  163.         //    } else {
  164.         //        var_dump($i .' IS MISSING \n');
  165.         //    }
  166.         //}
  167.         foreach ($emails as $email) {
  168.             $this->accountClaimEmail(
  169.                 $email,
  170.                 $mailer,
  171.                 $translator
  172.             );
  173.             var_dump($email .' : SUCCESS \n');
  174.         }
  175.         var_dump('all accounts have been sent with account claim email.'); exit();
  176.         if ($form->isSubmitted() && $form->isValid()) {
  177.             return $this->accountClaimEmail(
  178.                 $form->get('email')->getData(),
  179.                 $mailer,
  180.                 $translator
  181.             );
  182.         }
  183.         return $this->render('reset_password/request.html.twig', [
  184.             'requestForm' => $form->createView(),
  185.         ]);
  186.     }
  187.     private function accountClaimEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  188.     {
  189.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  190.             'email' => $emailFormData,
  191.         ]);
  192.         // Do not reveal whether a user account was found or not.
  193.         if (!$user) {
  194.             return $this->redirectToRoute('app_check_email');
  195.         }
  196.         try {
  197.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  198.         } catch (ResetPasswordExceptionInterface $e) {
  199.             return $this->redirectToRoute('app_check_email');
  200.         }
  201.         $email = (new TemplatedEmail())
  202.             ->from(new Address(Constant::FROM_EMAIL'Documentary Australia'))
  203.             ->to($user->getEmail())
  204.             ->subject('Your Documentary Australia Account Claim')
  205.             ->htmlTemplate('reset_password/account_claim.html.twig')
  206.             ->context([
  207.                 'user' => $user,
  208.                 'resetToken' => $resetToken,
  209.             ])
  210.         ;
  211.         $mailer->send($email);
  212.         // Store the token object in session for retrieval in check-email route.
  213.         $this->setTokenObjectInSession($resetToken);
  214.         return $this->redirectToRoute('app_check_email');
  215.     }
  216. }