Skip to content

Instantly share code, notes, and snippets.

@makasim
Last active December 21, 2015 02:59
Show Gist options
  • Save makasim/6238847 to your computer and use it in GitHub Desktop.
Save makasim/6238847 to your computer and use it in GitHub Desktop.
openid facebook\twitter
<?php
namespace Rj\CoreBundle\OAuth;
/**
* Copyright (c) 2010 Arnaud Le Blanc, all rights reserved
*/
/**
* Facebook OAuth 2.0 client
*/
class Facebook
{
public static $namespace = "App_Facebook_NS";
private static $authorize_uri = 'https://graph.facebook.com/oauth/authorize?';
private static $access_token_uri = 'https://graph.facebook.com/oauth/access_token?';
private static $instances = array();
private static $app_id;
private static $secret;
//private static $key;
protected $access_token;
protected $http_client;
public function __construct($access_token = null, array $config)
{
if (self::$app_id === null) {
self::$app_id = $config['id'];
self::$secret = $config['secret'];
}
$this->access_token = $access_token;
}
public static function getInstance($access_token = null, array $config)
{
if (self::$app_id === null) {
self::$app_id = $config['id'];
self::$secret = $config['secret'];
}
if (!isset(self::$instances[$access_token])) {
self::$instances[$access_token] = new self($access_token);
}
return self::$instances[$access_token];
}
public function getAppId()
{
return self::$app_id;
}
public function getSecret()
{
return self::$secret;
}
// public function getKey()
// {
// return self::$key;
// }
public function authorizeUrl($redirect_uri, $scope, $display = 'page')
{
return static::$authorize_uri . http_build_query(array(
'client_id' => self::$app_id,
'redirect_uri' => $redirect_uri,
'scope' => $scope,
'display' => $display,
));
}
public function authorize($redirect_uri, $scope, $display = 'page')
{
header('Location: ' . $this->authorizeUrl($redirect_uri, $scope, $display));
exit;
}
public function accessToken(array $params, $redirect_uri)
{
$uri = static::$access_token_uri . http_build_query(array(
'client_id' => self::$app_id,
'redirect_uri' => $redirect_uri,
'client_secret' => self::$secret,
'code' => isset($params['code']) ? $params['code'] : '',
));
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
curl_close ($ch);
parse_str($res, $result);
if (!isset($result['access_token'])) {
throw new \Exception(__METHOD__ . ' failed : ' . $res);
}
$this->access_token = $result['access_token'];
return isset($result['access_token']);
}
public function getAccessToken()
{
return $this->access_token;
}
public function getHttpClient()
{
$ch=curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return $ch;
return new \App_Facebook_Http_Client($this);
}
public function exchangeSessions(array $session_keys)
{
$client = new \Zend_Http_Client();
$client->setUri('https://graph.facebook.com/oauth/exchange_sessions');
$client->setParameterPost('client_id', $this->getAppId());
$client->setParameterPost('client_secret', $this->getSecret());
$client->setParameterPost('sessions', implode(',', $session_keys));
$res = $client->request(\Zend_Http_Client::POST);
$res = $res->getBody();
$res = json_decode($res);
$ret = array();
foreach($res as $item) {
$ret[ array_shift($session_keys) ] = $item;
}
return $ret;
}
public function get($uri)
{
$ch = $this->getHttpClient();
curl_setopt($ch, CURLOPT_URL, $uri . "?access_token=" . $this->getAccessToken());
$body = curl_exec($ch);
$data = json_decode($body);
return $data;
}
public function post($uri, array $params = array())
{
$client = $this->getHttpClient();
$client->setUri($uri);
foreach($params as $name => $value) {
$client->setParameterPost($name, $value);
}
$res = $client->request(\Zend_Http_Client::POST);
$body = $res->getBody();
$data = json_decode($body);
return $data;
}
/** old methods */
private static $APIKEY = "d7bf42841b2d6f1ac9b2d5100fe1d45a";
private static $APISECRET = "0f9cc778c031f1b283e8c2e1c8d8eeaa";
public static function init()
{
require_once 'Facebook/api/facebook.php';
return new self(Facebook::$APIKEY, Facebook::$APISECRET);
}
public static function getFans(\Zend_Cache_Core $cache = null, $refresh = false)
{
$id = 'getFacebookFans';
return \App_Cache::wrap($cache, $refresh, $id, function() {
$facebook = \App_Facebook::init();
$arr = $facebook->api_client->fql_query('select fan_count from page where page_id = 342588105629');
if (!isset($arr[0]['fan_count'])) {
return null;
}
return $arr[0]['fan_count'];
});
}
}
<?php
namespace Rj\CoreBundle\OpenId\RelyingParty;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Fp\OpenIdBundle\RelyingParty\RelyingPartyInterface;
use Fp\OpenIdBundle\RelyingParty\IdentityProviderResponse;
use Rj\CoreBundle\OAuth\Facebook;
class FacebookRelyingParty implements RelyingPartyInterface
{
protected $fb;
protected $router;
public function __construct(Facebook $fb, RouterInterface $router)
{
$this->fb = $fb;
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public function supports(Request $request)
{
return
preg_match('#^https?://facebook\.com#', $request->get('openid_identifier', '')) ||
'facebook' == $request->get('relying_party')
;
}
/**
* {@inheritdoc}
*/
public function manage(Request $request)
{
if (false == $this->supports($request)) {
throw new \RuntimeException('The relying party does not support the request');
}
$returnUrl = $this->getReturnUrl($request);
if ($request->get('openid_identifier')) {
return new RedirectResponse($this->fb->authorizeUrl($returnUrl, 'email'));
} else {
if (false == $this->fb->accessToken($request->query->all(), $returnUrl)) {
throw new \LogicException('Facebook did not provide access token');
}
$fbUser = $this->fb->get('https://graph.facebook.com/me');
if (false == $fbUser) {
throw new \LogicException('Facebook did not provide user object');
}
if (false == (isset($fbUser->id) && $facebookUserId = $fbUser->id)) {
throw new \LogicException('Facebook did not provider the user id');
}
return new IdentityProviderResponse(
'http://facebook.com/' . $facebookUserId,
array(
'contact/email' => isset($fbUser->email) ? $fbUser->email : null,
'namePerson/first' => isset($fbUser->first_name) ? $fbUser->first_name : null,
'namePerson/last' => isset($fbUser->last_name) ? $fbUser->last_name : null,
)
);
}
}
protected function getReturnUrl(Request $request)
{
$routeParams = $request->get('_route_params', array());
$routeParams['relying_party'] = 'facebook';
return $this->router->generate(
$request->get('_route'),
$routeParams,
$absolute = true
);
}
}
fp_openid_security_login:
pattern: /login
fp_openid_security_check:
pattern: /login_check/{relying_party}
defaults:
relying_party: openid
requirements:
relying_party: openid|facebook|twitter|remixcv
security:
role_hierarchy:
ROLE_ADMIN: [ROLE_USER, ROLE_ALLOWED_TO_SWITCH, ROLE_REFERRER]
firewalls:
secured_area:
fp_openid:
login_path: fp_openid_security_login
check_path: fp_openid_security_check
failure_path: rj_core_external_login_failed
default_target_path: rj_cv_client_cv_edit
provider: openid_user_manager
relying_party: rj.core.openid.relying_party
required_attributes:
- contact/email
- namePerson/first
- namePerson/last
providers:
main:
entity: { class: Rj\CoreBundle\Entity\Member, property: username }
openid_user_manager:
id: fp_openid.user_manager
services:
rj.core.openid.relying_party:
class: Fp\OpenIdBundle\RelyingParty\RelyingPartyCollection
calls:
- [append, [@fp_openid.relying_party.recovered_failure]]
- [append, [@rj.core.openid.relying_party.facebook]]
- [append, [@rj.core.openid.relying_party.twitter]]
- [append, [@fp_openid.relying_party.light_open_id]]
rj.core.openid.relying_party.twitter:
class: Rj\CoreBundle\OpenId\RelyingParty\TwitterRelyingParty
public: false
arguments:
- @oauth.twitter
- @session
- @router
oauth.twitter:
class: Zend_Oauth_Consumer
arguments:
-
consumerKey: %twitter_oauth.consumer_key%
consumerSecret: %twitter_oauth.consumer_secret%
requestScheme: header
version: 1.1
signatureMethod: HMAC-SHA1
requestTokenUrl: https://api.twitter.com/oauth/request_token
authorizeUrl: https://api.twitter.com/oauth/authenticate
accessTokenUrl: https://api.twitter.com/oauth/access_token
timeout: 30
rj.core.openid.relying_party.facebook:
class: Rj\CoreBundle\OpenId\RelyingParty\FacebookRelyingParty
public: false
arguments:
- @oauth.facebook
- @router
oauth.facebook:
class: Rj\CoreBundle\OAuth\Facebook
public: false
arguments:
- null
-
id: %facebook_oauth.consumer_id%
key: %facebook_oauth.consumer_key%
secret: %facebook_oauth.consumer_secret%
<?php
namespace Rj\CoreBundle\OpenId\RelyingParty;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Fp\OpenIdBundle\RelyingParty\RelyingPartyInterface;
use Fp\OpenIdBundle\RelyingParty\IdentityProviderResponse;
class TwitterRelyingParty implements RelyingPartyInterface
{
protected $tw;
protected $session;
protected $router;
public function __construct(\Zend_Oauth_Consumer $tw, SessionInterface $session, RouterInterface $router)
{
$this->tw = $tw;
$this->session = $session;
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public function supports(Request $request)
{
return
preg_match('#^https?://twitter\.com#', $request->get('openid_identifier', '')) ||
'twitter' == $request->get('relying_party')
;
}
/**
* {@inheritdoc}
*/
public function manage(Request $request)
{
if (false == $this->supports($request)) {
throw new \RuntimeException('The relying party does not support the request');
}
return $request->get('openid_identifier') ?
$this->verify($request) :
$this->complete($request)
;
}
protected function verify(Request $request)
{
$this->tw->setCallbackUrl($this->getReturnUrl($request));
$requestToken = $this->tw->getRequestToken(array('scope' => 'https://api.twitter.com/oauth/request_token'));
$this->storeRequestToken($requestToken);
$this->tw->redirect(null, $requestToken);
}
protected function complete(Request $request)
{
$this->tw->setCallbackUrl($this->getReturnUrl($request));
$accessToken = $this->tw->getAccessToken($request->query->all(), $this->restoreRequestToken());
$service = new \Zend_Service_Twitter(array('accessToken' => $accessToken));
$userShow = $service->usersShow($accessToken->getParam('user_id'));
return new IdentityProviderResponse(
'http://twitter.com/' . (string) $userShow->id,
array(
'contact/email' => '',
'namePerson/first' => (string) $userShow->name,
'namePerson/last' => ''
)
);
}
protected function getReturnUrl(Request $request)
{
$routeParams = $request->get('_route_params', array());
$routeParams['relying_party'] = 'twitter';
return $this->router->generate(
$request->get('_route'),
$routeParams,
$absolute = true
);
}
protected function storeRequestToken($token)
{
$this->session->set('security.authentication.consumer.twitter.request_token', $token);
}
protected function restoreRequestToken()
{
return $this->session->get('security.authentication.consumer.twitter.request_token');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment