Exemplo n.º 1
0
 public function post($request)
 {
     $res = new Response($request);
     try {
         $oauth = new OAuth2(new Oauth2StorageUserCredential());
         $oauth->grantAccessToken($_POST);
     } catch (OAuth2ServerException $oauthError) {
         $oauthError->sendHttpResponse();
     }
     return $res;
 }
 /**
  * Tests OAuth2->grantAccessToken() with successful Auth code grant, but without redreict_uri in the input
  */
 public function testGrantAccessTokenWithGrantAuthCodeSuccessWithoutRedirect()
 {
     $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'my_little_app', 'client_secret' => 'b', 'code' => 'foo');
     $storedToken = array('redirect_uri' => 'http://www.example.com', 'client_id' => 'my_little_app', 'expires' => time() + 60);
     $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
     $mockStorage->expects($this->any())->method('getAuthCode')->will($this->returnValue($storedToken));
     // Successful token grant will return a JSON encoded token:
     $this->expectOutputRegex('/{"access_token":".*","expires_in":\\d+,"token_type":"bearer"/');
     $this->fixture = new OAuth2($mockStorage);
     $this->fixture->setVariable(OAuth2::CONFIG_ENFORCE_INPUT_REDIRECT, false);
     $this->fixture->grantAccessToken($inputData, array());
 }
 public function api($method, $url, $params = array(), $headers = array(), $auth = false)
 {
     if (!isset($params["access_token"])) {
         $params["access_token"] = $this->accessToken();
     }
     return parent::api($method, $url, $params, $headers, $auth);
 }
Exemplo n.º 4
0
 /**
  *
  * @param  Application        $app
  * @return API_OAuth2_Adapter
  */
 public function __construct(Application $app)
 {
     parent::__construct();
     $this->params = [];
     $this->app = $app;
     return $this;
 }
 public function api($method, $url, $params = array(), $headers = array(), $auth = false)
 {
     if (is_array($headers) && !isset($headers["Authorization"]) && is_string($this->accessToken())) {
         $headers["Authorization"] = "token " . $this->accessToken();
     }
     // Everything here is done by the OAuthRequest class.
     return parent::api($method, $url, $params, $headers, $auth);
 }
 public function __construct($client_id, $client_secret, $options = array())
 {
     parent::__construct($client_id, $client_secret, $options);
     if (is_numeric($this->options(["api", "version"]))) {
         $this->setVersion((double) $this->options(["api", "version"]));
         unset($this->options->api->version);
     }
 }
Exemplo n.º 7
0
  /**
   * Overrides OAuth2::__construct().
   */
  public function __construct() {
    parent::__construct();

    try {
      $this->db = new PDO(PDO_DSN, PDO_USER, PDO_PASS);
    } catch (PDOException $e) {
      die('Connection failed: ' . $e->getMessage());
    }
  }
Exemplo n.º 8
0
 /** 
  * 构造 
  */  
 public function __construct() {  
     parent::__construct();  
     $this -> db = Db::getInstance(C('OAUTH2_DB_DSN'));  
     $this -> table = array(  
         'auth_codes'=>C('OAUTH2_CODES_TABLE'),  
         'clients'=>C('OAUTH2_CLIENTS_TABLE'),  
         'tokens'=>C('OAUTH2_TOKEN_TABLE')  
     );  
 }  
