Example #1
0
 function request($command, $args = array())
 {
     // NOTE: cache not implemented
     $args = array_merge(array("url" => $this->rest_endpoint, "method" => $command, "format" => "json", "nojsoncallback" => "1"), $args);
     $request = new OAuthRequest(Verb::POST, $args['url']);
     foreach ($args as $key => $value) {
         $request->addBodyParameter($key, $value);
     }
     $this->oauth_service->signRequest($this->token, $request);
     $response_object = $request->send();
     $response = $response_object->getBody();
     $this->parsed_response = json_decode($response, TRUE);
     if ($this->parsed_response['stat'] == 'fail') {
         if ($this->die_on_error) {
             die("The Flickr API returned the following error: #{$this->parsed_response['code']} - {$this->parsed_response['message']}");
         } else {
             $this->error_code = $this->parsed_response['code'];
             $this->error_msg = $this->parsed_response['message'];
             $this->parsed_response = false;
         }
     } else {
         $this->error_code = false;
         $this->error_msg = false;
     }
     return $response;
 }
 /**
  * Construct the request to be verified
  * 
  * @param string request
  * @param string method
  */
 function __construct($uri = null, $method = 'GET')
 {
     $this->store = elggconnect_get_oauth_store();
     //OAuthStore::instance();
     parent::__construct($uri, $method);
     OAuthRequestLogger::start($this);
 }
