<?php
namespace App\Controller;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\UserRepository;
class FacebookController extends AbstractController
{
/**
* Link to this controller to start the "connect" process
*
* @Route("/connect/facebook", name="connect_facebook_start")
*/
public function connectAction(ClientRegistry $clientRegistry)
{
// on Symfony 3.3 or lower, $clientRegistry = $this->get('knpu.oauth2.registry');
// will redirect to Google!
return $clientRegistry
->getClient('facebook') // key used in config/packages/knpu_oauth2_client.yaml
->redirect([
'public_profile', 'email' // the scopes you want to access
]);
}
/**
* After going to Facebook, you're redirected back here
* because this is the "redirect_route" you configured
* in config/packages/knpu_oauth2_client.yaml
*
* @Route("/connect/facebook/check", name="connect_facebook_check")
*/
public function connectCheckAction(Request $request, ClientRegistry $clientRegistry, UserRepository $userRepository )
{
// ** if you want to *authenticate* the user, then
// leave this method blank and create a Guard authenticator
// (read below)
/** @var \KnpU\OAuth2ClientBundle\Client\Provider\FacebookClient $client */
$client = $clientRegistry->getClient('facebook');
//dd($client->fetchUser());
try {
// the exact class depends on which provider you're using
/** @var \League\OAuth2\Client\Provider\FacebookUser $user */
$user = $client->fetchUser();
$findUserByEmail =$userRepository->findOneBy(['email' => $user->getEmail()]);
//dd($findUserByEmail);
if($findUserByEmail == null) {
$this->addFlash('app_event_login', 'User not found!');
return $this->redirectToRoute('app_register');
}
if(empty($findUserByEmail->getProvider()) || $findUserByEmail->getProvider() != 'Facebook' ) {
$findUserByEmail->setProviderId($user->getID());
$findUserByEmail->setProvider('Facebook');
$dateNow = new \DateTime();
$findUserByEmail->setUpdatedAt($dateNow);
}
//dd($findUserByEmail);
// do something with all this new power!
// e.g. $name = $user->getFirstName();
// ...
$userRepository->save($findUserByEmail, true);
return $user;
} catch (IdentityProviderException $e) {
// something went wrong!
// probably you should return the reason to the user
var_dump($e->getMessage()); die;
}
}
}