<?php
namespace App\Controller\ThemesWebsite\Login;
use App\Entity\Core\Users;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Doctrine\ORM\EntityManagerInterface;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class FacebookController extends AbstractController
{
private $httpClient;
private $entityManager;
private $passwordEncoder;
private $tokenGenerator;
private $us;
private $params;
public function __construct(HttpClientInterface $httpClient,
EntityManagerInterface $entityManager,
UserPasswordEncoderInterface $passwordEncoder,
TokenGeneratorInterface $tokenGenerator,
\App\Services\Core\Users $us,
ParameterBagInterface $params
) {
$this->httpClient = $httpClient;
$this->entityManager = $entityManager;
$this->passwordEncoder = $passwordEncoder;
$this->tokenGenerator = $tokenGenerator;
$this->us = $us;
$this->params = $params;
}
public function connectFacebook(): RedirectResponse
{
$params = [
'response_type' => 'code',
'client_id' => $_ENV['OAUTH_FACEBOOK_CLIENT_ID'], // Replace with your Facebook App ID
'redirect_uri' => $this->generateUrl('connect_facebook_check', [], UrlGeneratorInterface::ABSOLUTE_URL),
'state' => bin2hex(random_bytes(16)), // CSRF token
'scope' => 'email public_profile' // Adjust the scope based on what you need
];
$url = 'https://www.facebook.com/v10.0/dialog/oauth?' . http_build_query($params);
return new RedirectResponse($url);
}
public function connectFacebookCheck(Request $request): Response
{
$code = $request->query->get('code');
$url = 'https://graph.facebook.com/v12.0/oauth/access_token';
$params = [
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $this->generateUrl('connect_facebook_check', [], UrlGeneratorInterface::ABSOLUTE_URL),
'client_id' =>$_ENV['OAUTH_FACEBOOK_CLIENT_ID'],
'client_secret' => $_ENV['OAUTH_FACEBOOK_CLIENT_SECRET'],
];
$client = HttpClient::create();
$response = $client->request('GET', $url, [
'query' => $params
]);
$data = $response->toArray();
$accessToken = $data['access_token'];
// Fetch user profile data from Facebook
$userData = $this->fetchUserProfile($accessToken);
// Handle user login or creation
$user = $this->updateOrCreateUser($userData);
$this->authenticateUser($user);
return $this->redirectToRoute('homepage');
}
private function updateOrCreateUser($userData)
{
$em = $this->getDoctrine()->getManager();
$userRepository = $em->getRepository(Users::class);
$user = $userRepository->findOneByEmail($userData['email']);
if (!$user) {
//$token = $this->tokenGenerator->generateToken();
$randomPassword = $this->us->randomPasswordSecurised();
$user = new Users();
$user->setEmail($userData['email']);
$user->setUsername(null);
//$user->setTokenExpiration(new \DateTime('+1 day'));
//$user->setVerificationToken($token);
$user->setFirst(true);
$user->setEnabled(true);
$user->setPassword($this->passwordEncoder->encodePassword($user, $randomPassword));
$user->setRoles(['ROLE_USER']);
$user->setUpdatedAt(new \DateTime("now"));
$user->setCreatedAt(new \DateTime("now"));
$user->setCurrentAgency(null);
$this->entityManager->persist($user);
$this->entityManager->flush();
}
return $user;
}
private function authenticateUser($user)
{
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($token);
$this->get('session')->set('_security_main', serialize($token));
}
/**
* Utilise le token d'accès pour obtenir les informations de profil de LinkedIn.
*/
private function fetchUserProfile($accessToken)
{
$profileUrl = 'https://graph.facebook.com/v10.0/me';
$profileResponse = $this->httpClient->request('GET', $profileUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json',
],
'query' => [
'fields' => 'id,name,email', // Specify the fields you need from Facebook
],
]);
$profileData = $profileResponse->toArray();
return array_merge($profileData);
}
}