Exemplo n.º 9
0
 public function _remap($method, $args)
 {
     if ($method == 'linked') {
         $this->linked();
         return;
     }
     // Invalid method or no provider = BOOM
     if (!in_array($method, array('session', 'callback')) or empty($args)) {
         show_404();
     }
     // Get the provider (facebook, twitter, etc)
     list($provider) = $args;
     // This provider is not supported by the module
     if (!isset($this->providers[$provider])) {
         show_404();
     }
     // Look to see if we have this provider in the db?
     if (!($credentials = $this->credential_m->get_active_provider($provider))) {
         $this->ion_auth->is_admin() ? show_error('Social Integration: ' . $provider . ' is not supported, or not enabled.') : show_404();
     }
     // oauth or oauth 2?
     $strategy = $this->providers[$provider];
     switch ($strategy) {
         case 'oauth':
             include $this->module_details['path'] . '/oauth/libraries/OAuth.php';
             $oauth = new OAuth();
             // Create an consumer from the config
             $consumer = $oauth->consumer(array('key' => $credentials->client_key, 'secret' => $credentials->client_secret));
             // Load the provider
             $provider = $oauth->provider($provider);
             break;
         case 'oauth2':
             include $this->module_details['path'] . '/oauth2/libraries/OAuth2.php';
             $oauth2 = new OAuth2();
             // OAuth2 is the honey badger when it comes to consumers - it just dont give a shit
             $consumer = null;
             $provider = $oauth2->provider($provider, array('id' => $credentials->client_key, 'secret' => $credentials->client_secret, 'scope' => $credentials->scope));
             break;
         default:
             exit('Something went properly wrong!');
     }
     // Call session or callback, with lots of handy details
     call_user_func(array($this, '_' . $method), $strategy, $provider, $consumer);
 }
Exemplo n.º 10
0
 public function __construct(IOAuth2Storage $storage, $config = array())
 {
     $config = is_array($config) ? $config : array();
     $config[self::CONFIG_SUPPORTED_SCOPES] = 'all';
     $config[self::DEFAULT_ACCESS_TOKEN_LIFETIME] = 7200;
     // 2 hours
     $config[self::DEFAULT_REFRESH_TOKEN_LIFETIME] = 31536000;
     // 365 days
     parent::__construct($storage, $config);
 }
Exemplo n.º 11
0
 public function api($method, $url, $params = array(), $headers = array(), $auth = false)
 {
     if (!isset($params["api_key"])) {
         $params["api_key"] = $this->client()->id;
     }
     if (!isset($params["api_secret"])) {
         $params["api_secret"] = $this->client()->secret;
     }
     return parent::api($method, $url, $params, $headers, $auth);
 }
Exemplo n.º 12
0
 public function apiCall($path, $method = 'GET', $params = null, $json = false)
 {
     //Prepare request URL
     $url = $this->oauth_endpoint . $path;
     //Obtain access token for authentication
     $token = $this->oauth2->getAccessToken();
     //Prepare cURL options
     $options[CURLOPT_RETURNTRANSFER] = true;
     $options[CURLOPT_CONNECTTIMEOUT] = 10;
     $options[CURLOPT_TIMEOUT] = 30;
     $options[CURLOPT_USERAGENT] = $this->user_agent;
     $options[CURLOPT_CUSTOMREQUEST] = $method;
     $options[CURLOPT_HTTPHEADER][] = "Authorization: " . $token['token_type'] . " " . $token['access_token'];
     if ($json) {
         $options[CURLOPT_HTTPHEADER][] = "Content-Type: application/json";
     }
     //Execution is placed in a loop in case CAPTCHA is required.
     do {
         //Prepare URL or POST parameters
         if (isset($params)) {
             if ($method == 'GET') {
                 $url .= '?' . http_build_query($params);
             } else {
                 $options[CURLOPT_POSTFIELDS] = $params;
             }
         }
         //Build cURL object
         $ch = curl_init($url);
         curl_setopt_array($ch, $options);
         //Wait on rate limiter if necessary
         $this->ratelimiter->wait();
         //Print request URL for debug
         if ($this->debug) {
             echo $url . "\n";
         }
         //Send request and close connection
         $response_raw = curl_exec($ch);
         curl_close($ch);
         //Parse response
         $response = json_decode($response_raw);
         if ($json_error = json_last_error()) {
             $response = $response_raw;
         }
         if (isset($response->json->captcha)) {
             $params['iden'] = $response->json->captcha;
             $params['captcha'] = $this->getCaptchaResponse($response->json->captcha);
             $needs_captcha = $params['captcha'] === 'skip' ? false : true;
         } else {
             $needs_captcha = false;
         }
     } while ($needs_captcha);
     return $response;
 }
