src/Controller/SecurityController.php line 244

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Client;
  4. use App\Entity\Company;
  5. use App\Entity\MarketplaceReservation;
  6. use App\Entity\Specialist;
  7. use App\Entity\User;
  8. use App\Form\Client\CompanyCodeType;
  9. use App\Form\Company\ClientType;
  10. use App\Form\Marketplace\CompanyMarketplaceType;
  11. use App\Form\SpecialistLightType;
  12. use App\Form\SpecialistType;
  13. use App\Repository\CompanyRepository;
  14. use App\Repository\SpecialistRepository;
  15. use App\Repository\UserRepository;
  16. use App\Security\ClientAuthenticator;
  17. use App\Security\ExternalClientProvider;
  18. use App\Security\SpecialistAuthenticator;
  19. use App\Service\ApiService;
  20. use App\Service\EmailService;
  21. use App\Service\OktaApiService;
  22. use Doctrine\ORM\EntityManagerInterface;
  23. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  24. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  25. use Symfony\Component\HttpFoundation\JsonResponse;
  26. use Symfony\Component\HttpFoundation\RedirectResponse;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\HttpFoundation\Response;
  29. use Symfony\Component\Routing\Annotation\Route;
  30. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  31. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  32. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  33. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  34. use Symfony\Component\Uid\Uuid;
  35. class SecurityController extends AbstractController
  36. {
  37.     /**
  38.      * @var emailService
  39.      */
  40.     private $emailService;
  41.     public function __construct(EmailService $emailService)
  42.     {
  43.         $this->emailService $emailService;
  44.     }
  45.     /**
  46.      * @Route("/admin/login", name="app_login_admin")
  47.      */
  48.     public function loginAdmin(AuthenticationUtils $authenticationUtils): Response
  49.     {
  50.         if ($this->getUser()) {
  51.              return $this->redirectToRoute('admin_dashboard');
  52.         }
  53.         // get the login error if there is one
  54.         $error $authenticationUtils->getLastAuthenticationError();
  55.         // last username entered by the user
  56.         $lastUsername $authenticationUtils->getLastUsername();
  57.         return $this->render('security/login_admin.html.twig', ['last_username' => $lastUsername'error' => $error]);
  58.     }
  59.     /**
  60.      * @Route("/admin/logout", name="app_admin_logout")
  61.      */
  62.     public function logoutAdmin(): void
  63.     {
  64.     }
  65.     /**
  66.      * @Route("/entreprise/logout", name="app_company_logout")
  67.      */
  68.     public function logoutCompany(): void
  69.     {
  70.     }
  71.     /**
  72.      * @Route("/entreprise/login", name="app_login_company")
  73.      */
  74.     public function loginCompany(AuthenticationUtils $authenticationUtils): Response
  75.     {
  76.         if ($this->getUser()) {
  77.             return $this->redirectToRoute('company_dashboard');
  78.         }
  79.         // get the login error if there is one
  80.         $error $authenticationUtils->getLastAuthenticationError();
  81.         // last username entered by the user
  82.         $lastUsername $authenticationUtils->getLastUsername();
  83.         return $this->render('security/login_company.html.twig', ['last_username' => $lastUsername'error' => $error]);
  84.     }
  85.     /**
  86.      * @Route("/equipe/logout", name="app_client_logout")
  87.      */
  88.     public function logoutClient(): void
  89.     {
  90.     }
  91.     /**
  92.      * @Route("/equipe/login-api", name="client_login", methods={"GET"})
  93.      * @return JsonResponse|RedirectResponse
  94.      */
  95.     public function clientLogin(Request $requestExternalClientProvider $clientProviderApiService $apiService,
  96.                                 EventDispatcherInterface $dispatcherTokenStorageInterface $tokenStorage)
  97.     {
  98.         if (!$apiService->checkAuthorisation($request)) {
  99.             return new JsonResponse("Unauthorised"403);
  100.         }
  101.         $urlToken $request->get('token');
  102.         try {
  103.             $user $clientProvider->loadUserByToken($urlToken);
  104.             $token = new UsernamePasswordToken($user'client'$user->getRoles());
  105.             $tokenStorage->setToken($token);
  106.             $event = new InteractiveLoginEvent($request$token);
  107.             $dispatcher->dispatch($event"security.interactive_login");
  108.         }catch (\Exception $e){
  109.             return $this->redirectToRoute(ClientAuthenticator::LOGIN_ROUTE);
  110.         }
  111.         return $this->redirectToRoute('client_dashboard');
  112.     }
  113.     /**
  114.      * @Route("/equipe/login", name="app_login_client")
  115.      */
  116.     public function loginClient(Request $requestAuthenticationUtils $authenticationUtils): Response
  117.     {
  118.         $byPassSaml $request->get('bypass'false);
  119.         if ($this->getUser()) {
  120.             return $this->redirectToRoute('client_dashboard');
  121.         }
  122.         if ($request->server->get('HTTP_HOST') == $this->getParameter('saml_redirect_domain') && !$byPassSaml){
  123.             return $this->redirectToRoute('saml_login');
  124.         }
  125.         // get the login error if there is one
  126.         $error $authenticationUtils->getLastAuthenticationError();
  127.         // last username entered by the user
  128.         $lastUsername $authenticationUtils->getLastUsername();
  129.         return $this->render('security/login_client.html.twig', ['last_username' => $lastUsername'error' => $error]);
  130.     }
  131.     /**
  132.      * @Route("/equipe/login/premiere-connexion", name="app_login_company_code")
  133.      */
  134.     public function loginByCompanyCode(Request $requestCompanyRepository $companyRepo): Response
  135.     {
  136.         $form $this->createForm(CompanyCodeType::class);
  137.         $form->handleRequest($request);
  138.         if ($form->isSubmitted() && $form->isValid()) {
  139.             $company $companyRepo->findOneBy(
  140.                 [
  141.                     'companyCode' => $form->getData()['companyCode']
  142.                 ]
  143.             );
  144.             
  145.             if ($company instanceof Company && $company->getCompanyCode() == $form->getData()['companyCode']) {
  146.                 return $this->redirectToRoute('app_create_user_company_code', ['companyCode' => $company->getCompanyCode()]);
  147.             }else{
  148.                 $error true;
  149.                 $this->addFlash('errorGlobal'"Aucune entreprise trouvée");
  150.                 return $this->redirectToRoute('app_login_company_code', ['error' => $error]);
  151.             }
  152.         }
  153.         return $this->render('security/login_company_code.html.twig', [
  154.             'codeForm' => $form->createView(),
  155.         ]);
  156.     }
  157.     /**
  158.      * @Route("/equipe/login/code/{companyCode}", name="app_create_user_company_code")
  159.      */
  160.     public function createUserByCompanyCode(Request $requeststring $companyCodeEntityManagerInterface $entityManager,
  161.                                             EventDispatcherInterface $dispatcherTokenStorageInterface $tokenStorageCompanyRepository $companyRepo): Response
  162.     {
  163.         $company $companyRepo->findOneBy(
  164.             [
  165.                 'companyCode' => $companyCode
  166.             ]
  167.         );
  168.         if ($company == null || $companyCode !== $company->getCompanyCode()) {
  169.             $error true;
  170.             $this->addFlash('errorGlobal'"Aucune entreprise trouvée");
  171.             return $this->redirectToRoute('app_login_company_code', ['error' => $error]);
  172.         }
  173.         $client = new Client();
  174.         $client->setCompany($company);
  175.         $form $this->createForm(ClientType::class, $client);
  176.         $form->handleRequest($request);
  177.         if ($form->isSubmitted() && $form->isValid()) {
  178.             $plainPassword "empty";
  179.             $client->getUser()->setName((string) $client);
  180.             $client->getUser()->setActive(true);
  181.             $client->setIsCgu(true);
  182.             $entityManager->persist($client);
  183.             $entityManager->flush();
  184.             $entityManager->refresh($client);
  185.             try {
  186.                 $user $client->getUser();
  187.                 $token = new UsernamePasswordToken($user'client'$user->getRoles());
  188.                 $tokenStorage->setToken($token);
  189.                 $event = new InteractiveLoginEvent($request$token);
  190.                 $dispatcher->dispatch($event"security.interactive_login");
  191.                 $this->emailService->sendNewClientCreatedEmail($client$plainPassword);
  192.             }catch (\Exception $e){
  193.                 $this->addFlash('errorGlobal''Une erreur est survenue');
  194.                 return $this->redirectToRoute(ClientAuthenticator::LOGIN_ROUTE);
  195.             }
  196.             return $this->redirectToRoute('client_dashboard');
  197.         }
  198.         return $this->render('security/create_user_company_code.html.twig', [
  199.             'regForm' => $form->createView(),
  200.         ]);
  201.     }
  202.     /**
  203.      * @Route("/expert/login", name="app_login_specialist")
  204.      */
  205.     public function loginSpecialist(AuthenticationUtils $authenticationUtils): Response
  206.     {
  207.         if ($this->getUser()) {
  208.             return $this->redirectToRoute('specialist_dashboard');
  209.         }
  210.         // get the login error if there is one
  211.         $error $authenticationUtils->getLastAuthenticationError();
  212.         // last username entered by the user
  213.         $lastUsername $authenticationUtils->getLastUsername();
  214.         return $this->render('security/login_specialist.html.twig', ['last_username' => $lastUsername'error' => $error]);
  215.     }
  216.     /**
  217.      * @Route("/login", name="app_login_marketplace", host="%MARKETPLACE_HOST%")
  218.      */
  219.     public function loginMarketplace(AuthenticationUtils $authenticationUtilsEntityManagerInterface $em): Response
  220.     {
  221.         if ($this->getUser()) {
  222.             return $this->redirectToRoute('marketplace_app_user');
  223.         }
  224.         // get the login error if there is one
  225.         $error $authenticationUtils->getLastAuthenticationError();
  226.         // last username entered by the user
  227.         $lastUsername $authenticationUtils->getLastUsername();
  228.        
  229.         return $this->render('security/login_marketplace.html.twig', ['last_username' => $lastUsername'error' => $error]);
  230.     }
  231.     /**
  232.      * @Route("/inscription", name="app_create_user_marketplace", host="%MARKETPLACE_HOST%")
  233.      */
  234.     public function createMarketplaceUser(Request $requestEntityManagerInterface $emEventDispatcherInterface $dispatcherTokenStorageInterface $tokenStorageCompanyRepository $companyRepo): Response
  235.     {
  236.         $company = new Company;
  237.         $company->setForceSegmentation(false);
  238.         $form $this->createForm(CompanyMarketplaceType::class, $company, ['newCompany' => true]);
  239.         $form->handleRequest($request);
  240.         if ($form->isSubmitted() && $form->isValid()) {
  241.             try {
  242.                 $user $company->getUser();
  243.                 $user->setCompany($company);
  244.                 $em->persist($user);
  245.                 $em->persist($company);
  246.                 $em->flush();
  247.                 $this->addFlash('success'"Compte crée avec succès");
  248.                 $token = new UsernamePasswordToken($user'marketplace'$user->getRoles());
  249.                 $tokenStorage->setToken($token);
  250.                 $event = new InteractiveLoginEvent($request$token);
  251.                 $dispatcher->dispatch($event"security.interactive_login");
  252.                 $this->emailService->sendNewMarketplaceCompanyCreatedEmail($company);
  253.                 if (!empty($request->getSession()->get('RESERVATION_ID'))) {
  254.                     $marketplaceReservation $em->getRepository(MarketplaceReservation::class)->find($request->getSession()->get('RESERVATION_ID'));
  255.                     return $this->redirectToRoute('marketplace_app_reservation_recap', ['marketplaceReservationId' => $marketplaceReservation->getId()]);
  256.                 }
  257.                 return $this->redirectToRoute('marketplace_app_user');
  258.             } catch (\Throwable $th) {
  259.                 //throw $th;
  260.                 $this->addFlash('accountError''Une erreur est survenue');
  261.             }
  262.         }
  263.         return $this->render('security/create_user_marketplace.html.twig', [
  264.             'form' => $form->createView()
  265.         ]);
  266.     }
  267.      /**
  268.      * @Route("/logout", name="app_logout_marketplace", host="%MARKETPLACE_HOST%")
  269.      */
  270.     public function logoutMarketplace(): void
  271.     {
  272.     }
  273.      /**
  274.      * @Route("/expert/login/creation-de-compte", name="app_create_specialist")
  275.      */
  276.     public function specialistUserCreation(Request $requestEntityManagerInterface $entityManagerSpecialistRepository $specialistRepo ): Response
  277.     {
  278.       
  279.         $specialist = new Specialist();
  280.         $options = [
  281.             'pwd_required' => true,
  282.             'specialist_reg' => true,
  283.         ];
  284.         $form $this->createForm(SpecialistLightType::class, $specialist$options);
  285.         $form->handleRequest($request);
  286.         if ($form->isSubmitted() && $form->isValid()) {
  287.             $existingSpecialist $specialistRepo->findOneBy(
  288.                 [
  289.                     'tel' => $specialist->getTel(),
  290.                     ]
  291.                 );
  292.             if ($existingSpecialist == null) {
  293.                 $validUuid Uuid::v1();
  294.                 $specialist->setIsVirtualEvent(true);
  295.                 $specialist->getUser()->setActive(true);
  296.                 $specialist->setSpecialistTags([]);
  297.                 $specialist->setUuid($validUuid);
  298.                 $specialist->setStatus(Specialist::STATUS_WAITING_MAIL_CONFIRMATION);
  299.                 try {
  300.                     $entityManager->persist($specialist);
  301.                     $entityManager->flush();
  302.                     $entityManager->refresh($specialist);
  303.                     $this->emailService->sendSpecialistAccountConfirmation($specialist);
  304.                     $this->addFlash('success''Un mail de confirmation vient de vous être envoyé. Afin de finaliser votre inscription veuillez cliquer sur le lien présent dans ce mail. A très vite sur ULTEAM pour découvrir nos opportunités');
  305.                     return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  306.                 }catch (\Exception $e){
  307.                     $this->addFlash('errorGlobal''Une erreur est survenue');
  308.                     return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  309.                 }
  310.             }elseif ($existingSpecialist != null && $existingSpecialist->getStatus() == Specialist::STATUS_REFUSED) {
  311.                 $this->addFlash('errorGlobal''Désolé mais la connexion à ton compte n\'est pas possible actuellement');
  312.                 return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  313.             }else {
  314.                 $this->addFlash('errorGlobal''Un expert avec ce numero de téléphone existe déjà');
  315.                 return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  316.             }
  317.         }
  318.         return $this->render('security/create_specialist.html.twig', [
  319.             'regForm' => $form->createView(),
  320.         ]);
  321.     }
  322.     /**
  323.      * @Route("/expert/login/validation-compte/{specialistUuid}", name="app_validate_specialist")
  324.      */
  325.     public function expertUserValidate(Request $requestEntityManagerInterface $entityManagerSpecialistRepository $specialistRepostring $specialistUuid ): Response
  326.     {
  327.         
  328.         $specialist $specialistRepo->findOneBy([
  329.             'uuid' => $specialistUuid
  330.         ]);
  331.         if ($specialist instanceof Specialist ) {
  332.             $specialist->setStatus(Specialist::STATUS_WAITING_ULTEAM_CONFIRMATION);
  333.             $entityManager->persist($specialist);
  334.             $entityManager->flush();
  335.             $this->emailService->sendNewSpecialistNotificationToUlteam($specialist);
  336.             $this->addFlash('success''Félicitations, ton compte est à présent validé, tu peux te connecter et profiter des opportunités ULTEAM');
  337.             return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  338.         }else {
  339.             $this->addFlash('errorGlobal''Une erreur est survenue');
  340.             return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  341.         }
  342.         
  343.         return $this->render('security/create_specialist.html.twig', [
  344.         ]);
  345.     }
  346.     /**
  347.      * @Route("/expert/logout", name="app_specialist_logout")
  348.      */
  349.     public function logoutSpecialist(): void
  350.     {
  351.     }
  352. }