src/Controller/Security/ResetPasswordController.php line 75

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