src/Controller/SecurityController.php line 156

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