Exemplo n.º 13
0
 public function getAccessToken($client_id = '', $secret = '', $redirect_url = '', $code = '')
 {
     $result = parent::getAccessToken($client_id, $secret, $redirect_url, $code);
     $result = json_decode($result, true);
     if (isset($result['error'])) {
         $this->error = $result['error'] . ' ' . $result['error_description'];
         return false;
     } else {
         $this->access_token = $result['access_token'];
         return $result;
     }
 }
 public function api($method, $url, $params = array(), $headers = array(), $auth = false)
 {
     if (!isset($params["oauth_token"])) {
         $params["oauth_token"] = $this->accessToken();
     }
     if (!isset($params["v"])) {
         $params["v"] = "20140806";
     }
     if (!isset($params["m"])) {
         $params["m"] = "foursquare";
     }
     return parent::api($method, $url, $params, $headers, $auth);
 }
Exemplo n.º 15
0
 public function connectProvider($provider)
 {
     if ($provider == 'stripe') {
         $user = Auth::user();
         if (Input::has('code')) {
             // get the token with the code
             $response = OAuth2::getRefreshToken(Input::get('code'));
             if (isset($response['refresh_token'])) {
                 $user->stripeRefreshToken = $response['refresh_token'];
                 $user->stripeUserId = $response['stripe_user_id'];
                 Stripe\Stripe::setApiKey($_ENV['STRIPE_SECRET_KEY']);
                 $account = Stripe\Account::retrieve($user->stripeUserId);
                 // success
                 $returned_object = json_decode(strstr($account, '{'), true);
                 // save user
                 $user->ready = 'connecting';
                 // setting name if is null
                 if (strlen($user->name) == 0) {
                     $user->name = $returned_object['display_name'];
                 }
                 if (strlen($user->zoneinfo) == 0) {
                     $user->zoneinfo = $returned_object['country'];
                 }
                 // saving user
                 $user->save();
                 IntercomHelper::connected($user, 'stripe');
                 Queue::push('CalculateFirstTime', array('userID' => $user->id));
             } else {
                 if (isset($response['error'])) {
                     Log::error($response['error_description']);
                     return Redirect::route('connect.connect')->with('error', 'Something went wrong, try again later');
                 } else {
                     Log::error("Something went wrong with stripe connect, don't know what");
                     return Redirect::route('connect.connect')->with('error', 'Something went wrong, try again later');
                 }
             }
         } else {
             if (Input::has('error')) {
                 // there was an error in the request
                 Log::error(Input::get('error_description'));
                 return Redirect::route('connect.connect')->with('error', Input::get('error_description'));
             } else {
                 // we don't know what happened
                 Log:
                 error('Unknown error with user: '******'connect.connect')->with('error', 'Something went wrong, try again');
             }
         }
     }
     return Redirect::route('auth.dashboard')->with('success', ucfirst($provider) . ' connected.');
 }
