src/Controller/ResetPasswordController.php line 45

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 Doctrine\ORM\EntityManagerInterface;
  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\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Routing\Matcher\Dumper\StaticPrefixCollection;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  19. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  21. class ResetPasswordController extends AbstractController
  22. {
  23.     use ResetPasswordControllerTrait;
  24.     private $resetPasswordHelper;
  25.     private $entityManager;
  26.     private $hasher;
  27.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerUserPasswordHasherInterface $hasher)
  28.     {
  29.         $this->resetPasswordHelper $resetPasswordHelper;
  30.         $this->entityManager $entityManager;
  31.         $this->hasher $hasher;
  32.     }
  33.     /**
  34.      * Display & process form to request a password reset.
  35.      *
  36.      * @Route("/{slug}/reset-password", name="app_forgot_password_request")
  37.      */
  38.     public function resetPwdrequest(Request $requestMailerInterface $mailerTranslatorInterface $translator,string $slug): 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.                 $slug
  48.             );
  49.         }
  50.         $template 'reset_password/front/request.html.twig';
  51.         if ($slug == "client") {
  52.             $template 'reset_password/v2/request.html.twig';
  53.         }
  54.         return $this->render($template, [
  55.             'requestForm' => $form->createView(),
  56.             'slug' => $slug
  57.         ]);
  58.     }
  59.     /**
  60.      * Confirmation page after a user has requested a password reset.
  61.      *
  62.      * @Route("/{slug}/check-email", name="app_check_email")
  63.      */
  64.     public function checkEmail(string $slug): 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.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  70.         }
  71.         $slug str_replace("specialist""expert"$slug);
  72.         $template 'reset_password/front/check_email.html.twig';
  73.         if ($slug == "client") {
  74.             $template 'reset_password/v2/check_email.html.twig';
  75.         }
  76.         return $this->render($template, [
  77.             'resetToken' => $resetToken,
  78.             'slug' => $slug
  79.         ]);
  80.     }
  81.     /**
  82.      * Validates and process the reset URL that the user clicked in their email.
  83.      *
  84.      * @Route("/{slug}/reset/{token}", name="app_reset_password")
  85.      */
  86.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasher,
  87.                           TranslatorInterface $translatorstring $slugstring $token null): Response
  88.     {
  89.         if ($token) {
  90.             // We store the token in session and remove it from the URL, to avoid the URL being
  91.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  92.             $this->storeTokenInSession($token);
  93.             return $this->redirectToRoute('app_reset_password', ['slug' => $slug]);
  94.         }
  95.         $token $this->getTokenFromSession();
  96.         if (null === $token) {
  97.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  98.         }
  99.         $prefix 'front';
  100.         $returnPage 'app_login_admin';
  101.         try {
  102.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  103.             if ($user->hasRole(User::ROLE_CLIENT)) {
  104.                 $prefix "front";
  105.                 $returnPage 'app_login_client';
  106.             } elseif ($user->hasRole(User::ROLE_SPECIALIST)) {
  107.                 $prefix "front";
  108.                 $returnPage 'app_login_specialist';
  109.             } elseif ($user->hasRole(User::ROLE_COMPANY)) {
  110.                 $prefix "front";
  111.                 $returnPage 'app_login_company';
  112.             }
  113.         } catch (ResetPasswordExceptionInterface $e) {
  114.             $this->addFlash('reset_password_error'sprintf(
  115.                 '%s - %s',
  116.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  117.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  118.             ));
  119.             return $this->redirectToRoute('app_forgot_password_request');
  120.         }
  121.         // The token is valid; allow the user to change their password.
  122.         $form $this->createForm(ChangePasswordFormType::class);
  123.         $form->handleRequest($request);
  124.         $prefix 'front';
  125.         $returnPage 'app_login_admin';
  126.         if ($user->hasRole(User::ROLE_CLIENT)) {
  127.             $prefix "v2";
  128.             $returnPage 'app_login_client';
  129.         } elseif ($user->hasRole(User::ROLE_SPECIALIST)) {
  130.             $prefix "front";
  131.             $returnPage 'app_login_specialist';
  132.         } elseif ($user->hasRole(User::ROLE_COMPANY)) {
  133.             $prefix "front";
  134.             $returnPage 'app_login_company';
  135.         }
  136.         if ($form->isSubmitted() && $form->isValid()) {
  137.             try {
  138.                 // Encode(hash) the plain password, and set it.
  139.                 $user->setPassword($this->hasher->hashPassword($user$form->get('plainPassword')->getData()));
  140.                 $this->entityManager->persist($user);
  141.                 $this->entityManager->flush();
  142.                 // A password reset token should be used only once, remove it.
  143.                 $this->resetPasswordHelper->removeResetRequest($token);
  144.                 // The session is cleaned up after the password has been changed.
  145.                 $this->cleanSessionAfterReset();
  146.                 $this->addFlash("success""Mot de passe modifié");
  147.             } catch (\Throwable $th) {
  148.                 throw $th;
  149.             }
  150.             return $this->redirectToRoute($returnPage);
  151.         }
  152.         
  153.         return $this->render("reset_password/$prefix/reset.html.twig", [
  154.             'resetForm' => $form->createView(),
  155.             'slug' => $slug
  156.         ]);
  157.     }
  158.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translatorstring $slug): RedirectResponse
  159.     {
  160.         $slug str_replace("expert""specialist"$slug);
  161.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  162.             'email' => $emailFormData,
  163.             'category' => $slug
  164.         ]);
  165.         
  166.         $slug str_replace("specialist""expert"$slug);
  167.         $redirect $this->redirectToRoute('app_check_email', ['slug' => $slug]);
  168.         // if (in_array($slug, [User::GROUP_ADMIN])) {
  169.         //     $redirect = $this->redirectToRoute('app_check_email_backoffice', [
  170.         //         'slug' => $slug
  171.         //     ]);
  172.         // }
  173.         // Do not reveal whether a user account was found or not.
  174.         if (!$user) {
  175.             return $redirect;
  176.         }
  177.         try {
  178.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  179.         } catch (ResetPasswordExceptionInterface $e) {
  180.             return $redirect;
  181.         }
  182.         $email = (new TemplatedEmail())
  183.             ->from(new Address('hello@ulteam.app''ULTEAM'))
  184.             ->to($user->getEmail())
  185.             ->subject('Demande de reinitialisation de mot de passe')
  186.             ->htmlTemplate('reset_password/front/email.html.twig')
  187.             ->context([
  188.                 'resetToken' => $resetToken,
  189.                 'slug' => $slug
  190.             ]);
  191.         $mailer->send($email);
  192.         // Store the token object in session for retrieval in check-email route.
  193.         $this->setTokenObjectInSession($resetToken);
  194.         return $redirect;
  195.     }
  196. }