src/Controller/ThemesWebsite/Login/FacebookController.php line 53

Open in your IDE?
  1. <?php
  2. namespace App\Controller\ThemesWebsite\Login;
  3. use App\Entity\Core\Users;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpClient\HttpClient;
  9. use Symfony\Contracts\HttpClient\HttpClientInterface;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  12. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
  15. use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
  16. use Symfony\Component\Security\Core\User\UserInterface;
  17. use Symfony\Component\Security\Core\User\UserProviderInterface;
  18. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  19. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  20. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  21. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  22. use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
  23. use Symfony\Component\Routing\RouterInterface;
  24. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  25. class FacebookController extends AbstractController
  26. {
  27.     private $httpClient;
  28.     private $entityManager;
  29.     private $passwordEncoder;
  30.     private $tokenGenerator;
  31.     private $us;
  32.     private $params;
  33.     public function __construct(HttpClientInterface $httpClient,
  34.                                 EntityManagerInterface $entityManager,
  35.                                 UserPasswordEncoderInterface $passwordEncoder,
  36.                                 TokenGeneratorInterface $tokenGenerator,
  37.                                 \App\Services\Core\Users $us,
  38.                                 ParameterBagInterface $params
  39.     ) {
  40.         $this->httpClient $httpClient;
  41.         $this->entityManager $entityManager;
  42.         $this->passwordEncoder $passwordEncoder;
  43.         $this->tokenGenerator $tokenGenerator;
  44.         $this->us $us;
  45.         $this->params $params;
  46.     }
  47.     public function connectFacebook(): RedirectResponse
  48.     {
  49.         $params = [
  50.             'response_type' => 'code',
  51.             'client_id' => $_ENV['OAUTH_FACEBOOK_CLIENT_ID'], // Replace with your Facebook App ID
  52.             'redirect_uri' => $this->generateUrl('connect_facebook_check', [], UrlGeneratorInterface::ABSOLUTE_URL),
  53.             'state' => bin2hex(random_bytes(16)), // CSRF token
  54.             'scope' => 'email public_profile' // Adjust the scope based on what you need
  55.         ];
  56.         $url 'https://www.facebook.com/v10.0/dialog/oauth?' http_build_query($params);
  57.         return new RedirectResponse($url);
  58.     }
  59.     public function connectFacebookCheck(Request $request): Response
  60.     {
  61.         $code $request->query->get('code');
  62.         $url 'https://graph.facebook.com/v12.0/oauth/access_token';
  63.         $params = [
  64.             'grant_type' => 'authorization_code',
  65.             'code' => $code,
  66.             'redirect_uri' => $this->generateUrl('connect_facebook_check', [], UrlGeneratorInterface::ABSOLUTE_URL),
  67.             'client_id' =>$_ENV['OAUTH_FACEBOOK_CLIENT_ID'],
  68.             'client_secret' => $_ENV['OAUTH_FACEBOOK_CLIENT_SECRET'],
  69.         ];
  70.         $client HttpClient::create();
  71.         $response $client->request('GET'$url, [
  72.             'query' => $params
  73.         ]);
  74.         $data $response->toArray();
  75.         $accessToken $data['access_token'];
  76.         // Fetch user profile data from Facebook
  77.         $userData $this->fetchUserProfile($accessToken);
  78.         // Handle user login or creation
  79.         $user $this->updateOrCreateUser($userData);
  80.         $this->authenticateUser($user);
  81.         return $this->redirectToRoute('homepage');
  82.     }
  83.     private function updateOrCreateUser($userData)
  84.     {
  85.         $em $this->getDoctrine()->getManager();
  86.         $userRepository $em->getRepository(Users::class);
  87.         $user $userRepository->findOneByEmail($userData['email']);
  88.         if (!$user) {
  89.             //$token = $this->tokenGenerator->generateToken();
  90.             $randomPassword $this->us->randomPasswordSecurised();
  91.             $user = new Users();
  92.             $user->setEmail($userData['email']);
  93.             $user->setUsername(null);
  94.             //$user->setTokenExpiration(new \DateTime('+1 day'));
  95.             //$user->setVerificationToken($token);
  96.             $user->setFirst(true);
  97.             $user->setEnabled(true);
  98.             $user->setPassword($this->passwordEncoder->encodePassword($user$randomPassword));
  99.             $user->setRoles(['ROLE_USER']);
  100.             $user->setUpdatedAt(new \DateTime("now"));
  101.             $user->setCreatedAt(new \DateTime("now"));
  102.             $user->setCurrentAgency(null);
  103.             $this->entityManager->persist($user);
  104.             $this->entityManager->flush();
  105.         }
  106.         return $user;
  107.     }
  108.     private function authenticateUser($user)
  109.     {
  110.         $token = new UsernamePasswordToken($usernull'main'$user->getRoles());
  111.         $this->get('security.token_storage')->setToken($token);
  112.         $this->get('session')->set('_security_main'serialize($token));
  113.     }
  114.     /**
  115.      * Utilise le token d'accès pour obtenir les informations de profil de LinkedIn.
  116.      */
  117.     private function fetchUserProfile($accessToken)
  118.     {
  119.         $profileUrl 'https://graph.facebook.com/v10.0/me';
  120.         $profileResponse $this->httpClient->request('GET'$profileUrl, [
  121.             'headers' => [
  122.                 'Authorization' => 'Bearer ' $accessToken,
  123.                 'Content-Type' => 'application/json',
  124.             ],
  125.             'query' => [
  126.                 'fields' => 'id,name,email'// Specify the fields you need from Facebook
  127.             ],
  128.         ]);
  129.         $profileData $profileResponse->toArray();
  130.         return array_merge($profileData);
  131.     }
  132. }