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.         return $this->redirect("/{$member->getPreferredLanguage()}");
  101.     }
  102.     /**
  103.      * @Route("/security/reset-password", methods={"GET", "POST"}, name="mybiz_account_reset_password")
  104.      */
  105.     public function resetPassword(
  106.         Request                        $request,
  107.         PasswordHasherFactoryInterface $encoderFactory,
  108.         EntityManagerInterface         $em,
  109.         TranslatorInterface            $translator,
  110.         TokenStorageInterface          $tokenStorage,
  111.         EventDispatcherInterface       $eventDispatcher,
  112.         UserRepository                 $userRepository
  113.     ): Response
  114.     {
  115.         $form $this->createForm(ResetPasswordType::class, null, ["locale" => $this->locale]);
  116.         $form->handleRequest($request);
  117.         if ($form->isSubmitted() && $form->isValid()) {
  118.             $datas $form->getData();
  119.             $password $datas["password"];
  120.             $confirmPassword $datas["confirmPassword"];
  121.             if ($password !== $confirmPassword) {
  122.                 $this->addFlash("warning"$translator->trans('validator.password.not_equal', [], 'validator'$this->locale));
  123.                 return $this->render('mybiz/security/reset_password.html.twig', [
  124.                     "form" => $form->createView(),
  125.                     "locale" => $this->locale
  126.                 ]);
  127.             }
  128.             $token $request->get("token");
  129.             if (empty($token)) {
  130.                 $this->addFlash("warning"$translator->trans('validator.password.token_invalid', [], 'validator'$this->locale));
  131.                 return $this->render('mybiz/security/reset_password.html.twig', [
  132.                     "form" => $form->createView(),
  133.                     "locale" => $this->locale
  134.                 ]);
  135.             }
  136.             /** @var User|null $user */
  137.             try {
  138.                 $user $userRepository->findUserByToken($token);
  139.             } catch (\Throwable $e) {
  140.                 $this->addFlash("error"$translator->trans('validator.password.token_invalid', [], 'validator'$this->locale));
  141.                 return $this->render('mybiz/security/reset_password.html.twig', [
  142.                     "form" => $form->createView(),
  143.                     "locale" => $this->locale
  144.                 ]);
  145.             }
  146.             if (null === $user) {
  147.                 $this->addFlash("warning"$translator->trans('validator.password.token_invalid', [], 'validator'$this->locale));
  148.                 return $this->render('mybiz/security/reset_password.html.twig', [
  149.                     "form" => $form->createView(),
  150.                     "locale" => $this->locale
  151.                 ]);
  152.             }
  153.             if (new \DateTime() > $user->getPasswordResetTokenExpiresAt()) {
  154.                 $this->addFlash("warning"$translator->trans('validator.password.token_invalid', [], 'validator'$this->locale));
  155.                 return $this->render('mybiz/security/reset_password.html.twig', [
  156.                     "form" => $form->createView(),
  157.                     "locale" => $this->locale
  158.                 ]);
  159.             }
  160.             $passwordEncoded $encoderFactory->getPasswordHasher($user)->hash($password$user->getSalt());
  161.             $user->setPassword($passwordEncoded);
  162.             $user->setPasswordResetToken(null);
  163.             $user->setPasswordResetTokenExpiresAt(null);
  164.             $user->setPasswordResetTokenEmailsSent(null);
  165.             $token = new UsernamePasswordToken($usernull'ofutures'$user->getRoles());
  166.             $tokenStorage->setToken($token); //now the user is logged in
  167.             //now dispatch the login event
  168.             $event = new InteractiveLoginEvent($request$token);
  169.             $eventDispatcher->dispatch($event'security.interactive_login');
  170.             $em->persist($user);
  171.             $em->flush();
  172.             $this->addFlash("success"$translator->trans("security.forget_password.success", [], "security"$this->locale));
  173.             return $this->redirectToRoute("mybiz_redirect");
  174.         }
  175.         return $this->render('mybiz/security/reset_password.html.twig', [
  176.             "form" => $form->createView(),
  177.             "locale" => $this->locale
  178.         ]);
  179.     }
  180.     /**
  181.      * @Route("/security/forget-password", methods={"GET", "POST"}, name="mybiz_forget_password")
  182.      */
  183.     public function forgetPassword(
  184.         Request                   $request,
  185.         TranslatorInterface       $translator,
  186.         UserForgotPasswordHandler $userForgotPasswordHandler,
  187.         UserRepository            $userRepository
  188.     ): Response
  189.     {
  190.         $form $this->createForm(ForgetPasswordType::class, null, ["locale" => $this->locale]);
  191.         $form->handleRequest($request);
  192.         if ($form->isSubmitted() && $form->isValid()) {
  193.             $datas $form->getData();
  194.             if (!isset($datas["email"])) {
  195.                 $this->addFlash("warning"$translator->trans("validator.user.email_invalid", [], "validator"$this->locale));
  196.                 return $this->redirectToRoute("mybiz_forget_password");
  197.             }
  198.             $user $userRepository->findOneBy([
  199.                 "email" => $datas["email"]
  200.             ]);
  201.             if (null === $user) {
  202.                 $this->addFlash("warning"$translator->trans("validator.user.email_invalid", [], "validator"$this->locale));
  203.                 return $this->redirectToRoute("mybiz_login");
  204.             }
  205.             try {
  206.                 $userForgotPasswordHandler->handle($user);
  207.             } catch (\Throwable $e) {
  208.                 return $this->render('mybiz/security/forget_password.html.twig', [
  209.                     "form" => $form->createView(),
  210.                     "locale" => $this->locale
  211.                 ]);
  212.             }
  213.             $this->addFlash("success"$translator->trans("security.forget_password.success", [], "security"$this->locale));
  214.             return $this->redirectToRoute("mybiz_login");
  215.         }
  216.         return $this->render('mybiz/security/forget_password.html.twig', [
  217.             "form" => $form->createView(),
  218.             "locale" => $this->locale
  219.         ]);
  220.     }
  221.     /**
  222.      * @Route("/security/jwt/login", methods={"GET"}, name="mybiz_jwt_login")
  223.      */
  224.     public function jwtLogin(
  225.         Request          $request,
  226.         JwtAuthenticator $jwtAuthenticator
  227.     ): Response
  228.     {
  229.         $jwt $request->get("jwt");
  230.         if (null === $jwt) {
  231.             return $this->redirectToRoute("mybiz_login");
  232.         }
  233.         if (false === $jwtAuthenticator->authenticateByJwt($jwt)) {
  234.             return $this->redirectToRoute("mybiz_login");
  235.         }
  236.         return $this->redirectToRoute("futures_homepage");
  237.     }
  238. }