src/Controller/Security/ResetPasswordController.php line 48

Open in your IDE?
  1. <?php
  2. // src: https://github.com/symfony/maker-bundle/blob/main/src/Resources/skeleton/resetPassword/ResetPasswordController.tpl.php
  3. namespace App\Controller\Security;
  4. use App\Entity\Email;
  5. use App\Entity\User;
  6. use App\Form\ChangePasswordFormType;
  7. use App\Form\ResetPasswordRequestFormType;
  8. use App\Repository\UserRepository;
  9. use App\Service\EmailService;
  10. use App\Service\FrontService;
  11. use App\Service\ParameterService;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Exception;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use Symfony\Component\HttpFoundation\RedirectResponse;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Contracts\Translation\TranslatorInterface;
  21. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  22. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  23. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  24. #[Route('/reset-password')]
  25. class ResetPasswordController extends AbstractController
  26. {
  27.     use ResetPasswordControllerTrait;
  28.     public function __construct(
  29.         private readonly ResetPasswordHelperInterface $resetPasswordHelper,
  30.         private readonly EmailService                 $emailService,
  31.         private readonly EntityManagerInterface       $entityManager,
  32.         private readonly TranslatorInterface          $translator,
  33.         private readonly ParameterService             $parameterService,
  34.         private readonly FrontService                 $frontService
  35.     )
  36.     {
  37.     }
  38.     /**
  39.      * Display & process form to request a password reset.
  40.      */
  41.     #[Route(''name'app_forgot_password_request')]
  42.     public function request(Request $request): Response
  43.     {
  44.         $form $this->createForm(ResetPasswordRequestFormType::class);
  45.         $form->handleRequest($request);
  46.         $customerType $request->query->get('type');
  47.         if ($form->isSubmitted() && $form->isValid()) {
  48.             return $this->processSendingPasswordResetEmail(
  49.                 $form->get('email')->getData(), $customerType
  50.             );
  51.         }
  52.         return $this->render('security/' $customerType '/forgot_password.html.twig', [
  53.             'requestForm' => $form->createView(),
  54.             'society'           => $this->parameterService->getSocietyParameters(),
  55.             'social_networks'   => $this->frontService->getSocialNetworks(),
  56.             'agencies'          => $this->frontService->getAgencies(),
  57.             'currencies'        => $this->frontService->getCurrencies(),
  58.             'agency' => ($request->query->get('type')) ? $this->parameterService->getSocietyParameters() : null,
  59.             'type' => $customerType
  60.         ]);
  61.     }
  62.     /**
  63.      * Confirmation page after a user has requested a password reset.
  64.      */
  65.     #[Route('/check-email'name'app_check_email')]
  66.     public function checkEmail(): Response
  67.     {
  68.         // Generate a fake token if the user does not exist or someone hit this page directly.
  69.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  70.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  71.         }
  72.         return $this->render('security/reset_password/check_email.html.twig', [
  73.             'resetToken' => $resetToken,
  74.             'society'           => $this->parameterService->getSocietyParameters(),
  75.             'social_networks'   => $this->frontService->getSocialNetworks(),
  76.             'agencies'          => $this->frontService->getAgencies(),
  77.             'currencies'        => $this->frontService->getCurrencies(),
  78.         ]);
  79.     }
  80.     /**
  81.      * Validates and process the reset URL that the user clicked in their email.
  82.      */
  83.     #[Route('/reset/{token}'name'app_reset_password')]
  84.     public function reset(
  85.         Request                     $request,
  86.         UserPasswordHasherInterface $passwordHasher,
  87.         TranslatorInterface         $translator,
  88.         string                      $token null): Response
  89.     {
  90.         if ($token) {
  91.             // We store the token in session and remove it from the URL, to avoid the URL being
  92.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  93.             $this->storeTokenInSession($token);
  94.             return $this->redirectToRoute('app_reset_password');
  95.         }
  96.         $token $this->getTokenFromSession();
  97.         if (null === $token) {
  98.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  99.         }
  100.         try {
  101.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  102.         } catch (ResetPasswordExceptionInterface $e) {
  103.             $this->addFlash('reset_password_error'sprintf(
  104.                 '%s - %s',
  105.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  106.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  107.             ));
  108.             return $this->redirectToRoute('app_forgot_password_request', ['type' => 'btoc']);
  109.         }
  110.         // The token is valid; allow the user to change their password.
  111.         $form $this->createForm(ChangePasswordFormType::class, $user);
  112.         $form->handleRequest($request);
  113.         if ($form->isSubmitted() && $form->isValid()) {
  114.             // A password reset token should be used only once, remove it.
  115.             $this->resetPasswordHelper->removeResetRequest($token);
  116.             // Encode(hash) the plain password, and set it.
  117.             $encodedPassword $passwordHasher->hashPassword(
  118.                 $user,
  119.                 $form->get('password')->getData()
  120.             );
  121.             $user->setPassword($encodedPassword);
  122.             $this->entityManager->persist($user);
  123.             $this->entityManager->flush();
  124.             // The session is cleaned up after the password has been changed.
  125.             //  $this->cleanSessionAfterReset();
  126.             return $this->render('security/confirm.html.twig', [
  127.                 'confirmMessage' =>
  128.                     $this->translator->trans('Pages.ResetPassword.Alerts.Success', [], 'messages_front'),
  129.                 'society'           => $this->parameterService->getSocietyParameters(),
  130.                 'social_networks'   => $this->frontService->getSocialNetworks(),
  131.                 'agencies'          => $this->frontService->getAgencies(),
  132.                 'currencies'        => $this->frontService->getCurrencies(),
  133.             ]);
  134.         }
  135.         return $this->render('security/reset_password/reset.html.twig', [
  136.             'resetForm' => $form->createView(),
  137.             'society'           => $this->parameterService->getSocietyParameters(),
  138.             'social_networks'   => $this->frontService->getSocialNetworks(),
  139.             'agencies'          => $this->frontService->getAgencies(),
  140.             'currencies'        => $this->frontService->getCurrencies(),
  141.         ]);
  142.     }
  143.     private function processSendingPasswordResetEmail(string $emailAddressstring $customerType): RedirectResponse
  144.     {
  145.         $user $this->entityManager->getRepository(User::class)->findOneBy(['email' => $emailAddress]);
  146.         // Do not reveal whether a user account was found or not.
  147.         if (!$user) {
  148.             $this->addFlash('reset_password_error''email introuvable');
  149.             return $this->redirectToRoute('app_forgot_password_request', ['type' => $customerType]);
  150.         }
  151.         try {
  152.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  153.         } catch (ResetPasswordExceptionInterface $e) {
  154.             /*    If you want to tell the user why a reset email was not sent, uncomment
  155.                 the lines below and change the redirect to 'app_forgot_password_request'.
  156.                 Caution: This may reveal if a user is registered or not.*/
  157.             $this->addFlash('reset_password_error'sprintf(
  158.                 '%s - %s',
  159.                 $this->translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  160.                 $this->translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  161.             ));
  162.             return $this->redirectToRoute('app_forgot_password_request', ['type' => $customerType]);
  163.         }
  164.         $htmlContent $this->renderView('security/reset_password/email.html.twig', ['resetToken' => $resetToken]);
  165.         $email $this->emailService->composeMail(
  166.             $this->parameterService->getEmailSocietyAddress(Email::ACCOUNT),
  167.             $user->getEmail(),
  168.             "Reset password",
  169.             $htmlContent,
  170.         );
  171.         try {
  172.             $this->emailService->send($email);
  173.             $email->setState(true);
  174.         } catch (Exception $e) {
  175.             $this->addFlash('reset_password_error'$e->getMessage());
  176.             return $this->redirectToRoute('app_forgot_password_request');
  177.         }
  178.         // Store the token object in session for retrieval in check-email route.
  179.         $this->setTokenObjectInSession($resetToken);
  180.         return $this->redirectToRoute('app_check_email');
  181.     }
  182.     #[Route('/change-password'name'app_front_userarea_change_password'methods: ['GET''POST'])]
  183.     public function changePassword(
  184.         Request $request,
  185.         UserRepository $userRepository,
  186.         UserPasswordHasherInterface $userPasswordHasher
  187.     ): Response
  188.     {
  189.         $user $this->getUser();
  190.         $customer $user->getCustomer();
  191.         $form $this->createForm(ChangePasswordFormType::class, $user);
  192.         $form->handleRequest($request);
  193.         if ($form->isSubmitted() && $form->isValid()) {
  194.             $user->setPassword(
  195.                 $userPasswordHasher->hashPassword(
  196.                     $user,
  197.                     $form->get('password')->getData()
  198.                 )
  199.             );
  200.             $userRepository->add($usertrue);
  201.             return $this->redirectToRoute('app_front_userarea_change_password', [], Response::HTTP_SEE_OTHER);
  202.         }
  203.         $activatedModules $this->parameterService->getActiveModules();
  204.         return $this->renderForm('front/userarea/btoc/change-password.html.twig', [
  205.             'customer' => $customer,
  206.             'form' => $form,
  207.             'activatedModules' => $activatedModules,
  208.             'currentRoute' => $request->attributes->get('_route'),
  209.             'society'           => $this->parameterService->getSocietyParameters(),
  210.             'social_networks'   => $this->frontService->getSocialNetworks(),
  211.             'agencies'          => $this->frontService->getAgencies(),
  212.             'currencies'        => $this->frontService->getCurrencies(),
  213.         ]);
  214.     }
  215. }