Add an unautorized request token to our server.

@param string consumer_key
@param array options		(eg. token_ttl)
@return array (token, token_secret)
349207
public function addConsumerRequestToken ( $consumer_key, $options = array() )
	{
		$token  = $this->generateKey(true);
		$secret = $this->generateKey();
		 

		if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
		{
			$ttl = intval($options['token_ttl']);
		}
		else
		{
			$ttl = $this->max_request_token_ttl;
		}

		if (!isset($options['oauth_callback'])) {
	 		// 1.0a Compatibility : store callback url associated with request token
			$options['oauth_callback']='oob';
 		}
		$options_oauth_callback =$options['oauth_callback'];
		$sql = "BEGIN SP_ADD_CONSUMER_REQUEST_TOKEN(:P_TOKEN_TTL, :P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_SECRET, :P_CALLBACK_URL, :P_RESULT); END;";

			// parse sql
		$stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
 
		// Bind In and Out Variables
		oci_bind_by_name($stmt, ':P_TOKEN_TTL', $ttl, 20);
		oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
		oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
		oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $secret, 255);
		oci_bind_by_name($stmt, ':P_CALLBACK_URL', $options_oauth_callback, 255);
		oci_bind_by_name($stmt, ':P_RESULT', $result, 20);

		//Execute the statement
		oci_execute($stmt);
		

		$returnArray= array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl);
		return $returnArray;
	}
948405
def _post_patched_request(consumers, lti_key, body,
                          url, method, content_type):
    
    # pylint: disable=too-many-locals, too-many-arguments
    oauth_server = LTIOAuthServer(consumers)
    oauth_server.add_signature_method(SignatureMethod_HMAC_SHA1_Unicode())
    lti_consumer = oauth_server.lookup_consumer(lti_key)
    lti_cert = oauth_server.lookup_cert(lti_key)
    secret = lti_consumer.secret

    consumer = oauth2.Consumer(key=lti_key, secret=secret)
    client = oauth2.Client(consumer)

    if lti_cert:
        client.add_certificate(key=lti_cert, cert=lti_cert, domain='')
        log.debug("cert %s", lti_cert)

    import httplib2

    http = httplib2.Http
    # pylint: disable=protected-access
    normalize = http._normalize_headers

    def my_normalize(self, headers):
        """ This function patches Authorization header """
        ret = normalize(self, headers)
        if 'authorization' in ret:
            ret['Authorization'] = ret.pop('authorization')
        log.debug("headers")
        log.debug(headers)
        return ret

    http._normalize_headers = my_normalize
    monkey_patch_function = normalize
    response, content = client.request(
        url,
        method,
        body=body.encode('utf-8'),
        headers={'Content-Type': content_type})

    http = httplib2.Http
    # pylint: disable=protected-access
    http._normalize_headers = monkey_patch_function

    log.debug("key %s", lti_key)
    log.debug("secret %s", secret)
    log.debug("url %s", url)
    log.debug("response %s", response)
    log.debug("content %s", format(content))

    return response, content
1249640
public function setConsumerAccessTokenTtl ( $token, $token_ttl )
	{
		if ($token_ttl <= 0)
		{
			// Immediate delete when the token is past its ttl
			$this->deleteConsumerAccessToken($token, 0, true);
		}
		else
		{
			// Set maximum time to live for this token
			 
			
			$sql = "BEGIN SP_SET_CONSUMER_ACC_TOKEN_TTL(:P_TOKEN, :P_TOKEN_TTL, :P_RESULT); END;";

			// parse sql
			$stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');

			// Bind In and Out Variables
			oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
			oci_bind_by_name($stmt, ':P_TOKEN_TTL', $token_ttl, 20);
			oci_bind_by_name($stmt, ':P_RESULT', $result, 20);


			//Execute the statement
			oci_execute($stmt);
		}
	}