Exemplo n.º 16
0
        $OAuth->logout();
        $returnstring = base64_encode(serialize($_SESSION));
        header("Location: {$_SESSION['returnto']}");
        unset($_SESSION['returnto'], $_SESSION['callto']);
        session_write_close();
        die;
    }
    if ($_GET['action'] == "getsession") {
        $returnstring = base64_encode(serialize($_SESSION));
        header("Location: {$_GET['returnto']}");
    }
}
//If we have a callback, it probably means the user executed the authorize function, so let's finish authorization by getting the access token.
if (isset($_GET['oauth_verifier']) && $_GET['oauth_verifier']) {
    start_session();
    $OAuth = new OAuth2($_SESSION['callto']);
    $returnstring = base64_encode(serialize($_SESSION));
    if ($OAuth->isAuthorized()) {
        header("Location: {$_SESSION['returnto']}");
        unset($_SESSION['returnto'], $_SESSION['callto']);
        session_write_close();
        die;
    } else {
        session_write_close();
        die("Failed to complete Authorization!<br>Returned error:<br>" . $OAuth->getError());
    }
}
die("This is a redirector OAuth handling script.  It is not meant to be called directly.");
function start_session()
{
    session_save_path(XTOOLS_BASE_SYS_DIR_SESSION . '/tmp/session');
Exemplo n.º 17
0
<?php

/**
 * @file
 * Sample protected resource.
 *
 * Obviously not production-ready code, just simple and to the point.
 *
 * In reality, you'd probably use a nifty framework to handle most of the crud for you.
 */
require "lib/OAuth2StoragePdo.php";
try {
    $oauth = new OAuth2(new OAuth2StoragePDO());
    $token = $oauth->getBearerToken();
    $oauth->verifyAccessToken($token);
} catch (OAuth2ServerException $oauthError) {
    $oauthError->sendHttpResponse();
}
// With a particular scope, you'd do:
// $oauth->verifyAccessToken("scope_name");
?>

<html>
	<head>
		<title>Hello!</title>
	</head>
	<body>
		<p>This is a secret.</p>
	</body>
</html>
Exemplo n.º 18
0
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="<?php 
echo TRUSTED_LOGIN_PLUGIN_PATH;
?>
css/tlogin-2.0.2.css">
        <link rel="stylesheet" href="css/main.css">
    </head>
    <body>

        <div class="page">
            <h1>Тестовая страница Trusted.Login </h1>

            <?php 
// session_unset();
$token = OAuth2::getFromSession();
//Получаем токен
if ($token) {
    $user = $token->getUser();
    $suser = $user->getServiceUser();
    echo "<div class='view-contaier'>";
    echo "<div class='profile'>";
    echo "<div style='width: 50px; height: 50px; border-radius: 100%; background: url(" . $suser->getAvatarUrl($token->getAccessToken()) . ") no-repeat; background-size: contain; display: inline-block'></div>";
    echo "<span class='user-name'>" . $suser->getDisplayName() . "</span>";
    echo "<a class='view-login' href='logout.php'>Выход</a>";
    echo "</div>";
    echo "</div>";
} else {
    // Вставка виджета Trusted.Login
    include './tlogin.tpl';
}
Exemplo n.º 19
0
<?php

/**
 * @file
 * Sample token endpoint.
 *
 * Obviously not production-ready code, just simple and to the point.
 *
 * In reality, you'd probably use a nifty framework to handle most of the crud for you.
 */
require "lib/OAuth2StoragePDO.php";
$oauth = new OAuth2(new OAuth2StoragePDO());
try {
    $oauth->grantAccessToken();
} catch (OAuth2ServerException $oauthError) {
    $oauthError->sendHttpResponse();
}
Exemplo n.º 20
0
 */
// Clickjacking prevention (supported by IE8+, FF3.6.9+, Opera10.5+, Safari4+, Chrome 4.1.249.1042+)
header('X-Frame-Options: DENY');
require "lib/OAuth2StoragePDO.php";
/*
* You would need to authenticate the user before authorization.
* 
* Below is some psudeo-code to show what you might do:
* 
session_start();
if (!isLoggedIn()) {
	redirectToLoginPage();
	exit();
}
*/
$oauth = new OAuth2(new OAuth2StoragePDO());
if ($_POST) {
    $userId = $_SESSION['user_id'];
    // Use whatever method you have for identifying users.
    $oauth->finishClientAuthorization($_POST["accept"] == "Yep", $userId, $_POST);
}
try {
    $auth_params = $oauth->getAuthorizeParams();
} catch (OAuth2ServerException $oauthError) {
    $oauthError->sendHttpResponse();
}
?>
<html>
<head>
	<title>Authorize</title>
	<script>
Exemplo n.º 21
0
Arquivo: VK.php Projeto: Stoiss777/s
 public function getCodeUri()
 {
     return parent::getCodeUri() . '&v=' . $this->versionApi;
 }
Exemplo n.º 22
0
 /**
  * Get url where adapter should return on when doing cancel.
  *
  * @return string
  */
 public function getCancelUrl()
 {
     $root_url = OAuth2::getBaseUrl();
     // ensure https connect urls
     if ($this->https) {
         $root_url = str_replace('http:', 'https:', $root_url);
     }
     $params = array('oa2_action' => 'cancel', 'oa2_adapter' => $this->adapter_id, 'oa2_state' => $this->state);
     return OAuth2_CURL::urljoin($root_url, $params);
 }
Exemplo n.º 23
0
 /**
  * Tests OAuth2->finishClientAuthorization()
  */
 public function testFinishClientAuthorization()
 {
     // TODO Auto-generated OAuth2Test->testFinishClientAuthorization()
     $this->markTestIncomplete("finishClientAuthorization test not implemented");
     $this->fixture->finishClientAuthorization();
 }
Exemplo n.º 24
0
<?php

/* Подключаем модуль Trusted.Login */
require_once './trusted/config.php';
//указать путь до настроек модуля
require_once TRUSTED_MODULE_AUTH;
//подключить сам модуль Trusted.Login
OAuth2::remove();
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="css/tlogin-2.0.1.css">
    <link rel="stylesheet" href="css/main.css">
</head>
<body>
    <div class="page">
        <h1>Вы успешно вышли из системы</h1>
        <div class='view-contaier'>
            <a href="index.php" class='view-login'>На главную</a>
        </div>
    </div>
</body>
</html>
Exemplo n.º 25
0
 static function token($params)
 {
     $res = array("success" => true, "message" => "");
     try {
         $token = OAuth2::getFromSession();
         //$refreshToken = $token->getRefreshToken();
         //$token->refresh();
         $accessToken = $token->getAccessToken();
         $res["message"] = $accessToken;
     } catch (OAuth2Exception $ex) {
         header("HTTP/1.1 500 Internal Server Error");
         $res["message"] = $ex->message;
         echo json_encode($res);
         die;
     }
     return $res;
 }
Exemplo n.º 26
0
<?php

/**
 * Front end hook for OAuth2 Provider for WordPress
 * 
 * @author Justin Greer
 */
global $wp_query;
/**
* Require OAuth Storage
*/
require_once dirname(__FILE__) . '/admin/IOAuth2Storage.php';
/**
* @var Set the object
*/
$oauth = new OAuth2(new IOAuth2StorageWP());
/**
* @var Clean the method from the query up a bit if needed
*/
$method = $wp_query->get('oauth');
$allowed = array('authorize', 'request_token', 'request_access', 'refresh_token', 'login');
/**
 * Check to make sure only parameters defined are used and nothing else
 */
if (!in_array($method, $allowed)) {
    header("Content-Type: application/json");
    header("Cache-Control: no-store");
    $error = json_encode(array('error' => 'Paramter method', 'error_description' => 'The method parameter is required and seems to be missing'));
    echo $error;
    exit;
}
Exemplo n.º 27
0
 /**
  * Возвращает данные о пользователе полученные с сервиса. 
  * @return \ServiceUser
  * @throws OAuth2Exception
  */
 function getServiceUser()
 {
     $res = $this->serviceUser;
     if (!$res && $this->id) {
         $token = OAuth2::getFromSession();
         if ($token) {
             $arUser = TAuthCommand::getUserProfileByToken($token->getAccessToken());
             //Проверка идентификаторов пользователей
             //debug($arUser);
             if ($arUser['id'] == $this->id) {
                 $res = ServiceUser::fromArray($arUser);
             } else {
                 throw new OAuth2Exception(TRUSTEDNET_ERROR_MSG_DIFFERENT_USER_ID, TRUSTEDNET_ERROR_CODE_DIFFERENT_USER_ID, null);
             }
         } else {
             throw new OAuth2Exception(TRUSTEDNET_ERROR_MSG_TOKEN_NOT_FOUND, TRUSTEDNET_ERROR_CODE_TOKEN_NOT_FOUND, null);
         }
     }
     return $res;
 }
Exemplo n.º 28
0
  /**
   * Overrides OAuth2::__construct().
   */
  public function __construct() {
    parent::__construct();

    $mongo = new Mongo(MONGO_CONNECTION);
    $this->db = $mongo->selectDB(MONGO_DB);
  }
Exemplo n.º 29
0
 public function grantAccessToken($scope = NULL)
 {
     $this->scope = $scope;
     parent::grantAccessToken();
 }
 /**
  * Overrides OAuth2::__construct().
  */
 public function __construct()
 {
     parent::__construct();
     $mongo = new Mongo();
     $this->db = $mongo->selectDB("innet");
 }