src/Controller/Website/Mybiz/Security/SecurityController.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Website\Mybiz\Security;
  3. use App\Data\RoleConstant;
  4. use App\Entity\Member;
  5. use App\Entity\User;
  6. use App\Form\CRM\User\Authentication\ForgetPasswordType;
  7. use App\Form\CRM\User\Authentication\ResetPasswordType;
  8. use App\Repository\UserRepository;
  9. use App\Security\Voter\CRM\CRMAccessVoter;
  10. use App\Service\Api\Mobile\JwtAuthenticator;
  11. use App\Service\Locale\LocaleProvider;
  12. use App\Service\User\UserForgotPasswordHandler;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Routing\RouterInterface;
  21. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  22. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  23. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  24. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  25. use Symfony\Contracts\Translation\TranslatorInterface;
  26. class SecurityController extends AbstractController
  27. {
  28.     private string $locale;
  29.     public function __construct(LocaleProvider $localeProvider)
  30.     {
  31.         $this->locale $localeProvider->provide();
  32.     }
  33.     /**
  34.      * @Route("/security/login", methods={"GET", "POST"}, name="mybiz_login")
  35.      */
  36.     public function login(
  37.         Request             $request,
  38.         AuthenticationUtils $authenticationUtils
  39.     ): Response
  40.     {
  41.         /** @var User|null $user */
  42.         $user $this->getUser();
  43.         if (null !== $user) {
  44.             return $this->redirectToRoute("mybiz_redirect");
  45.         }
  46.         $error $authenticationUtils->getLastAuthenticationError();
  47.         $email $request->get("email");
  48.         // last username entered by the user
  49.         $lastUsername $email ?? $authenticationUtils->getLastUsername();
  50.         return $this->render('mybiz/security/login.html.twig', [
  51.             'last_username' => $lastUsername,
  52.             'email' => $email,
  53.             'error' => $error,
  54.             'locale' => $this->locale
  55.         ]);
  56.     }
  57.     /**
  58.      * @Route("/security/redirect", methods={"GET", "POST"}, name="mybiz_redirect")
  59.      */
  60.     public function redirectMember(
  61.         Request                $request,
  62.         EntityManagerInterface $em,
  63.         RouterInterface        $router
  64.     ): Response
  65.     {
  66.         /** @var User|null $user */
  67.         $user $this->getUser();
  68.         if (null === $user) {
  69.             return $this->redirectToRoute("mybiz_login");
  70.         }
  71.         $target $request->getSession()->get("_security.futures_website.target_path");
  72.         try {
  73.             // Si l'utilisateur essaie d'aller quelque part, on le redirige vers cette route. Si aucune route ne match,
  74.             // On ne fait rien
  75.             $router->match(parse_url($targetPHP_URL_PATH));
  76.             $request->getSession()->set("_security.futures_website.target_path"null);
  77.             return $this->redirect($target);
  78.         } catch (\Throwable $e) {
  79.         }
  80.         $user->setLastLoginAt(new \DateTime());
  81.         $em->flush();
  82.         if ($this->isGranted(CRMAccessVoter::CRM_ACCESSRoleConstant::ROLE_ADMIN)) {
  83.             return $this->redirectToRoute("crm_dashboard");
  84.         }
  85.         if ($this->isGranted(CRMAccessVoter::CRM_ACCESSRoleConstant::ROLE_SUPPORT)) {
  86.             return $this->redirectToRoute("crm_member_list");
  87.         }
  88.         if ($this->isGranted(CRMAccessVoter::CRM_ACCESSRoleConstant::ROLE_EDUCATEUR)) {
  89.             return $this->redirectToRoute("crm_replay_list");
  90.         }
  91.         /** @var Member|null $member */
  92.         $member $user->getMember();
  93.         // Si le membre n'existe pas on le redirige sur /
  94.         if (null === $member) {
  95.             return $this->redirectToRoute("general_homepage");
  96.         }
  97.         if (false === $member->isAmbassador()) {
  98.             return $this->redirectToRoute("mybiz_become_ambasador");
  99.         }
  100.         if($member->isInsider()){
  101.             return $this->redirectToRoute("mybiz_v2_homepage");
  102.         }
  103.         return $this->redirect("/{$member->getPreferredLanguage()}");
  104.     }
  105.     /**
  106.      * @Route("/security/reset-password", methods={"GET", "POST"}, name="mybiz_account_reset_password")
  107.      */
  108.     public function resetPassword(
  109.         Request                        $request,
  110.         PasswordHasherFactoryInterface $encoderFactory,
  111.         EntityManagerInterface         $em,
  112.         TranslatorInterface            $translator,
  113.         TokenStorageInterface          $tokenStorage,
  114.         EventDispatcherInterface       $eventDispatcher,
  115.         UserRepository                 $userRepository
  116.     ): Response
  117.     {
  118.         $form $this->createForm(ResetPasswordType::class, null, ["locale" => $this->locale]);
  119.         $form->handleRequest($request);
  120.         if ($form->isSubmitted() && $form->isValid()) {
  121.             $datas $form->getData();
  122.             $password $datas["password"];
  123.             $confirmPassword $datas["confirmPassword"];
  124.             if ($password !== $confirmPassword) {
  125.                 $this->addFlash("warning"$translator->trans('validator.password.not_equal', [], 'validator'$this->locale));
  126.                 return $this->render('mybiz/security/reset_password.html.twig', [
  127.                     "form" => $form->createView(),
  128.                     "locale" => $this->locale
  129.                 ]);
  130.             }
  131.             $token $request->get("token");
  132.             if (empty($token)) {
  133.                 $this->addFlash("warning"$translator->trans('validator.password.token_invalid', [], 'validator'$this->locale));
  134.                 return $this->render('mybiz/security/reset_password.html.twig', [
  135.                     "form" => $form->createView(),
  136.                     "locale" => $this->locale
  137.                 ]);
  138.             }
  139.             /** @var User|null $user */
  140.             try {
  141.                 $user $userRepository->findUserByToken($token);
  142.             } catch (\Throwable $e) {
  143.                 $this->addFlash("error"$translator->trans('validator.password.token_invalid', [], 'validator'$this->locale));
  144.                 return $this->render('mybiz/security/reset_password.html.twig', [
  145.                     "form" => $form->createView(),
  146.                     "locale" => $this->locale
  147.                 ]);
  148.             }
  149.             if (null === $user) {
  150.                 $this->addFlash("warning"$translator->trans('validator.password.token_invalid', [], 'validator'$this->locale));
  151.                 return $this->render('mybiz/security/reset_password.html.twig', [
  152.                     "form" => $form->createView(),
  153.                     "locale" => $this->locale
  154.                 ]);
  155.             }
  156.             if (new \DateTime() > $user->getPasswordResetTokenExpiresAt()) {
  157.                 $this->addFlash("warning"$translator->trans('validator.password.token_invalid', [], 'validator'$this->locale));
  158.                 return $this->render('mybiz/security/reset_password.html.twig', [
  159.                     "form" => $form->createView(),
  160.                     "locale" => $this->locale
  161.                 ]);
  162.             }
  163.             $passwordEncoded $encoderFactory->getPasswordHasher($user)->hash($password$user->getSalt());
  164.             $user->setPassword($passwordEncoded);
  165.             $user->setPasswordResetToken(null);
  166.             $user->setPasswordResetTokenExpiresAt(null);
  167.             $user->setPasswordResetTokenEmailsSent(null);
  168.             $token = new UsernamePasswordToken($usernull'ofutures'$user->getRoles());
  169.             $tokenStorage->setToken($token); //now the user is logged in
  170.             //now dispatch the login event
  171.             $event = new InteractiveLoginEvent($request$token);
  172.             $eventDispatcher->dispatch($event'security.interactive_login');
  173.             $em->persist($user);
  174.             $em->flush();
  175.             $this->addFlash("success"$translator->trans("security.forget_password.success", [], "security"$this->locale));
  176.             return $this->redirectToRoute("mybiz_redirect");
  177.         }
  178.         return $this->render('mybiz/security/reset_password.html.twig', [
  179.             "form" => $form->createView(),
  180.             "locale" => $this->locale
  181.         ]);
  182.     }
  183.     /**
  184.      * @Route("/security/forget-password", methods={"GET", "POST"}, name="mybiz_forget_password")
  185.      */
  186.     public function forgetPassword(
  187.         Request                   $request,
  188.         TranslatorInterface       $translator,
  189.         UserForgotPasswordHandler $userForgotPasswordHandler,
  190.         UserRepository            $userRepository
  191.     ): Response
  192.     {
  193.         $form $this->createForm(ForgetPasswordType::class, null, ["locale" => $this->locale]);
  194.         $form->handleRequest($request);
  195.         if ($form->isSubmitted() && $form->isValid()) {
  196.             $datas $form->getData();
  197.             if (!isset($datas["email"])) {
  198.                 $this->addFlash("warning"$translator->trans("validator.user.email_invalid", [], "validator"$this->locale));
  199.                 return $this->redirectToRoute("mybiz_forget_password");
  200.             }
  201.             $user $userRepository->findOneBy([
  202.                 "email" => $datas["email"]
  203.             ]);
  204.             if (null === $user) {
  205.                 $this->addFlash("warning"$translator->trans("validator.user.email_invalid", [], "validator"$this->locale));
  206.                 return $this->redirectToRoute("mybiz_login");
  207.             }
  208.             try {
  209.                 $userForgotPasswordHandler->handle($user);
  210.             } catch (\Throwable $e) {
  211.                 return $this->render('mybiz/security/forget_password.html.twig', [
  212.                     "form" => $form->createView(),
  213.                     "locale" => $this->locale
  214.                 ]);
  215.             }
  216.             $this->addFlash("success"$translator->trans("security.forget_password.success", [], "security"$this->locale));
  217.             return $this->redirectToRoute("mybiz_login");
  218.         }
  219.         return $this->render('mybiz/security/forget_password.html.twig', [
  220.             "form" => $form->createView(),
  221.             "locale" => $this->locale
  222.         ]);
  223.     }
  224.     /**
  225.      * @Route("/security/jwt/login", methods={"GET"}, name="mybiz_jwt_login")
  226.      */
  227.     public function jwtLogin(
  228.         Request          $request,
  229.         JwtAuthenticator $jwtAuthenticator
  230.     ): Response
  231.     {
  232.         $jwt $request->get("jwt");
  233.         if (null === $jwt) {
  234.             return $this->redirectToRoute("mybiz_login");
  235.         }
  236.         if (false === $jwtAuthenticator->authenticateByJwt($jwt)) {
  237.             return $this->redirectToRoute("mybiz_login");
  238.         }
  239.         return $this->redirectToRoute("futures_homepage");
  240.     }
  241. }