Ejemplo n.º 1
0
 /**
  * @param array $params         
  * @throws Exception
  */
 public function authenticate(array $params)
 {
     if (!isset($params['code']) || empty($params['code'])) {
         throw new Exception('Authentication failed, invalid or empty code.');
     }
     $oAuthConf = Config::$a['oauth']['providers'][$this->authProvider];
     $client = new \OAuth2\Client($oAuthConf['clientId'], $oAuthConf['clientSecret'], \OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC);
     $client->setAccessTokenType(\OAuth2\Client::ACCESS_TOKEN_BEARER);
     $response = $client->getAccessToken('https://ssl.reddit.com/api/v1/access_token', 'authorization_code', array('redirect_uri' => sprintf(Config::$a['oauth']['callback'], $this->authProvider), 'code' => $params['code']));
     if (empty($response) || isset($response['error'])) {
         throw new Exception('Invalid access_token response');
     }
     if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) {
         throw new Exception('Failed request for access token');
     }
     $client->setAccessToken($response['result']['access_token']);
     // Reddit requires a User-Agent
     $info = $client->fetch("https://oauth.reddit.com/api/v1/me.json", array(), 'GET', array('User-Agent' => 'destiny.gg/' . Config::version()));
     if (empty($info['result']) || !is_array($info['result']) || isset($info['error'])) {
         throw new Exception('Invalid user details response');
     }
     $authCreds = $this->getAuthCredentials($params['code'], $info['result']);
     $authCredHandler = new AuthenticationRedirectionFilter();
     return $authCredHandler->execute($authCreds);
 }
Ejemplo n.º 2
0
 /**
  * @param array $params         
  * @throws Exception
  */
 public function authenticate(array $params, ViewModel $model)
 {
     if (!isset($params['code']) || empty($params['code'])) {
         throw new Exception('Authentication failed, invalid or empty code.');
     }
     $oAuthConf = Config::$a['oauth']['providers'][$this->authProvider];
     $client = new \OAuth2\Client($oAuthConf['clientId'], $oAuthConf['clientSecret']);
     $client->setAccessTokenType(\OAuth2\Client::ACCESS_TOKEN_OAUTH);
     $response = $client->getAccessToken('https://api.twitch.tv/kraken/oauth2/token', 'authorization_code', array('redirect_uri' => sprintf(Config::$a['oauth']['callback'], $this->authProvider), 'code' => $params['code']));
     if (empty($response) || isset($response['error'])) {
         throw new Exception('Invalid access_token response');
     }
     if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) {
         throw new Exception('Failed request for access token');
     }
     $client->setAccessToken($response['result']['access_token']);
     $response = $client->fetch('https://api.twitch.tv/kraken/user');
     if (empty($response['result']) || isset($response['error'])) {
         throw new Exception('Invalid user details response');
     }
     if (is_string($response['result'])) {
         throw new Exception(sprintf('Invalid auth result %s', $response['result']));
     }
     $authCreds = $this->getAuthCredentials($params['code'], $response['result']);
     $authCredHandler = new AuthenticationRedirectionFilter();
     return $authCredHandler->execute($authCreds);
 }
 /**
  * Registers services on the given app.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  */
 public function register(Application $app)
 {
     $app['oauth_client_id'] = '';
     $app['oauth_client_secret'] = '';
     $app['oauth_client'] = $app->share(function (Application $app) {
         $client = new \OAuth2\Client($app['oauth_client_id'], $app['oauth_client_secret']);
         $session = $app['request']->getSession();
         if ($session->has('oauth_access_token')) {
             $client->setAccessToken($session->get('oauth_access_token'));
             $client->setAccessTokenType(\OAuth2\Client::ACCESS_TOKEN_BEARER);
         }
         return $client;
     });
     $app['oauth_base_url'] = function (Application $app) {
         if ($app['session']->has('slug')) {
             return sprintf('https://%s.nationbuilder.com/', $app['session']->get('slug'));
         }
         return false;
     };
     $app['oauth_url'] = function (Application $app) {
         if ($app['session']->has('slug')) {
             return sprintf('https://%s.nationbuilder.com/api/v1/', $app['session']->get('slug'));
         }
         return false;
     };
     $app['oauth_auth_url'] = function (Application $app) {
         if ($app['session']->has('slug')) {
             return sprintf('https://%s.nationbuilder.com/oauth/', $app['session']->get('slug'));
         }
         return false;
     };
 }
Ejemplo n.º 4
0
/**
 * New OAuth2 Client
 */