Example #3
0
 /**
  * Populates $_{SERVER,GET,POST} and whatever environment-variables needed to test everything..
  *
  * @param string $method GET or POST
  * @param string $uri What URI is the request to (eg http://example.com/foo?bar=baz)
  * @param string $post_data What should the post-data be
  * @param string $auth_header What to set the Authorization header to
  */
 public static function build_request($method, $uri, $post_data = '', $auth_header = '')
 {
     self::reset_request_vars();
     $method = strtoupper($method);
     $parts = parse_url($uri);
     $port = @$parts['port'];
     $scheme = $parts['scheme'];
     $host = $parts['host'];
     $path = @$parts['path'];
     $query = @$parts['query'];
     $port or $port = $scheme == 'https' ? '443' : '80';
     if ($scheme == 'https') {
         $_SERVER['HTTPS'] = 'on';
     }
     $_SERVER['REQUEST_METHOD'] = $method;
     $_SERVER['HTTP_HOST'] = $host;
     $_SERVER['SERVER_PORT'] = $port;
     $_SERVER['SCRIPT_NAME'] = $path;
     $_SERVER['REQUEST_URI'] = $path . '?' . $query;
     $_SERVER['QUERY_STRING'] = $query . '';
     parse_str($query, $_GET);
     if ($method == 'POST') {
         $_SERVER['HTTP_CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
         $_POST = parse_str($post_data);
         OAuthRequest::$POST_INPUT = 'data:application/x-www-form-urlencoded,' . $post_data;
     }
     if ($auth_header != '') {
         $_SERVER['HTTP_AUTHORIZATION'] = $auth_header;
     }
 }
Example #4
0
function sendOAuthBodyPOST($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $body)
{
    $hash = base64_encode(sha1($body, TRUE));
    $parms = array('oauth_body_hash' => $hash);
    $test_token = '';
    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
    $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
    $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
    $acc_req->sign_request($hmac_method, $test_consumer, $test_token);
    // Pass this back up "out of band" for debugging
    global $LastOAuthBodyBaseString;
    $LastOAuthBodyBaseString = $acc_req->get_signature_base_string();
    // echo($LastOAuthBodyBaseString."\m");
    $header = $acc_req->to_header();
    $header = $header . "\r\nContent-type: " . $content_type . "\r\n";
    $params = array('http' => array('method' => 'POST', 'content' => $body, 'header' => $header));
    try {
        $ctx = stream_context_create($params);
        $fp = @fopen($endpoint, 'rb', false, $ctx);
    } catch (Exception $e) {
        $fp = false;
    }
    if ($fp) {
        $response = @stream_get_contents($fp);
    } else {
        // Try CURL
        $headers = explode("\r\n", $header);
        $response = sendXmlOverPost($endpoint, $body, $headers);
    }
    if ($response === false) {
        throw new Exception("Problem reading data from {$endpoint}, {$php_errormsg}");
    }
    return $response;
}
/**
 * Makes a request to the Yelp API and returns the response
 *
 * @param    $host    The domain host of the API
 * @param    $path    The path of the APi after the domain
 * @return   The JSON response from the request
 */
function request($host, $path) {
    $unsigned_url = "http://" . $host . $path;

    // Token object built using the OAuth library
    $token = new OAuthToken($GLOBALS['TOKEN'], $GLOBALS['TOKEN_SECRET']);

    // Consumer object built using the OAuth library
    $consumer = new OAuthConsumer($GLOBALS['CONSUMER_KEY'], $GLOBALS['CONSUMER_SECRET']);

    // Yelp uses HMAC SHA1 encoding
    $signature_method = new OAuthSignatureMethod_HMAC_SHA1();

    $oauthrequest = OAuthRequest::from_consumer_and_token(
        $consumer,
        $token,
        'GET',
        $unsigned_url
    );

    // Sign the request
    $oauthrequest->sign_request($signature_method, $consumer, $token);

    // Get the signed URL
    $signed_url = $oauthrequest->to_url();

    // Send Yelp API Call
    $ch = curl_init($signed_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
Example #6
0
 /**
  * @return OAuthRequest
  */
 public function newRequestMessage($method, $url, $parameters)
 {
     if (!isset($method)) {
         $method = $this->getProperty("httpMethod");
         if ($method == null) {
             $method = $this->consumer->getProperty("httpMethod");
             if ($method == null) {
                 $method = "GET";
             }
         }
     }
     $message = OAuthRequest::from_consumer_and_token($this->consumer, $this->accessToken, $method, $url, $parameters);
     $signatureMethod = null;
     if ($parameters[OAuth::$OAUTH_SIGNATURE_METHOD] == OAuth::$RSA_SHA1) {
         $signatureMethod = new OAuthSignatureMethod_RSA_SHA1();
     } else {
         if ($parameters[OAuth::$OAUTH_SIGNATURE_METHOD] == OAuth::$HMAC_SHA1) {
             $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
         } else {
             //PLAINTEXT
             $signatureMethod = new OAuthSignatureMethod_PLAINTEXT();
         }
     }
     $message->sign_request($signatureMethod, $this->consumer, $this->tokenSecret);
     return $message;
 }
Example #7
0
 /**
  * Sign the request using OAuth. This uses the consumer token and key
  * but 2 legged oauth doesn't require an access token and key. In situations where you want to
  * do a 'reverse phone home' (aka: gadget does a makeRequest to your server
  * and your server wants to retrieve more social information) this is the prefered
  * method.
  *
  * @param string $method the method (get/put/delete/post)
  * @param string $url the url to sign (http://site/social/rest/people/1/@me)
  * @param array $params the params that should be appended to the url (count=20 fields=foo, etc)
  * @param string $postBody for POST/PUT requests, the postBody is included in the signature
  * @return string the signed url
  */
 public function sign($method, $url, $params = array(), $postBody = false, &$headers = array())
 {
     $oauthRequest = OAuthRequest::from_request($method, $url, $params);
     $params = $this->mergeParameters($params);
     foreach ($params as $key => $val) {
         if (is_array($val)) {
             $val = implode(',', $val);
         }
         $oauthRequest->set_parameter($key, $val);
     }
     if ($postBody && strlen($postBody)) {
         if ($this->useBodyHash) {
             $bodyHash = base64_encode(sha1($postBody, true));
             $oauthRequest->set_parameter("oauth_body_hash", $bodyHash);
         }
         if ($this->useBodyHack) {
             $oauthRequest->set_parameter($postBody, '');
         }
     }
     $oauthRequest->sign_request($this->signatureMethod, $this->consumerToken, $this->accessToken);
     if ($postBody && $this->useBodyHack) {
         unset($oauthRequest->parameters[$postBody]);
     }
     $signedUrl = $oauthRequest->to_url();
     return $signedUrl;
 }
Example #8
0
 /**
  * Sign our target URL with OAuth auth stuff.
  *
  * @param string $url
  * @param array $params
  * @return string
  */
 protected function oAuthUrl($url, $params = array())
 {
     // In an ideal world this would be better encapsulated. :)
     $request = OAuthRequest::from_consumer_and_token($this->oauth->consumer, $this->oauth->token, 'GET', $url, $params);
     $request->sign_request($this->oauth->sha1_method, $this->oauth->consumer, $this->oauth->token);
     return $request->to_url();
 }
Example #9
0
 /**
  * Adds a signature to the request
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param $authorizationHeader Move the signature parameters into the Authorization header of the request
  */
 public function sign(common_http_Request $request, common_http_Credentials $credentials, $authorizationHeader = false)
 {
     if (!$credentials instanceof tao_models_classes_oauth_Credentials) {
         throw new tao_models_classes_oauth_Exception('Invalid credentals: ' . gettype($credentials));
     }
     $oauthRequest = $this->getOauthRequest($request);
     $dataStore = new tao_models_classes_oauth_DataStore();
     $consumer = $dataStore->getOauthConsumer($credentials);
     $token = $dataStore->new_request_token($consumer);
     $allInitialParameters = array();
     $allInitialParameters = array_merge($allInitialParameters, $request->getParams());
     $allInitialParameters = array_merge($allInitialParameters, $request->getHeaders());
     //oauth_body_hash is used for the signing computation
     if ($authorizationHeader) {
         $oauth_body_hash = base64_encode(sha1($request->getBody(), true));
         //the signature should be ciomputed from encoded versions
         $allInitialParameters = array_merge($allInitialParameters, array("oauth_body_hash" => $oauth_body_hash));
     }
     //$authorizationHeader = self::buildAuthorizationHeader($signatureParameters);
     $signedRequest = OAuthRequest::from_consumer_and_token($consumer, $token, $oauthRequest->get_normalized_http_method(), $oauthRequest->getUrl(), $allInitialParameters);
     $signature_method = new OAuthSignatureMethod_HMAC_SHA1();
     //common_logger::d('Base string: '.$signedRequest->get_signature_base_string());
     $signedRequest->sign_request($signature_method, $consumer, $token);
     common_logger::d('Base string from TAO/Joel: ' . $signedRequest->get_signature_base_string());
     if ($authorizationHeader) {
         $combinedParameters = $signedRequest->get_parameters();
         $signatureParameters = array_diff_assoc($combinedParameters, $allInitialParameters);
         $signatureParameters["oauth_body_hash"] = base64_encode(sha1($request->getBody(), true));
         $signatureHeaders = array("Authorization" => self::buildAuthorizationHeader($signatureParameters));
         $signedRequest = new common_http_Request($signedRequest->getUrl(), $signedRequest->get_normalized_http_method(), $request->getParams(), array_merge($signatureHeaders, $request->getHeaders()), $request->getBody());
     } else {
         $signedRequest = new common_http_Request($signedRequest->getUrl(), $signedRequest->get_normalized_http_method(), $signedRequest->get_parameters(), $request->getHeaders(), $request->getBody());
     }
     return $signedRequest;
 }
 public function __construct($consumer, $token, $http_method, $http_url, $parameters = array())
 {
     $this->OAuthRequest = OAuthRequest::from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters);
     $this->OAuthRequest->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, $token);
     $this->method = $http_method;
     $this->parameters = is_array($parameters) ? $parameters : array($parameters);
 }
Example #11
0
function getYelp($term, $location)
{
    $unsigned_url = "http://api.yelp.com/v2/search?term=" . urlencode($term) . "&location=" . urlencode($location) . "&limit=1";
    // Set your keys here
    $consumer_key = "8LjXkvQ-lcUe7dSlvIHhAQ";
    $consumer_secret = "7AnAzMD4h6mthw27wT48qZFEJoo";
    $token = "B-j7tOmv_GPGzZsfc_VId-cjRMLlBcCq";
    $token_secret = "Hjq6GZOp61HR_JxUgB9_O7HpqKA";
    // Token object built using the OAuth library
    $token = new OAuthToken($token, $token_secret);
    // Consumer object built using the OAuth library
    $consumer = new OAuthConsumer($consumer_key, $consumer_secret);
    // Yelp uses HMAC SHA1 encoding
    $signature_method = new OAuthSignatureMethod_HMAC_SHA1();
    // Build OAuth Request using the OAuth PHP library. Uses the consumer and token object created above.
    $oauthrequest = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $unsigned_url);
    // Sign the request
    $oauthrequest->sign_request($signature_method, $consumer, $token);
    // Get the signed URL
    $signed_url = $oauthrequest->to_url();
    // Send Yelp API Call
    $ch = curl_init($signed_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $data = curl_exec($ch);
    // Yelp response
    curl_close($ch);
    // Handle Yelp response data
    //$response = json_decode($data);
    // Print it for debugging
    //print_r($response);
    return $data;
}
function brukar_client_oauth_callback()
{
    require_once drupal_get_path('module', 'brukar_common') . '/OAuth.php';
    $method = new OAuthSignatureMethod_HMAC_SHA1();
    $consumer = new OAuthConsumer(variable_get('brukar_consumer_key'), variable_get('brukar_consumer_secret'));
    if (isset($_SESSION['auth_oauth']) && $_SESSION['auth_oauth']['oauth_token'] == $_GET['oauth_token']) {
        unset($_GET['oauth_token']);
        $tmp = new OAuthToken($_SESSION['auth_oauth']['oauth_token'], $_SESSION['auth_oauth']['oauth_token_secret']);
        $req = OAuthRequest::from_consumer_and_token($consumer, $tmp, 'GET', variable_get('brukar_url') . 'server/oauth/access_token', array());
        $req->sign_request($method, $consumer, $tmp);
        parse_str(trim(file_get_contents($req->to_url())), $token);
        unset($_SESSION['auth_oauth']);
        if (count($token) > 0) {
            $_SESSION['_brukar_access_token'] = array('token' => $token['oauth_token'], 'token_secret' => $token['oauth_token_secret']);
            $token = new OAuthToken($token['oauth_token'], $token['oauth_token_secret']);
            $req = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', variable_get('brukar_url') . 'server/oauth/user', array());
            $req->sign_request($method, $consumer, $token);
            brukar_client_login((array) json_decode(trim(file_get_contents($req->to_url()))));
        }
    }
    $debug_data = array('cookie' => $_COOKIE, 'request_uri' => request_uri(), 'auth_oauth' => isset($_SESSION['auth_oauth']) ? $_SESSION['auth_oauth'] : 'no auth_oauth');
    watchdog('brukar_client', 'User login failed.<br/>Debug data:<br/><pre>!debug_data</pre><br/>', array('!debug_data' => print_r($debug_data, TRUE)), WATCHDOG_ERROR);
    drupal_set_message(t('Noe gikk feil under innlogging.'), 'warning');
    drupal_goto('<front>');
}
Example #13
0
File: user.php Project: xctcc/npt
function user_oauth_sign(&$url, &$args = false)
{
    require_once 'OAuth.php';
    $method = $args !== false ? 'POST' : 'GET';
    if (preg_match_all('#[?&]([^=]+)=([^&]+)#', $url, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $match) {
            $args[$match[1]] = $match[2];
        }
        $url = substr($url, 0, strpos($url, '?'));
    }
    $sig_method = new OAuthSignatureMethod_HMAC_SHA1();
    $consumer = new OAuthConsumer(OAUTH_KEY, OAUTH_SECRET);
    $token = NULL;
    if (($oauth_token = $_GET['oauth_token']) && $_SESSION['oauth_request_token_secret']) {
        $oauth_token_secret = $_SESSION['oauth_request_token_secret'];
    } else {
        list($oauth_token, $oauth_token_secret) = explode('|', $GLOBALS['user']['password']);
    }
    if ($oauth_token && $oauth_token_secret) {
        $token = new OAuthConsumer($oauth_token, $oauth_token_secret);
    }
    $request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $url, $args);
    $request->sign_request($sig_method, $consumer, $token);
    switch ($method) {
        case 'GET':
            $url = $request->to_url();
            $args = false;
            return;
        case 'POST':
            $url = $request->get_normalized_http_url();
            $args = $request->to_postdata();
            return;
    }
}
function get_yelp_data_for_truck($vendor_name, $lat, $long)
{
    // Configuration.
    $consumer_key = '';
    $consumer_secret = '';
    $token = '';
    $token_secret = '';
    // Search params.
    $params = array('term' => $vendor_name, 'category_filter' => 'foodtrucks,foodstands', 'location' => 'San Francisco, CA', 'cll' => (string) $lat . "," . (string) $long, 'limit' => 1);
    // Build the request.
    $unsigned_uri = "http://api.yelp.com/v2/search/?" . http_build_query($params);
    // Token object built using the OAuth library
    $token = new OAuthToken($token, $token_secret);
    // Consumer object built using the OAuth library
    $consumer = new OAuthConsumer($consumer_key, $consumer_secret);
    // Yelp uses HMAC SHA1 encoding
    $signature_method = new OAuthSignatureMethod_HMAC_SHA1();
    $oauthrequest = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $unsigned_uri);
    // Sign the request
    $oauthrequest->sign_request($signature_method, $consumer, $token);
    // Get the signed URL
    $signed_url = $oauthrequest->to_url();
    $results = fetch_data($signed_url);
    // Ensure a business listing is returned and the location is not closed
    // permanently.
    if (array_key_exists("businesses", $results) && !$results["businesses"][0]["is_closed"]) {
        return $results["businesses"][0];
    }
    return null;
}
function immediate_update_outcome_in_canvas($oauth_consumer_key, $secret, $lti_sourced_id, $lis_outcome_service_url, $score)
{
    set_time_limit(180);
    $xmlRequest = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<imsx_POXEnvelopeRequest xmlns=\"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">\n    <imsx_POXHeader>\n        <imsx_POXRequestHeaderInfo>\n            <imsx_version>V1.0</imsx_version>\n            <imsx_messageIdentifier>999999123</imsx_messageIdentifier>\n        </imsx_POXRequestHeaderInfo>\n    </imsx_POXHeader>\n    <imsx_POXBody>\n        <replaceResultRequest>\n            <resultRecord>\n                <sourcedGUID>\n                    <sourcedId>{$lti_sourced_id}</sourcedId>\n                </sourcedGUID>\n                <result>\n                    <resultScore>\n                        <language>en</language>\n                        <textString>" . $score . "</textString>\n                    </resultScore>\n                </result>\n            </resultRecord>\n        </replaceResultRequest>\n    </imsx_POXBody>\n</imsx_POXEnvelopeRequest>";
    $hash = base64_encode(sha1($xmlRequest, TRUE));
    $params = array('oauth_body_hash' => $hash);
    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
    $consumer = new OAuthConsumer($oauth_consumer_key, $secret, NULL);
    $req = OAuthRequest::from_consumer_and_token($consumer, NULL, 'POST', $lis_outcome_service_url, $params);
    $req->sign_request($hmac_method, $consumer, NULL);
    $params = $req->get_parameters();
    $header = $req->to_header();
    $header .= "\nContent-type: application/xml";
    $ext_response = do_post_request($lis_outcome_service_url, $xmlRequest, $header);
    $ext_doc = new DOMDocument();
    set_error_handler(array($this, 'HandleXmlError'));
    $ext_doc->loadXML($ext_response);
    restore_error_handler();
    $ext_nodes = domnode_to_array($ext_doc->documentElement);
    if (!isset($ext_nodes['imsx_POXHeader']['imsx_POXResponseHeaderInfo']['imsx_statusInfo']['imsx_codeMajor'])) {
        throw new Exception("No imsx_codeMajor from outcome service for " . $lti_sourced_id);
    }
    if ($ext_nodes['imsx_POXHeader']['imsx_POXResponseHeaderInfo']['imsx_statusInfo']['imsx_codeMajor'] != 'success' && isset($ext_nodes['imsx_POXHeader']['imsx_POXResponseHeaderInfo']['imsx_statusInfo']['imsx_description']) && $ext_nodes['imsx_POXHeader']['imsx_POXResponseHeaderInfo']['imsx_statusInfo']['imsx_description'] != 'User is no longer in course') {
        throw new Exception("No success code from outcome service for " . $lti_sourced_id);
    }
}
 /**
  * Handle a request for temporary OAuth credentials
  *
  * Make sure the request is kosher, then emit a set of temporary
  * credentials -- AKA an unauthorized request token.
  *
  * @param array $args array of arguments
  *
  * @return void
  */
 function handle($args)
 {
     parent::handle($args);
     $datastore = new ApiStatusNetOAuthDataStore();
     $server = new OAuthServer($datastore);
     $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
     $server->add_signature_method($hmac_method);
     try {
         $req = OAuthRequest::from_request();
         // verify callback
         if (!$this->verifyCallback($req->get_parameter('oauth_callback'))) {
             throw new OAuthException("You must provide a valid URL or 'oob' in oauth_callback.", 400);
         }
         // check signature and issue a new request token
         $token = $server->fetch_request_token($req);
         common_log(LOG_INFO, sprintf("API OAuth - Issued request token %s for consumer %s with oauth_callback %s", $token->key, $req->get_parameter('oauth_consumer_key'), "'" . $req->get_parameter('oauth_callback') . "'"));
         // return token to the client
         $this->showRequestToken($token);
     } catch (OAuthException $e) {
         common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
         // Return 401 for for bad credentials or signature problems,
         // and 400 for missing or unsupported parameters
         $code = $e->getCode();
         $this->clientError($e->getMessage(), empty($code) ? 401 : $code, 'text');
     }
 }
