<?php
namespace ApiBundle\OAuth\Extensions;
use ApiBundle\OAuth\FacebookSdk;
use AppBundle\Entity\User;
use AppBundle\Services\UserManager;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use FOS\OAuthServerBundle\Storage\GrantExtensionInterface;
use OAuth2\Model\IOAuth2Client;
use OAuth2\OAuth2Exception;
use Symfony\Bridge\Monolog\Logger;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
class FacebookGrantExtension implements GrantExtensionInterface
{
/**
* @var UserManager
*/
protected $userManager = null;
/**
* @var FacebookSdk
*/
protected $facebookSdk = null;
/**
* @var ContainerInterface
*/
private $container;
/**
* @var Logger
*/
private $logger;
/**
* FacebookGrantExtension constructor.
* @param UserManager $userManager
* @param FacebookSdk $facebookSdk
* @param ContainerInterface $container
*/
public function __construct(
UserManager $userManager,
FacebookSdk $facebookSdk,
ContainerInterface $container
) {
$this->userManager = $userManager;
$this->facebookSdk = $facebookSdk;
$this->container = $container;
$this->logger = $this->container->get('place.logger');
}
public function checkGrantExtension(IOAuth2Client $client, array $inputData, array $authHeaders)
{
if (!isset($inputData['facebook_token'])) {
throw new \OAuthException(
Response::HTTP_BAD_REQUEST,
'facebook_token param is empty'
);
}
try {
// Try to get the user with the facebook token from Open Graph
$facebookUser = $this->facebookSdk->getFacebookUserByToken($inputData['facebook_token']);
} catch (FacebookResponseException $e) {
// When Graph returns an error
throw new \OAuthException(
Response::HTTP_BAD_REQUEST,
'Graph returned an error: '.$e->getMessage()
);
} catch (FacebookSDKException $e) {
// When validation fails or other local issues
throw new \OAuthException(
Response::HTTP_BAD_REQUEST,
'Facebook SDK returned an error: '.$e->getMessage()
);
}
if (empty($facebookUser) || empty($facebookUser->getId())) {
throw new \OAuthException(
Response::HTTP_BAD_REQUEST,
'facebook api did not returned user data'
);
}
/** @var User $user */
$user = $this->userManager->findUserByFacebookId($facebookUser->getId());
// If no user found
if (null === $user) {
$this->logger->critical(self::class . ' - User is not found by facebook id' . $facebookUser->getId());
return false;
}
return [
'data' => $user,
];
}
}