src/Controller/GoogleController.php line 39

Open in your IDE?
  1. <?php
  2. /*
  3. * ==============================================================
  4. *     Autor            :  Farid Benjomaa
  5. *     Modified by        :  
  6. *    COPYRIGHT (C) 2025, Media-Technologies
  7. * ==============================================================
  8. */
  9. namespace App\Controller;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
  12. use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
  13. use League\OAuth2\Client\Provider\Google;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use App\Entity\Client;
  17. use App\Entity\Config;
  18. use Symfony\Component\HttpFoundation\Session\Session;
  19. use App\Entity\UserContact;
  20. use App\Form\SocialRegistrationFormType;
  21. use App\Security\UserContactAuthenticator;
  22. use App\Services\CallApiServices;
  23. use App\Services\QuestionMailService;
  24. use Doctrine\ORM\EntityManagerInterface;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  27. use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
  28. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  29. class GoogleController extends AbstractController
  30. {
  31.     /**
  32.      * Link to this controller to start the "connect" process
  33.      *
  34.      * @Route("/connect/google", name="connect_google_start")
  35.      */
  36.     public function connectAction(ClientRegistry $clientRegistry)
  37.     {
  38.         // on Symfony 3.3 or lower, $clientRegistry = $this->get('knpu.oauth2.registry');
  39.         // will redirect to Facebook!
  40.         return $clientRegistry
  41.             ->getClient('google'// key used in config/packages/knpu_oauth2_client.yaml
  42.             ->redirect();
  43.     }
  44.     /**
  45.      * Link to this controller to start the "connect" process
  46.      *
  47.      * @Route("/register/google", name="inscription_google_start")
  48.      */
  49.     public function googleInscriptionAction(ClientRegistry $clientRegistry)
  50.     {
  51.         // on Symfony 3.3 or lower, $clientRegistry = $this->get('knpu.oauth2.registry');
  52.         // will redirect to Facebook!
  53.         return $clientRegistry
  54.             ->getClient('googleRegister'// key used in config/packages/knpu_oauth2_client.yaml
  55.             ->redirect();
  56.     }
  57.     /**
  58.      * After going to Facebook, you're redirected back here
  59.      * because this is the "redirect_route" you configured
  60.      * in config/packages/knpu_oauth2_client.yaml
  61.      *
  62.      * @Route("/connect/google/check", name="connect_google_check")
  63.      */
  64.     public function connectCheckAction(Request $requestClientRegistry $clientRegistry)
  65.     {
  66.         // ** if you want to *authenticate* the user, then
  67.         // leave this method blank and create a Guard authenticator
  68.         // (read below)
  69.         /** @var \KnpU\OAuth2ClientBundle\Client\Provider\Google $client */
  70.         $client $clientRegistry->getClient('google');
  71.         try {
  72.             // the exact class depends on which provider you're using
  73.             /** @var \League\OAuth2\Client\Provider\Google $user */
  74.             $user $client->fetchUser();
  75.             // do something with all this new power!
  76.             // e.g. $name = $user->getFirstName();
  77.             $session $request->getSession();
  78.             $session->set('clientGoogle'$user);
  79.             // ...
  80.         } catch (IdentityProviderException $e) {
  81.             // something went wrong!
  82.             // probably you should return the reason to the user
  83.             // var_dump($e->getMessage());
  84.             die;
  85.         }
  86.     }
  87.     /**
  88.      * After going to Facebook, you're redirected back here
  89.      * because this is the "redirect_route" you configured
  90.      * in config/packages/knpu_oauth2_client.yaml
  91.      *
  92.      * @Route("/register/google/check", name="register_google_check")
  93.      */
  94.     public function registerCheckAction(Request $requestClientRegistry $clientRegistry)
  95.     {
  96.         $clientGoogle = new Client();
  97.         // ** if you want to *authenticate* the user, then
  98.         // leave this method blank and create a Guard authenticator
  99.         // (read below)
  100.         /** @var \KnpU\OAuth2ClientBundle\Client\Provider\Google $client */
  101.         $client $clientRegistry->getClient('googleRegister');
  102.         try {
  103.             // the exact class depends on which provider you're using
  104.             /** @var \League\OAuth2\Client\Provider\Google $user */
  105.             $user $client->fetchUser();
  106.             // do something with all this new power!
  107.             $clientGoogle->setFirstName($user->getFirstName());
  108.             $clientGoogle->setLastName($user->getLastName());
  109.             $clientGoogle->setEmail($user->getEmail());
  110.             $clientGoogle->setSocial('google');
  111.             $clientGoogle->setSocialUid($user->getId());
  112.             $session $request->getSession();
  113.             $session->set('clientGoogle'$clientGoogle);
  114.             return $this->redirectToRoute("app_google_social_register");
  115.             // ...
  116.         } catch (IdentityProviderException $e) {
  117.             // something went wrong!
  118.             // probably you should return the reason to the user
  119.             // var_dump($e->getMessage());
  120.             die;
  121.         }
  122.     }
  123.     /**
  124.      * @Route("/socialLog", name="app_social_login")
  125.      */
  126.     public function googleLogin(CallApiServices $callApiServicesQuestionMailService $questionMailServiceRequest $requestUserPasswordHasherInterface $userPasswordHasherUserAuthenticatorInterface $userAuthenticatorUserContactAuthenticator $authenticatorEntityManagerInterface $entityManager): Response
  127.     {
  128.         // if ($this->getUser()) {
  129.         //     return $this->redirectToRoute('target_path');
  130.         // }
  131.         // get the login error if there is one
  132.         $error $authenticationUtils->getLastAuthenticationError();
  133.         // last username entered by the user
  134.         $lastUsername $authenticationUtils->getLastUsername();
  135.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  136.     }
  137.     /**
  138.      * @Route("/googleSocial", name="app_google_social_register")
  139.      */
  140.     public function googleRegister(CallApiServices $callApiServicesQuestionMailService $questionMailServiceRequest $requestUserPasswordHasherInterface $userPasswordHasherUserAuthenticatorInterface $userAuthenticatorUserContactAuthenticator $authenticatorEntityManagerInterface $entityManager): Response
  141.     {
  142.         $serviceId $this->getParameter('app.serviceId');
  143.         $accountId $this->getParameter('app.accountId');
  144.         $user = new Client();
  145.         $session $request->getSession();
  146.         $clientGoogle $session->get('clientGoogle');
  147.         $config $session->get('configPlateforme');
  148.         $recaptchaTab $config->getRecaptchaTab();
  149.         $recaptchaKey $recaptchaTab['sitekey'];
  150.         $form $this->createForm(SocialRegistrationFormType::class, $user);
  151.         $form->get('firstName')->setData($clientGoogle->getFirstName());
  152.         $form->get('lastName')->setData($clientGoogle->getLastName());
  153.         $form->get('email')->setData($clientGoogle->getEmail());
  154.         $form->handleRequest($request);
  155.         if ($form->isSubmitted() && $form->isValid()) {
  156.             $password $clientGoogle->getSocialUid();
  157.             $user->setSocial($clientGoogle->getSocial());
  158.             $user->setSocialUid($clientGoogle->getSocialUid());
  159.             $user->setPassword($password);
  160.             $clientInscription $callApiServices->socialInscription(
  161.                 $config->getServiceId(),
  162.                 $user->getGenre(),
  163.                 $user->getEmail(),
  164.                 $user->getPassword(),
  165.                 $user->getFirstName(),
  166.                 $user->getLastName(),
  167.                 $user->getCountry(),
  168.                 $user->getPhoneNumber(),
  169.                 $user->getSocial(),
  170.                 $user->getSocialUid()
  171.             );
  172.             $user->setCode($clientInscription['code']);
  173.             $user->setServiceId($serviceId);
  174.             $session->clear();
  175.             $this->addFlash("inscription""Vous avez bien été inscrit! Vous allez recevoir un mail afin d'activer votre compte d'un moment à l'autre.
  176.             Si vous ne recevez pas le mail, veuillez vérifier dans votre boîte SPAM ou courrier indésirable, s'il s'y trouve !! ");
  177.             // Envoie de Mail.
  178.             //$questionMailService->checkMail($user, $request);
  179.             return $this->redirectToRoute("app_login");
  180.         }
  181.         return $this->render('registration/social_register.html.twig', [
  182.             'registrationForm' => $form->createView(),
  183.             "recaptchaKey" => $recaptchaKey,
  184.         ]);
  185.     }
  186. }