src/Controller/SecurityController.php line 150

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 $emailService, UserPasswordHasherInterface $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 $request, ExternalClientProvider $clientProvider, ApiService $apiService,
  96.                                 EventDispatcherInterface $dispatcher, TokenStorageInterface $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 $request, AuthenticationUtils $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 $request, CompanyRepository $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 $request, string $companyCode, EntityManagerInterface $entityManager,
  163.                                             EventDispatcherInterface $dispatcher, TokenStorageInterface $tokenStorage, CompanyRepository $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.             // La page affiche « En validant ce formulaire, je déclare avoir lu les CGU » : acceptation de la version courante
  195.             $client->acceptCgu($this->getParameter('moderation.cgu_version'), new \DateTime());
  196.             $entityManager->persist($client);
  197.             $entityManager->flush();
  198.             $entityManager->refresh($client);
  199.             try {
  200.                 $user = $client->getUser();
  201.                 $token = new UsernamePasswordToken($user, 'client', $user->getRoles());
  202.                 $tokenStorage->setToken($token);
  203.                 $event = new InteractiveLoginEvent($request, $token);
  204.                 $dispatcher->dispatch($event, "security.interactive_login");
  205.                 $this->emailService->sendNewClientCreatedEmail($client, $plainPassword);
  206.             }catch (\Exception $e){
  207.                 $this->addFlash('errorGlobal', 'Une erreur est survenue');
  208.                 return $this->redirectToRoute(ClientAuthenticator::LOGIN_ROUTE);
  209.             }
  210.             return $this->redirectToRoute('client_first_connection', ['step' => 1]);
  211.         }
  212.         return $this->render('security/v2/create_user_company_code.html.twig', [
  213.             'regForm' => $form->createView(),
  214.         ]);
  215.     }
  216.     /**
  217.      * @Route("/expert/login", name="app_login_specialist")
  218.      */
  219.     public function loginSpecialist(AuthenticationUtils $authenticationUtils): Response
  220.     {
  221.         if ($this->getUser()) {
  222.             return $this->redirectToRoute('specialist_dashboard');
  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.         return $this->render('security/login_specialist.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
  229.     }
  230.     /**
  231.      * @Route("/login", name="app_login_marketplace", host="%MARKETPLACE_HOST%")
  232.      */
  233.     public function loginMarketplace(AuthenticationUtils $authenticationUtils, EntityManagerInterface $em): Response
  234.     {
  235.         if ($this->getUser()) {
  236.             return $this->redirectToRoute('marketplace_app_user');
  237.         }
  238.         // get the login error if there is one
  239.         $error = $authenticationUtils->getLastAuthenticationError();
  240.         // last username entered by the user
  241.         $lastUsername = $authenticationUtils->getLastUsername();
  242.        
  243.         return $this->render('security/login_marketplace.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
  244.     }
  245.     /**
  246.      * @Route("/inscription", name="app_create_user_marketplace", host="%MARKETPLACE_HOST%")
  247.      */
  248.     public function createMarketplaceUser(Request $request, EntityManagerInterface $em, EventDispatcherInterface $dispatcher, TokenStorageInterface $tokenStorage, CompanyRepository $companyRepo): Response
  249.     {
  250.         $company = new Company;
  251.         $company->setForceSegmentation(false);
  252.         $form = $this->createForm(CompanyMarketplaceType::class, $company, ['newCompany' => true]);
  253.         $form->handleRequest($request);
  254.         if ($form->isSubmitted() && $form->isValid()) {
  255.             try {
  256.                 $user = $company->getUser();
  257.                 $user->setCompany($company);
  258.                 $em->persist($user);
  259.                 $em->persist($company);
  260.                 $em->flush();
  261.                 $this->addFlash('success', "Compte crée avec succès");
  262.                 $token = new UsernamePasswordToken($user, 'marketplace', $user->getRoles());
  263.                 $tokenStorage->setToken($token);
  264.                 $event = new InteractiveLoginEvent($request, $token);
  265.                 $dispatcher->dispatch($event, "security.interactive_login");
  266.                 $this->emailService->sendNewMarketplaceCompanyCreatedEmail($company);
  267.                 if (!empty($request->getSession()->get('RESERVATION_ID'))) {
  268.                     $marketplaceReservation = $em->getRepository(MarketplaceReservation::class)->find($request->getSession()->get('RESERVATION_ID'));
  269.                     return $this->redirectToRoute('marketplace_app_reservation_recap', ['marketplaceReservationId' => $marketplaceReservation->getId()]);
  270.                 }
  271.                 return $this->redirectToRoute('marketplace_app_user');
  272.             } catch (\Throwable $th) {
  273.                 //throw $th;
  274.                 $this->addFlash('accountError', 'Une erreur est survenue');
  275.             }
  276.         }
  277.         return $this->render('security/create_user_marketplace.html.twig', [
  278.             'form' => $form->createView()
  279.         ]);
  280.     }
  281.      /**
  282.      * @Route("/logout", name="app_logout_marketplace", host="%MARKETPLACE_HOST%")
  283.      */
  284.     public function logoutMarketplace(): void
  285.     {
  286.     }
  287.      /**
  288.      * @Route("/expert/login/creation-de-compte", name="app_create_specialist")
  289.      */
  290.     public function specialistUserCreation(Request $request, EntityManagerInterface $entityManager, SpecialistRepository $specialistRepo ): Response
  291.     {
  292.       
  293.         $specialist = new Specialist();
  294.         $options = [
  295.             'pwd_required' => true,
  296.             'specialist_reg' => true,
  297.         ];
  298.         $form = $this->createForm(SpecialistLightType::class, $specialist, $options);
  299.         $form->handleRequest($request);
  300.         if ($form->isSubmitted() && $form->isValid()) {
  301.             $existingSpecialist = $specialistRepo->findOneBy(
  302.                 [
  303.                     'tel' => $specialist->getTel(),
  304.                     ]
  305.                 );
  306.             if ($existingSpecialist == null) {
  307.                 $validUuid = Uuid::v1();
  308.                 $specialist->setIsVirtualEvent(true);
  309.                 $specialist->getUser()->setActive(true);
  310.                 $specialist->setSpecialistTags([]);
  311.                 $specialist->setUuid($validUuid);
  312.                 $specialist->setStatus(Specialist::STATUS_WAITING_MAIL_CONFIRMATION);
  313.                 try {
  314.                     $entityManager->persist($specialist);
  315.                     $entityManager->flush();
  316.                     $entityManager->refresh($specialist);
  317.                     $this->emailService->sendSpecialistAccountConfirmation($specialist);
  318.                     $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');
  319.                     return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  320.                 }catch (\Exception $e){
  321.                     $this->addFlash('errorGlobal', 'Une erreur est survenue');
  322.                     return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  323.                 }
  324.             }elseif ($existingSpecialist != null && $existingSpecialist->getStatus() == Specialist::STATUS_REFUSED) {
  325.                 $this->addFlash('errorGlobal', 'Désolé mais la connexion à ton compte n\'est pas possible actuellement');
  326.                 return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  327.             }else {
  328.                 $this->addFlash('errorGlobal', 'Un expert avec ce numero de téléphone existe déjà');
  329.                 return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  330.             }
  331.         }
  332.         return $this->render('security/create_specialist.html.twig', [
  333.             'regForm' => $form->createView(),
  334.         ]);
  335.     }
  336.     /**
  337.      * @Route("/expert/login/validation-compte/{specialistUuid}", name="app_validate_specialist")
  338.      */
  339.     public function expertUserValidate(Request $request, EntityManagerInterface $entityManager, SpecialistRepository $specialistRepo, string $specialistUuid ): Response
  340.     {
  341.         
  342.         $specialist = $specialistRepo->findOneBy([
  343.             'uuid' => $specialistUuid
  344.         ]);
  345.         if ($specialist instanceof Specialist ) {
  346.             $specialist->setStatus(Specialist::STATUS_WAITING_ULTEAM_CONFIRMATION);
  347.             $entityManager->persist($specialist);
  348.             $entityManager->flush();
  349.             $this->emailService->sendNewSpecialistNotificationToUlteam($specialist);
  350.             $this->addFlash('success', 'Félicitations, ton compte est à présent validé, tu peux te connecter et profiter des opportunités ULTEAM');
  351.             return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  352.         }else {
  353.             $this->addFlash('errorGlobal', 'Une erreur est survenue');
  354.             return $this->redirectToRoute(SpecialistAuthenticator::LOGIN_ROUTE);
  355.         }
  356.         
  357.         return $this->render('security/create_specialist.html.twig', [
  358.         ]);
  359.     }
  360.     /**
  361.      * @Route("/expert/logout", name="app_specialist_logout")
  362.      */
  363.     public function logoutSpecialist(): void
  364.     {
  365.     }
  366. }