1211613
function request($uri,$method,$token=NULL) {
		$web=\Web::instance();
		$options=[
			'method'=>$method,
			'content'=>http_build_query($this->args),
			'header'=>['Accept: application/json']
		];
		if ($token)
			array_push($options['header'],'Authorization: Bearer '.$token);
		elseif ($method=='POST' && isset($this->args['client_id']))
			array_push($options['header'],'Authorization: Basic '.
				base64_encode(
					$this->args['client_id'].':'.
					$this->args['client_secret']
				)
			);
		$response=$web->request($uri,$options);
		if ($response['error'])
			user_error($response['error'],E_USER_ERROR);
		if (isset($response['body'])) {
			if (preg_grep('/^Content-Type:.*application\/json/i',
				$response['headers'])) {
				$token=json_decode($response['body'],TRUE);
				if (isset($token['error_description']))
					user_error($token['error_description'],E_USER_ERROR);
				if (isset($token['error']))
					user_error($token['error'],E_USER_ERROR);
				return $token;
			}
			else
				return $response['body'];
		}
		return FALSE;
	}
1314119
private function get_token(&$request, $consumer, $token_type="access") {
    $token_field = @$request->get_parameter('oauth_token');
    if ( !$token_field) return false;
    $token = $this->data_store->lookup_token(
      $consumer, $token_type, $token_field
    );
    if (!$token) {
      throw new OAuthException("Invalid $token_type token: $token_field");
    }
    return $token;
  }
966468
public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false )
    {
        $consumer = $this->query_row_assoc('
                        SELECT    *
                        FROM oauth_server_registry
                        WHERE osr_consumer_key = \'%s\'
                        ', $consumer_key);

        if (!is_array($consumer))
        {
            throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"');
        }

        $c = array();
        foreach ($consumer as $key => $value)
        {
            $c[substr($key, 4)] = $value;
        }
        $c['user_id'] = $c['usa_id_ref'];

        if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id)
        {
            throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"');
        }
        return $c;
    }
19765
def sign_request(method, uri, form_args)
      # Convert non-string keys to strings so the sort works
      args = {}
      if form_args
        form_args.each do |key, value|
          next unless value and value != ""

          key = key.to_s unless key.is_a?(String)
          args[key] = value
        end
      end

      # Add the necessary OAuth args
      args["oauth_version"] = "1.0"
      args["oauth_consumer_key"] = @config[:api_key]
      args["oauth_nonce"] = Digest::MD5.hexdigest("#{Time.now.to_f}#{rand(10 ** 30)}")
      args["oauth_signature_method"] = "HMAC-SHA1"
      args["oauth_timestamp"] = Time.now.utc.to_i
      args["oauth_token"] = @config[:user][:token]

      # RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says:
      #
      #     Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
      #     reserved characters used for their reserved purposes may be used
      #     unencoded within a URL.
      #
      # However, if we don't escape apostrophes and parentheses the SmugMug API fails
      # with an invalid signature error:
      #
      #     Error #35, invalid signature (SmugMug::OAuthError)
      #
      # To overcome this, define a new unreserved character list and use this in URI::escape
      unreserved = "\\-_.!~*a-zA-Z\\d"
      unsafe = Regexp.new("[^#{unreserved}]", false, 'N')

      # Sort the params
      sorted_args = []
      args.sort.each do |key, value|
        sorted_args.push("#{key.to_s}=#{URI::escape(value.to_s, unsafe)}")
      end

      postdata = sorted_args.join("&")

      # Final string to hash
      sig_base = "#{method}&#{URI::escape("#{uri.scheme}://#{uri.host}#{uri.path}", unsafe)}&#{URI::escape(postdata, unsafe)}"

      signature = OpenSSL::HMAC.digest(@digest, "#{@config[:oauth_secret]}&#{@config[:user][:secret]}", sig_base)
      signature = URI::escape(Base64.encode64(signature).chomp, unsafe)

      if uri == API_URI
        "#{postdata}&oauth_signature=#{signature}"
      else
        args["oauth_signature"] = signature
        args
      end
    end
271009
public function setPublicKey(\OAuth2\ServerBundle\Entity\ClientPublicKey $public_key = null)
    {
        $this->public_key = $public_key;

        return $this;
    }
356390
public function lookup_token($consumer, $token_type, $token)
	{
  		\common_Logger::d(__CLASS__.'::'.__FUNCTION__.' called for token '.$token.' of type '.$token_type);
		return new OAuthToken($consumer, "");
	}
