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($customerType == null){
  48.             $customerType "btoc";
  49.         }
  50.         if ($form->isSubmitted() && $form->isValid()) {
  51.             return $this->processSendingPasswordResetEmail(
  52.                 $form->get('email')->getData(), $customerType
  53.             );
  54.         }
  55.         $template =  'security/' $customerType '/forgot_password.html.twig';
  56.         return $this->render($template, [
  57.             'requestForm' => $form->createView(),
  58.             'society'           => $this->parameterService->getSocietyParameters(),
  59.             'social_networks'   => $this->frontService->getSocialNetworks(),
  60.             'agencies'          => $this->frontService->getAgencies(),
  61.             'currencies'        => $this->frontService->getCurrencies(),
  62.             'agency' => ($request->query->get('type')) ? $this->parameterService->getSocietyParameters() : null,
  63.             'type' => $customerType
  64.         ]);
  65.     }
  66.     /**
  67.      * Confirmation page after a user has requested a password reset.
  68.      */
  69.     #[Route('/check-email'name'app_check_email')]
  70.     public function checkEmail(): Response
  71.     {
  72.         // Generate a fake token if the user does not exist or someone hit this page directly.
  73.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  74.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  75.         }
  76.         return $this->render('security/reset_password/check_email.html.twig', [
  77.             'resetToken' => $resetToken,
  78.             'society'           => $this->parameterService->getSocietyParameters(),
  79.             'social_networks'   => $this->frontService->getSocialNetworks(),
  80.             'agencies'          => $this->frontService->getAgencies(),
  81.             'currencies'        => $this->frontService->getCurrencies(),
  82.         ]);
  83.     }
  84.     /**
  85.      * Validates and process the reset URL that the user clicked in their email.
  86.      */
  87.     #[Route('/reset/{token}'name'app_reset_password')]
  88.     public function reset(
  89.         Request                     $request,
  90.         UserPasswordHasherInterface $passwordHasher,
  91.         TranslatorInterface         $translator,
  92.         string                      $token null): Response
  93.     {
  94.         if ($token) {
  95.             // We store the token in session and remove it from the URL, to avoid the URL being
  96.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  97.             $this->storeTokenInSession($token);
  98.             return $this->redirectToRoute('app_reset_password');
  99.         }
  100.         $token $this->getTokenFromSession();
  101.         if (null === $token) {
  102.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  103.         }
  104.         try {
  105.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  106.         } catch (ResetPasswordExceptionInterface $e) {
  107.             $this->addFlash('reset_password_error'sprintf(
  108.                 '%s - %s',
  109.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  110.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  111.             ));
  112.             return $this->redirectToRoute('app_forgot_password_request', ['type' => 'btoc']);
  113.         }
  114.         // The token is valid; allow the user to change their password.
  115.         $form $this->createForm(ChangePasswordFormType::class, $user);
  116.         $form->handleRequest($request);
  117.         if ($form->isSubmitted() && $form->isValid()) {
  118.             // A password reset token should be used only once, remove it.
  119.             $this->resetPasswordHelper->removeResetRequest($token);
  120.             // Encode(hash) the plain password, and set it.
  121.             $encodedPassword $passwordHasher->hashPassword(
  122.                 $user,
  123.                 $form->get('password')->getData()
  124.             );
  125.             $user->setPassword($encodedPassword);
  126.             $this->entityManager->persist($user);
  127.             $this->entityManager->flush();
  128.             // The session is cleaned up after the password has been changed.
  129.             //  $this->cleanSessionAfterReset();
  130.             $message $this->translator->trans(
  131.                 'Pages.ResetPassword.Alerts.Success', [], 'messages_front'
  132.             );
  133.             $this->addFlash('success'$message);
  134.             return $this->redirectToRoute("front_info_message");
  135.         }
  136.         return $this->render('security/reset_password/reset.html.twig', [
  137.             'resetForm' => $form->createView(),
  138.             'society'           => $this->parameterService->getSocietyParameters(),
  139.             'social_networks'   => $this->frontService->getSocialNetworks(),
  140.             'agencies'          => $this->frontService->getAgencies(),
  141.             'currencies'        => $this->frontService->getCurrencies(),
  142.         ]);
  143.     }
  144.     private function processSendingPasswordResetEmail(string $emailAddressstring $customerType): RedirectResponse
  145.     {
  146.         $user $this->entityManager->getRepository(User::class)->findOneBy(['email' => $emailAddress]);
  147.         // Do not reveal whether a user account was found or not.
  148.         if (!$user) {
  149.             $this->addFlash('reset_password_error''email introuvable');
  150.             return $this->redirectToRoute('app_forgot_password_request', ['type' => $customerType]);
  151.         }
  152.         try {
  153.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  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.             $this->addFlash('reset_password_error'sprintf(
  159.                 '%s - %s',
  160.                 $this->translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  161.                 $this->translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  162.             ));
  163.             return $this->redirectToRoute('app_forgot_password_request', ['type' => $customerType]);
  164.         }
  165.         $htmlContent $this->renderView('security/reset_password/email.html.twig', ['resetToken' => $resetToken]);
  166.         $email $this->emailService->composeMail(
  167.             $this->parameterService->getEmailSocietyAddress(Email::ACCOUNT),
  168.             $user->getEmail(),
  169.             "Reset password",
  170.             $htmlContent,
  171.         );
  172.         try {
  173.             $this->emailService->send($email);
  174.             $email->setState(true);
  175.         } catch (Exception $e) {
  176.             $this->addFlash('reset_password_error'$e->getMessage());
  177.             return $this->redirectToRoute('app_forgot_password_request');
  178.         }
  179.         // Store the token object in session for retrieval in check-email route.
  180.         $this->setTokenObjectInSession($resetToken);
  181.         return $this->redirectToRoute('app_check_email');
  182.     }
  183.     #[Route('/change-password'name'app_front_userarea_change_password'methods: ['GET''POST'])]
  184.     public function changePassword(
  185.         Request $request,
  186.         UserRepository $userRepository,
  187.         UserPasswordHasherInterface $userPasswordHasher
  188.     ): Response
  189.     {
  190.         $user $this->getUser();
  191.         $customer $user->getCustomer();
  192.         $form $this->createForm(ChangePasswordFormType::class, $user);
  193.         $form->handleRequest($request);
  194.         if ($form->isSubmitted() && $form->isValid()) {
  195.             $user->setPassword(
  196.                 $userPasswordHasher->hashPassword(
  197.                     $user,
  198.                     $form->get('password')->getData()
  199.                 )
  200.             );
  201.             $userRepository->add($usertrue);
  202.             $this->addFlash('success''Password is changed');
  203.             return $this->redirectToRoute('app_front_userarea_change_password', [], Response::HTTP_SEE_OTHER);
  204.         }
  205.         $activatedModules $this->parameterService->getActiveModules();
  206.         return $this->renderForm('front/userarea/btoc/change-password.html.twig', [
  207.             'customer' => $customer,
  208.             'form' => $form,
  209.             'activatedModules' => $activatedModules,
  210.             'currentRoute' => $request->attributes->get('_route'),
  211.             'society'           => $this->parameterService->getSocietyParameters(),
  212.             'social_networks'   => $this->frontService->getSocialNetworks(),
  213.             'agencies'          => $this->frontService->getAgencies(),
  214.             'currencies'        => $this->frontService->getCurrencies()
  215.         ]);
  216.     }
  217. }