Example #17
0
/**
 * Uses two-legged OAuth to respond to a Google documents list API request
 * @param string $base_feed Full URL of the resource to access
 * @param array $params (optional) parameters to be added to url line
 * @param string $type The HTTP method (GET, POST, PUT, DELETE)
 * @param string $postData (optional) POST/PUT request body
 * @param string $version (optional) if not sent will be set to 3.0
 * @param string $content_type (optional) what kind of content is being sent
 * @param string $slug (optional) used in determining the revision of a document
 * @param boolean $batch is this a batch transmission?
 * @return string $response body from the server
 */
function twolegged($base_feed, $params, $type, $postdata = null, $version = null, $content_type = null, $slug = null, $batch = null)
{
    global $CFG;
    require_once $CFG->dirroot . '/repository/morsle/lib.php';
    // for morsle_decode
    require_once $CFG->dirroot . '/google/oauth.php';
    // Establish an OAuth consumer based on our admin 'credentials'
    if (!($CONSUMER_KEY = get_config('morsle', 'consumer_key'))) {
        return NULL;
    }
    if (!($CONSUMER_SECRET = get_config('morsle', 'oauthsecretstr'))) {
        return NULL;
    }
    $CONSUMER_SECRET = morsle_decode($CONSUMER_SECRET);
    $consumer = new OAuthConsumer($CONSUMER_KEY, $CONSUMER_SECRET, NULL);
    // Create an Atom entry
    $contactAtom = new DOMDocument();
    //    $contactAtom = null;
    $request = OAuthRequest::from_consumer_and_token($consumer, NULL, $type, $base_feed, $params);
    // Sign the constructed OAuth request using HMAC-SHA1
    $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
    //  scope=https://docs.google.com/feeds/%20http://spreadsheets.google.com/feeds/%20https://docs.googleusercontent.com/
    // Make signed OAuth request to the Contacts API server
    if (!is_null($params)) {
        $url = $base_feed . '?' . implode_assoc('=', '&', $params);
    } else {
        $url = $base_feed;
    }
    $header_request = $request->to_header();
    $response = send_request($request->get_normalized_http_method(), $url, $header_request, $contactAtom, $postdata, $version, $content_type, $slug, $batch);
    return $response;
}
Example #18
0
function signParameters($oldparms, $endpoint, $method, $key, $secret, $org_secret, $org_id, $org_desc)
{
    global $last_base_string;
    $parms = $oldparms;
    $parms["lti_version"] = "LTI-1p0";
    $parms["lti_message_type"] = "basic-lti-launch-request";
    if ($org_id) {
        $parms["tool_consumer_instance_guid"] = $org_id;
    }
    if ($org_desc) {
        $parms["tool_consumer_instance_description"] = $org_desc;
        $parms["tool_consumer_instance_name"] = $org_desc;
    }
    $parms["basiclti_submit"] = "Launch Tool";
    $parms["oauth_callback"] = "about:blank";
    if ($org_secret) {
        $oauth_consumer_secret = $org_secret;
        $oauth_consumer_key = $org_id;
    } else {
        $oauth_consumer_secret = $secret;
        $oauth_consumer_key = $key;
    }
    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
    $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
    $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
    $acc_req->sign_request($hmac_method, $test_consumer, $test_token);
    // Pass this back up "out of band" for debugging
    $last_base_string = $acc_req->get_signature_base_string();
    $newparms = $acc_req->get_parameters();
    return $newparms;
}
 protected function execute($arguments = array(), $options = array())
 {
     require_once realpath(dirname(__FILE__) . '/../../../../lib/vendor/OAuth/OAuth.php');
     new sfDatabaseManager($this->configuration);
     sfContext::createInstance($this->createConfiguration('pc_frontend', 'prod'), 'pc_frontend');
     $consumerKey = isset($options['consumer-key']) && $options['consumer-key'] ? $options['consumer-key'] : opOpenSocialToolKit::getOAuthConsumerKey();
     $consumer = new OAuthConsumer($consumerKey, null, null);
     $signatureMethod = new OAuthSignatureMethod_RSA_SHA1_opOpenSocialPlugin();
     $httpOptions = opOpenSocialToolKit::getHttpOptions();
     $queueGroups = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueueGroups();
     $limitRequest = (int) $options['limit-request'];
     $limitRequestApp = (int) $options['limit-request-app'];
     $allRequest = 0;
     foreach ($queueGroups as $group) {
         $application = Doctrine::getTable('Application')->find($group[0]);
         $links = $application->getLinks();
         $linkHash = array();
         foreach ($links as $link) {
             if (isset($link['rel']) && isset($link['href'])) {
                 $method = isset($link['method']) ? strtolower($link['method']) : '';
                 $method = 'post' !== $method ? 'get' : 'post';
                 $linkHash[$link['rel']] = array('href' => $link['href'], 'method' => $method);
             }
         }
         $queues = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueuesByApplicationId($group[0], $limitRequestApp);
         foreach ($queues as $queue) {
             if (!isset($linkHash[$queue->getName()])) {
                 $queue->delete();
                 continue;
             }
             $href = $linkHash[$queue->getName()]['href'];
             $method = $linkHash[$queue->getName()]['method'];
             $oauthRequest = OAuthRequest::from_consumer_and_token($consumer, null, $method, $href, $queue->getParams());
             $oauthRequest->sign_request($signatureMethod, $consumer, null);
             $client = new Zend_Http_Client();
             if ('post' !== $method) {
                 $method = 'get';
                 $client->setMethod(Zend_Http_Client::GET);
                 $href .= '?' . $oauthRequest->to_postdata();
             } else {
                 $client->setMethod(Zend_Http_Client::POST);
                 $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED);
                 $client->setRawData($oauthRequest->to_postdata());
             }
             $client->setConfig($httpOptions);
             $client->setUri($href);
             $client->setHeaders($oauthRequest->to_header());
             $response = $client->request();
             if ($response->isSuccessful()) {
                 $queue->delete();
             }
             $allRequest++;
             if ($limitRequest && $limitRequest <= $allRequest) {
                 break 2;
             }
         }
         $application->free(true);
         $queues->free(true);
     }
 }