404835
private function check_signature(&$request, $consumer, $token)
    {
        // this should probably be in a different method
        $timestamp = @$request->get_parameter('oauth_timestamp');
        $nonce = @$request->get_parameter('oauth_nonce');

        $this->check_timestamp($timestamp);
        $this->check_nonce($consumer, $token, $nonce, $timestamp);

        $signature_method = $this->get_signature_method($request);

        $signature = $request->get_parameter('oauth_signature');
        $valid_sig = $signature_method->check_signature(
            $request,
            $consumer,
            $token,
            $signature
        );

        if (!$valid_sig) {
            throw new Exception("Invalid signature");
        }
    }
1179992
private function convertRequestToken($consumer_key, $request_token)
    {
        $params = array(
            'consumer_key'  => $consumer_key,
            'code'  => $request_token
        );

        $request = $this->getClient()->post('/v3/oauth/authorize');
        $request->getParams()->set('redirect.strict', true);
        $request->setHeader('Content-Type', 'application/json; charset=UTF8');
        $request->setHeader('X-Accept', 'application/json');
        $request->setBody(json_encode($params));
        $response = $request->send();

        $data = json_decode($response->getBody());

        return $data;
    }
982484
public function countServerTokens ( $consumer_key )
	{
		
                //
                $count =0;
                $sql = "BEGIN SP_COUNT_SERVICE_TOKENS(:P_CONSUMER_KEY, :P_COUNT, :P_RESULT); END;";

                // parse sql
                $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');

                // Bind In and Out Variables
                oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
                oci_bind_by_name($stmt, ':P_COUNT', $count, 40);
                oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
                
                //Execute the statement
                oci_execute($stmt);                
                //
		return $count;
	}
1310178
private function getToken($request, $consumer, $token_type = "access")
    {
        $token_field = $request instanceof Request
            ? $request->getParameter('oauth_token')
            : null;

        $token = $this->data_store->lookupToken(
            $consumer,
            $token_type,
            $token_field
        );
        if (!$token) {
            throw new Exception("Invalid $token_type token: $token_field");
        }
        return $token;
    }
679753
protected function get_url_with_auth( $consumer_key, $consumer_secret ) {

		$auth = new WC_API_Client_Authentication( $this->request->url, $consumer_key, $consumer_secret );

		if ( $auth->is_ssl() ) {

			// query string authentication over SSL works with all servers, whereas HTTP basic auth fails in certain cases
			// see https://github.com/kloon/WooCommerce-REST-API-Client-Library/issues/29
			$this->request->params = array_merge( $this->request->params, array(
				'consumer_key'    => $auth->get_consumer_key(),
				'consumer_secret' => $auth->get_consumer_secret(),
			) );

		} else {

			$this->request->params = array_merge( $this->request->params, $auth->get_oauth_params( $this->request->params, $this->request->method ) );
		}

		// build url
		return $this->request->url . ( ! empty( $this->request->params ) ? '?' . http_build_query( $this->request->params ) : '' );
	}
1276136
public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' )
	{
 		// 1.0a Compatibility : create a token verifier
 		$verifier = substr(md5(rand()),0,10);
		
		$this->query('
					UPDATE oauth_server_token
					SET ost_authorized    = 1,
						ost_usa_id_ref    = %d,
						ost_timestamp     = NOW(),
						ost_referrer_host = \'%s\',
						ost_verifier      = \'%s\'
					WHERE ost_token      = \'%s\'
					  AND ost_token_type = \'request\'
					', $user_id, $referrer_host, $verifier, $token);
		return $verifier;
	}
1665
def set_oauth_client(self, consumer_key, consumer_secret):
        
        self.oauth_client = oauth1.Client(consumer_key, consumer_secret)
213010
def authorize_from_request(rtoken, rsecret, verifier_or_pin)
      request_token = ::OAuth::RequestToken.new(consumer, rtoken, rsecret)
      access_token = request_token.get_access_token(:oauth_verifier => verifier_or_pin)
      @atoken, @asecret = access_token.token, access_token.secret
    end