function NewClient()
{
    global $QBOX_ACCESS_KEY, $QBOX_SECRET_KEY;
    $client = new \OAuth2\Client('a75604760c4da4caaa456c0c5895c061c3065c5a', '75df554a39f58accb7eb293b550fa59618674b7d');
    $client->setAccessTokenType($client::ACCESS_TOKEN_QBOX, $QBOX_SECRET_KEY, null);
    $client->setAccessToken($QBOX_ACCESS_KEY);
    return $client;
}
 public function callbackAction()
 {
     $callback_url = Mage::getUrl('gomage_social/reddit/callback', array('_secure' => true));
     $client = new OAuth2\Client(Mage::getStoreConfig('gomage_social/reddit/id'), Mage::getStoreConfig('gomage_social/reddit/secret'), OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC);
     $params = array("code" => $this->getRequest()->getParam('code'), "redirect_uri" => $callback_url);
     if ($params['code']) {
         $response = $client->getAccessToken($this->accessTokenUrl, "authorization_code", $params);
         $accessTokenResult = $response["result"];
         $client->setAccessToken($accessTokenResult["access_token"]);
         $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER);
         $response = (object) $client->fetch("https://oauth.reddit.com/api/v1/me.json");
         $profile = null;
         switch ($response->code) {
             case 200:
                 $profile = (object) $response->result;
                 break;
             default:
                 $this->getSession()->addError($this->__('Could not connect to Reddit. Refresh the page or try again later.'));
                 return $this->_redirectUrl();
         }
         if ($profile) {
             if ($profile->id) {
                 $social_collection = Mage::getModel('gomage_social/entity')->getCollection()->addFieldToFilter('social_id', $profile->id)->addFieldToFilter('type_id', GoMage_Social_Model_Type::REDDIT);
                 if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) {
                     $social_collection->addFieldToFilter('website_id', Mage::app()->getWebsite()->getId());
                 }
                 $social = $social_collection->getFirstItem();
                 if ($social && $social->getId()) {
                     if ($social->social_id == $profile->id) {
                         $customer = Mage::getModel('customer/customer');
                         if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) {
                             $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
                         }
                         $customer->load($social->getData('customer_id'));
                         if ($customer && $customer->getId()) {
                             if (!$customer->getConfirmation()) {
                                 $this->getSession()->loginById($customer->getId());
                             } else {
                                 $this->getSession()->addError($this->__('This account is not confirmed.'));
                             }
                         }
                     }
                 } else {
                     $profile->url = Mage::getUrl('gomage_social/reddit/checkEmail', array('_secure' => true));
                     $profile->urlEmailClose = Mage::getUrl('gomage_social/twitter/emailClose', array('_secure' => true));
                     $profile->type_id = GoMage_Social_Model_Type::REDDIT;
                     Mage::getSingleton('core/session')->setGsProfile($profile);
                 }
             }
         }
     }
     return $this->_redirectUrl();
 }
Ejemplo n.º 6
0
 /**
  * @param array $params         
  * @throws Exception
  */
 public function authenticate(array $params)
 {
     if (!isset($params['code']) || empty($params['code'])) {
         throw new Exception('Authentication failed, invalid or empty code.');
     }
     $authConf = Config::$a['oauth']['providers'][$this->authProvider];
     $callback = sprintf(Config::$a['oauth']['callback'], $this->authProvider);
     $client = new \OAuth2\Client($authConf['clientId'], $authConf['clientSecret']);
     $response = $client->getAccessToken('https://accounts.google.com/o/oauth2/token', 'authorization_code', array('redirect_uri' => $callback, 'code' => $params['code']));
     if (empty($response) || isset($response['error'])) {
         throw new Exception('Invalid access_token response');
     }
     if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) {
         throw new Exception('Failed request for access token');
     }
     $client->setAccessToken($response['result']['access_token']);
     $response = $client->fetch('https://www.googleapis.com/oauth2/v2/userinfo');
     if (empty($response['result']) || isset($response['error'])) {
         throw new Exception('Invalid user details response');
     }
     $authCreds = $this->getAuthCredentials($params['code'], $response['result']);
     $authCredHandler = new AuthenticationRedirectionFilter();
     return $authCredHandler->execute($authCreds);
 }