function get_pco_data($url,$method = "GET",$content = Null){
	global $pco_key, $pco_secret, $user_access_token, $user_access_token_secret;

	$test_consumer  = new OAuthConsumer($pco_key, $pco_secret, NULL);
	$access_consumer = new OAuthConsumer($user_access_token, $user_access_token_secret, NULL);

	// build and sign request
	$request = OAuthRequest::from_consumer_and_token($test_consumer,
	  $access_consumer, 
	  $method,
	  $url, 
	  NULL);
	$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),
	  $test_consumer, 
	  $access_consumer
	);
	
	if (isset($content)){
		//define request headers
		$headers = array("Accept: application/xml");
		$headers[] = $request->to_header();
		$headers[] = "Content-type: application/xml";
		$response = run_curl($url, $method, $headers, $content);
	}
	else {
		// make GET request
		$response = run_curl($request, $method);
	}
	
	return $response;

}
 public function validate_request()
 {
     $result = true;
     // Is gadget_url specified?
     if (sizeof($this->gadget_url) > 0) {
         // Does gadget_url match opensocial_app_id?
         if ($this->opensocial_app_url != $this->gadget_url) {
             $result = false;
         }
     }
     // Is this a signed request?
     if (!empty($this->oauth_consumer_key) && !empty($this->oauth_signature)) {
         $request = OAuthRequest::from_request(null, null, array_merge($_GET, $_POST));
         $signature_method = new ServerSignatureMethod();
         $signature_method->set_public_cert($this->oauth_consumer_key);
         // See if signature is valid
         if (!$signature_method->check_signature($request, null, null, $this->oauth_signature)) {
             $result = false;
         }
     } else {
         $result = false;
     }
     // If invalid request, return HTTP 401 response
     if (!$result) {
         header("HTTP/1.0 401 Unauthorized", true, 401);
         echo "<html><body>401 Unauthorized</body></html>";
         die;
     }
     // If valid request, go forward
     return true;
 }
 public function execute($filterChain)
 {
     require_once 'OAuth.php';
     $consumer = $token = null;
     try {
         $req = OAuthRequest::from_request();
         list($consumer, $token) = $this->getServer()->verify_request($req);
     } catch (OAuthException $e) {
         // do nothing
     }
     if ($consumer) {
         sfContext::getInstance()->getUser()->setAuthenticated(true);
         $information = Doctrine::getTable('OAuthConsumerInformation')->findByKeyString($consumer->key);
         if ($information) {
             sfContext::getInstance()->getUser()->addCredentials($information->getUsingApis());
         }
         $tokenType = $this->context->getRequest()->getParameter('token_type', 'member');
         if ('member' === $tokenType) {
             $accessToken = Doctrine::getTable('OAuthMemberToken')->findByKeyString($token->key, 'access');
             sfContext::getInstance()->getUser()->setAttribute('member_id', $accessToken->getMember()->id);
         }
     }
     $route = $this->context->getRequest()->getAttribute('sf_route');
     if ($route instanceof opAPIRouteInterface) {
         $actionInstance = $this->context->getController()->getActionStack()->getLastEntry()->getActionInstance();
         $config = $actionInstance->getSecurityConfiguration();
         if (!isset($config['all']['credentials'])) {
             $config['all']['credentials'] = array();
         }
         $config['all']['credentials'] = array_merge($config['all']['credentials'], array($route->getAPIName()));
         $actionInstance->setSecurityConfiguration($config);
     }
     $filterChain->execute();
 }
 /**
  * Class handler.
  *
  * @param array $args array of arguments
  *
  * @return void
  */
 function handle($args)
 {
     parent::handle($args);
     $datastore = new ApiStatusNetOAuthDataStore();
     $server = new OAuthServer($datastore);
     $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
     $server->add_signature_method($hmac_method);
     $atok = $app = null;
     // XXX: Insist that oauth_token and oauth_verifier be populated?
     // Spec doesn't say they MUST be.
     try {
         $req = OAuthRequest::from_request();
         $this->reqToken = $req->get_parameter('oauth_token');
         $this->verifier = $req->get_parameter('oauth_verifier');
         $app = $datastore->getAppByRequestToken($this->reqToken);
         $atok = $server->fetch_access_token($req);
     } catch (Exception $e) {
         common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
         common_debug(var_export($req, true));
         $code = $e->getCode();
         $this->clientError($e->getMessage(), empty($code) ? 401 : $code, 'text');
         return;
     }
     if (empty($atok)) {
         // Token exchange failed -- log it
         $msg = sprintf('API OAuth - Failure exchanging OAuth request token for access token, ' . 'request token = %s, verifier = %s', $this->reqToken, $this->verifier);
         common_log(LOG_WARNING, $msg);
         // TRANS: Client error given from the OAuth API when the request token or verifier is invalid.
         $this->clientError(_('Invalid request token or verifier.'), 400, 'text');
     } else {
         common_log(LOG_INFO, sprintf("Issued access token '%s' for application %d (%s).", $atok->key, $app->id, $app->name));
         $this->showAccessToken($atok);
     }
 }
Example #24
0
 function checkStatusByMerchantRef($pesapalMerchantReference)
 {
     $request_status = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, "GET", $this->QueryPaymentStatusByMerchantRef, $this->params);
     $request_status->set_parameter("pesapal_merchant_reference", $pesapalMerchantReference);
     $request_status->sign_request($this->signature_method, $this->consumer, $this->token);
     $status = $this->curlRequest($request_status);
     return $status;
 }
Example #25
0
 function update($status)
 {
     $tk = new TwitterToken();
     $req = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, 'POST', $tk->api_root . '/statuses/update.xml', array('status' => $status));
     $req->sign_request($this->method, $this->consumer, $this->token);
     $response = $this->http($req->get_normalized_http_url(), $req->to_postdata());
     return $response;
 }
Example #26
0
 public function add_headers(&$url, &$headers, &$data, &$type, &$options)
 {
     $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $options['type'], $url, $data);
     $request->sign_request($this->signature_method, $this->consumer, $this->token);
     $header = $request->to_header();
     // Strip leading 'Authorization:'
     $header = trim(substr($header, 14));
     $headers['Authorization'] = trim($header, ' ');
 }
Example #27
0
 function request($url, $method, $params = null)
 {
     $sign = new OAuthSignatureMethod_HMAC_SHA1();
     $request = OAuthRequest::from_consumer_and_token($this->consumer, null, $method, $url, $params);
     $request->sign_request($sign, $this->consumer, null);
     $ch = curl_init($request);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     return curl_exec($ch);
 }