Ejemplo n.º 7
0
    die;
    //?state=SomeUnguessableValue&code=ki4tr-_EAXNXVrhWMcQ5a5pLm0o
}
$authorizeUrl = 'https://ssl.reddit.com/api/v1/authorize';
$accessTokenUrl = 'https://ssl.reddit.com/api/v1/access_token';
$clientId = 'jJgLD5ebMOT9sw';
$clientSecret = 'muldwiysWI2ok2KWNmoiDK6FMKw';
$userAgent = 'ChangeMeClient/0.1 by YourUsername';
$redirectUrl = "http://brittanyannkos.com/reddit";
require "OAuth2/Client.php";
require "OAuth2/GrantType/IGrantType.php";
require "OAuth2/GrantType/AuthorizationCode.php";
$client = new OAuth2\Client($clientId, $clientSecret, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC);
$client->setCurlOption(CURLOPT_USERAGENT, $userAgent);
$_GET["code"] = "ki4tr-_EAXNXVrhWMcQ5a5pLm0o";
if (!isset($_GET["code"])) {
    $authUrl = $client->getAuthenticationUrl($authorizeUrl, $redirectUrl, array("scope" => "identity", "state" => "SomeUnguessableValue", "duration" => "permanent"));
    header("Location: " . $authUrl);
    die("Redirect");
} else {
    $params = array("code" => $_GET["code"], "redirect_uri" => $redirectUrl);
    $response = $client->getAccessToken($accessTokenUrl, "authorization_code", $params);
    $accessTokenResult = $response["result"];
    print_r($accessTokenResult);
    $client->setAccessToken($accessTokenResult["access_token"]);
    $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER);
    $response = $client->fetch("https://oauth.reddit.com/api/v1/me.json");
    echo '<strong>Response for fetch me.json:</strong><pre>';
    print_r($response);
    echo '</pre>';
}
require 'Client.php';
require 'IGrantType.php';
require 'AuthorizationCode.php';
/*******************************************************************************
 * IDENTIFICATION
 ******************************************************************************/
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);
$protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://";
$url = $protocol . $_SERVER["HTTP_HOST"] . $_SERVER['REQUEST_URI'];
//DECONNEXION
if (isset($_GET['reset'])) {
    unset($_SESSION['access_token']);
    header('Content-type: application/json');
    echo json_encode(array(DISCONNECT_PAGE));
} elseif (!empty($_SESSION['access_token'])) {
    $client->setAccessToken($_SESSION['access_token']);
    $profile = $client->fetch(PROFILE_PAGE);
} elseif (empty($_GET['code'])) {
    $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, $url);
    header('Location: ' . $auth_url);
    die('Redirect');
} else {
    $params = array('code' => $_GET['code'], 'redirect_uri' => $url);
    $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params);
    if (isset($response['result']) && isset($response['result']['access_token'])) {
        $client->setAccessToken($response['result']['access_token']);
        $_SESSION['access_token'] = $response['result']['access_token'];
        $client->setAccessToken($_SESSION['access_token']);
        $profile = $client->fetch(PROFILE_PAGE);
    } else {
        die('Une erreur est survenue lors de l’identification');
 * 4. We use the access_token to access an API endpoint
 */
try {
    $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC);
    if (!isset($_REQUEST['code'])) {
        $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
        header('Location: ' . $auth_url);
        die('Redirecting ...');
    } else {
        $params = array('code' => $_REQUEST['code'], 'redirect_uri' => REDIRECT_URI);
        $response = $client->getAccessToken(TOKEN_ENDPOINT, OAuth2\Client::GRANT_TYPE_AUTH_CODE, $params);
        $val = (object) $response['result'];
        if (!$val->access_token) {
            throw new Exception("No access token returned: " . $val->error_description);
        }
        $client->setAccessToken($val->access_token);
        $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_OAUTH);
        // Submit a file first
        $response = $client->fetch(SUBMIT_API, array('title' => 'Fella Sample Image', 'artist_comments' => 'Fella Sample Image', 'keywords' => 'fella sample image', 'folder' => APPNAME, 'file' => "@fella.png"), OAuth2\Client::HTTP_METHOD_POST);
        $result = (object) $response['result'];
        if (!$result) {
            throw new Exception('No valid JSON response returned');
        }
        if ($result->status != 'success') {
            throw new Exception($result->error_description);
        }
        // Rename the folder we just created
        $new_folder = NEW_FOLDER_NAME . uniqid();
        $target_folderid = $result->folderid;
        $response = $client->fetch(FOLDER_API, array('folderid' => $target_folderid, 'folder' => $new_folder), OAuth2\Client::HTTP_METHOD_POST);
        $result = (object) $response['result'];
Ejemplo n.º 10
0
<?php

include 'config.php';
$client = new OAuth2\Client($clientId, $clientSecret);
if (!isset($_GET['code'])) {
    $authUrl = $client->getAuthenticationUrl($authorizeUrl, $redirectUrl);
    header('Location: ' . $authUrl);
    die('Redirect');
} else {
    $params = array('code' => $_GET['code'], 'redirect_uri' => $redirectUrl);
    $response = $client->getAccessToken($accessTokenUrl, 'authorization_code', $params);
    $token = $response['result']['access_token'];
    $client->setAccessTokenType(1);
    $client->setAccessToken($token);
    $_SESSION['client'] = $client;
    $_SESSION['token'] = $token;
    header('Location: index.php');
}
Ejemplo n.º 11
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
use PositionlyApi\PositionlyApi;
require '_credentials.php';
$client = new OAuth2\Client($clientId, $clientSecret);
$authorizationParams = array('username' => $username, 'password' => $password);
$result = $client->getAccessToken(PositionlyApi::getTokenEndpoint(), 'password', $authorizationParams);
$accessToken = json_decode($result['result'], true);
$client->setAccessToken($accessToken['access_token']);
$api = new PositionlyApi($client);
// get accounts
$response = $api->call('/accounts');
// get first account id
$accountId = $response->getResult()[0]['id'];
// get first website id
$response = $api->call(sprintf('/accounts/%s/websites', $accountId));
$websiteId = $response->getResult()[0]['id'];
// get first keyword id
$response = $api->call(sprintf('/accounts/%s/websites/%s/keywords', $accountId, $websiteId));
$keywordId = $response->getResult()[0]['id'];
$engineId = 43;
// google polska
$response = $api->call(sprintf('/accounts/%s/websites/%s/engines/%s/keywords/%s/positions', $accountId, $websiteId, $engineId, $keywordId));
if ($response->isSuccess()) {
    echo 'Success!';
} else {
    echo 'Failure';
}
print_r($response);
exit;
Ejemplo n.º 12
0
require 'GrantType/IGrantType.php';
require 'GrantType/AuthorizationCode.php';
const CLIENT_ID = '379875764619-57lesbrrec02g9tf3r2d2gup6nvdl3p4.apps.googleusercontent.com';
const CLIENT_SECRET = 'KeHot5Ds76apeUcrE27xXYJH';
const REDIRECT_URI = 'http://localhost/oauth/test.php';
const AUTHORIZATION_ENDPOINT = 'https://accounts.google.com/o/oauth2/auth';
const TOKEN_ENDPOINT = 'https://accounts.google.com/o/oauth2/token';
//localhost/oauth/test.php
session_start();
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);
if (!isset($_GET['code'])) {
    $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI, array('scope' => 'http://www.google.com/m8/feeds/', 'access_type' => 'offline'));
    header('Location: ' . $auth_url);
    die('Redirect');
} else {
    if (empty($_SESSION['token'])) {
        $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
        $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params);
        if ($response['code'] == 200) {
            $_SESSION['token'] = $response['result']['access_token'];
        }
    }
    if (!empty($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
        $response = $client->fetch('https://www.google.com/m8/feeds/contacts/default/full');
        if ($response['code'] == 200) {
            $response = json_encode(simplexml_load_string($response['result']));
            print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
        }
    }
}
Ejemplo n.º 13
0
    // authentication call
    $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
    header('Location: ' . $auth_url);
    die('Redirect');
} else {
    // access token request
    $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
    $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params);
    // CAUTION! instead of parse_str, assign response directly to $info or find an alternative way.
    // parse_str($response['result'], $info);
    $info = $response['result'];
    $accessToken = $info['access_token'];
    $refreshToken = $info['refresh_token'];
    print_r($info);
    echo "<br /><br /><br />";
    // set access token for further api calls
    $client->setAccessToken($accessToken);
    // example api call
    $response = $client->fetch('https://api.parasut.com/v1/me');
    var_dump($response, $response['result']);
    echo "<br /><br /><br />";
    // in the case of token expiration, use method below
    $params = array('refresh_token' => $refreshToken);
    $response = $client->getAccessToken(TOKEN_ENDPOINT, 'refresh_token', $params);
    $info = $response['result'];
    print_r($info);
    $client->setAccessToken($info['access_token']);
    $response = $client->fetch('https://api.parasut.com/v1/33/sales_invoices');
    var_dump($response, $response['result']);
}
die;
Ejemplo n.º 14
0
/**
 *	Add the necessary webhooks for the Sausage Machine to function
 *	@param String $github_access_token see route_get_github_auth & route_get_github_auth_callback
 *	@param String $github_repo GitHub username, followed by a slash, followed by the name of the respository
 *	@return true if sucessful, false if not
 */
function github_add_webhook($github_access_token, $github_repo)
{
    $client = new OAuth2\Client(config('github_client_id'), config('github_client_secret'));
    $client->setAccessToken($github_access_token);
    $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_TOKEN);
    $client->setCurlOption(CURLOPT_USERAGENT, config('github_useragent'));
    $param = array('name' => 'web', 'active' => true, 'events' => array('push'), 'config' => array('url' => base_url() . 'github.php?push', 'content_type' => 'form'));
    $response = $client->fetch('https://api.github.com/repos/' . $github_repo . '/hooks', json_encode($param), 'POST');
    if (!isset($response['code']) || $response['code'] !== 201) {
        return false;
    } else {
        return true;
    }
}