Example #28
0
 public function getUserInfo($url, $accessToken)
 {
     $data_req = OAuthRequest::from_consumer_and_token($this->consumer, $accessToken, "GET", $url, NULL);
     $data_req->sign_request($this->signer, $this->consumer, $accessToken);
     $data = SimpleSAML_Utilities::fetch($data_req->to_url());
     #print_r($data);
     $dataDecoded = json_decode($data, TRUE);
     return $dataDecoded;
 }
function brukar_server_oauth_user()
{
    $server = _brukar_server();
    $request = OAuthRequest::from_request();
    list($consumer, $token) = $server->verify_request($request);
    $user = user_load($token->uid);
    echo json_encode(array('id' => $user->uid, 'name' => $user->name, 'mail' => $user->mail));
    exit;
}
Example #30
0
File: app.php Project: arfrank/Busk
 function play()
 {
     if ($this->session->userdata('user_id')) {
         //get oauth stuff
     } else {
         redirect('/join');
     }
     $this->load->library('form_validation');
     $this->form_validation->set_rules('name', 'Stage Name', 'required|trim');
     $this->form_validation->set_rules('paypal_email', 'Donation Email Address', 'required|trim');
     $this->form_validation->set_rules('website', 'Website URL', 'required|trim');
     if ($this->form_validation->run() == FALSE) {
         require_once "/Users/aaronfrank/Sites/busk/php/OAuth.php";
         require_once "/Users/aaronfrank/Sites/busk/php/OAuthConfig.php";
         $key = '';
         //'<your app's API key>';
         $secret = '';
         //'<your app's secret>';
         $request_token_endpoint = 'http://api.justin.tv/oauth/request_token';
         $oauth_access_token_endpoint = 'http://api.justin.tv/oauth/access_token';
         $authorize_endpoint = 'http://api.justin.tv/oauth/authorize';
         $test_consumer = new OAuthConsumer($key, $secret, NULL);
         //prepare to get request token
         $sig_method = new OAuthSignatureMethod_HMAC_SHA1();
         $parsed = parse_url($request_token_endpoint);
         $req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "GET", $request_token_endpoint);
         $req_req->sign_request($sig_method, $test_consumer, NULL);
         $req_token = doHttpRequest($req_req->to_url());
         //assuming the req token fetch was a success, we should have
         //oauth_token and oauth_token_secret
         parse_str($req_token, $tokens);
         $oauth_token = $tokens['oauth_token'];
         $oauth_token_secret = $tokens['oauth_token_secret'];
         $consumer = $test_consumer;
         // new OAuthConsumer($oauth_token, $oauth_token_secret, NULL);
         $auth_token = new OAuthConsumer($oauth_token, $oauth_token_secret);
         $access_token_req = new OAuthRequest("GET", $oauth_access_token_endpoint);
         $access_token_req = $access_token_req->from_consumer_and_token($test_consumer, $auth_token, "GET", $oauth_access_token_endpoint);
         $access_token_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, $auth_token);
         $after_access_request = doHttpRequest($access_token_req->to_url());
         $access_tokens = $tokens;
         $access_token = new OAuthConsumer($access_tokens['oauth_token'], $access_tokens['oauth_token_secret']);
         $streamkey_req = $access_token_req->from_consumer_and_token($consumer, $access_token, "GET", "http://api.justin.tv/api/stream/new_stream_key/busktv.xml");
         $streamkey_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, $access_token);
         $xml = doHttpRequest($streamkey_req->to_url());
         $xml_parser = xml_parser_create();
         xml_parse_into_struct($xml_parser, $xml, $vals, $index);
         $data['stream_key'] = $vals[0]['value'];
         $view_name = 'play_form';
     } else {
         $data['stream_key'] = $this->input->post('stream_key');
         $view_name = 'play';
     }
     $data['title'] = "Broadcast";
     $this->load->view($view_name, $data);
 }