Beispiel #1
0
    def from_consumer_and_token(
        oauth_consumer,
        token=None,
        callback=None,
        verifier=None,
        http_method=HTTP_METHOD,
        http_url=None,
        parameters=None,
    ):
        if not parameters:
            parameters = {}

        defaults = {
            constants.OAUTH_CONSUMER_KEY: oauth_consumer.key,
            constants.OAUTH_TIMESTAMP: generate_timestamp(),
            constants.OAUTH_NONCE: generate_nonce(),
            constants.OAUTH_VERSION: OAuthRequest.version,
        }

        defaults.update(parameters)
        parameters = defaults

        if token:
            parameters[constants.OAUTH_TOKEN] = token.key
            if token.callback:
                parameters[constants.OAUTH_CALLBACK] = token.callback
            # 1.0a support for verifier.
            if verifier:
                parameters[constants.OAUTH_VERIFIER] = verifier
        elif callback:
            # 1.0a support for callback in the request token request.
            parameters[constants.OAUTH_CALLBACK] = callback

        return PortalOAuthRequest(http_method, http_url, parameters)
Beispiel #2
0
    def from_consumer_and_token(oauth_consumer,
                                token=None,
                                callback=None,
                                verifier=None,
                                http_method=HTTP_METHOD,
                                http_url=None,
                                parameters=None):
        if not parameters:
            parameters = {}

        defaults = {
            constants.OAUTH_CONSUMER_KEY: oauth_consumer.key,
            constants.OAUTH_TIMESTAMP: generate_timestamp(),
            constants.OAUTH_NONCE: generate_nonce(),
            constants.OAUTH_VERSION: OAuthRequest.version,
        }

        defaults.update(parameters)
        parameters = defaults

        if token:
            parameters[constants.OAUTH_TOKEN] = token.key
            if token.callback:
                parameters[constants.OAUTH_CALLBACK] = token.callback
            # 1.0a support for verifier.
            if verifier:
                parameters[constants.OAUTH_VERIFIER] = verifier
        elif callback:
            # 1.0a support for callback in the request token request.
            parameters[constants.OAUTH_CALLBACK] = callback

        return PortalOAuthRequest(http_method, http_url, parameters)
Beispiel #3
0
    def sign_request(self, consumer, signature_method):
        """Add oauth parameters and sign the request with the given method.
    
    Args:
      consumer: The OAuthConsumer set with a key and secret.
      signature_method: A supported method for signing the built request.

    """
        params = {
            "oauth_consumer_key": consumer.key,
            "oauth_timestamp": oauth.generate_timestamp(),
            "oauth_nonce": oauth.generate_nonce(),
            "oauth_version": oauth.OAuthRequest.version,
        }

        # PHP OAuth library contains a bug which interferes with signing.  Since
        # some containers use this library, we will implement a workaround here.
        if self.use_body_as_signing_parameter:
            params[self.get_post_body()] = ""
        else:
            # Otherwise, use the oauth_body_hash extension to sign the request body.
            if self.post_body:
                body_hash = b64encode(hashlib.sha1(self.get_post_body()).digest())
                params["oauth_body_hash"] = body_hash

        if self.get_security_token():
            self.set_parameter("xoauth_requestor_id", None)

        self.set_parameters(params)
        self.oauth_request.sign_request(signature_method, consumer, None)
Beispiel #4
0
    def sign_request(self, consumer, signature_method):
        """Add oauth parameters and sign the request with the given method.
    
    Args:
      consumer: The OAuthConsumer set with a key and secret.
      signature_method: A supported method for signing the built request.

    """
        params = {
            "oauth_consumer_key": consumer.key,
            "oauth_timestamp": oauth.generate_timestamp(),
            "oauth_nonce": oauth.generate_nonce(),
            "oauth_version": oauth.OAuthRequest.version,
        }

        self.set_parameters(params)
        self.oauth_request.sign_request(signature_method, consumer, None)
Beispiel #5
0
    def build_access_headers(self,
                             method,
                             resource_url,
                             params=None,
                             request_token=None):
        """Build OAuth access headers for a future request.

        Args:
            method: The HTTP method being used (e.g. 'GET' or 'POST').
            resource_url: The full url the request will be made to.
            params: A dictionary of parameters to add to what's already on the url.
                Typically, this would consist of POST parameters.

        Returns:
            A tuple of (header_dict, params) where header_dict is a dictionary
            of header names and values appropriate for passing into dropbox.rest.RESTClient
            and params is a dictionary like the one that was passed in, but augmented with
            oauth-related parameters as appropriate.
        """
        if params is None:
            params = {}
        else:
            params = params.copy()

        oauth_params = {
            'oauth_consumer_key': self.consumer.key,
            'oauth_timestamp': oauth.generate_timestamp(),
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_version': oauth.OAuthRequest.version,
        }

        token = request_token if request_token else self.token

        if token:
            oauth_params['oauth_token'] = token.key

        params.update(oauth_params)

        oauth_request = oauth.OAuthRequest.from_request(method,
                                                        resource_url,
                                                        parameters=params)
        oauth_request.sign_request(self.signature_method, self.consumer, token)

        return oauth_request.to_header(), params
Beispiel #6
0
    def __init__(self,
                 tokens,
                 nojsoncallback=True,
                 format='json',
                 parameters=None):

        self.keys = hidden.keys()
        self.dbtokens = tokens

        self.dbtokens["token"].encode("ascii")
        self.dbtokens["token_secret"].encode('ascii')

        if self.dbtokens is not None:

            self.consumer = oauth.OAuthConsumer(
                self.keys["oauth_consumer_key"],
                self.keys["oauth_consumer_secret"])
            self.token = oauth.OAuthToken(
                self.dbtokens["token"].encode("ascii"),
                self.dbtokens["token_secret"].encode("ascii"))

            if nojsoncallback:
                self.nojsoncallback = 1
            else:
                self.nojsoncallback = 0
            if not parameters:
                parameters = {}

            self.url = "https://api.flickr.com/services/rest"

            defaults = {
                "format": format,
                "nojsoncallback": self.nojsoncallback,
                "oauth_timestamp": oauth.generate_timestamp(),
                "oauth_nonce": oauth.generate_nonce(),
                "signature_method": "HMAC-SHA1",
                "oauth_token": self.token.key,
                "api_key": self.consumer.key
            }
            #print defaults
            self.parameters = defaults

        else:
            print "token is none"
Beispiel #7
0
  def sign_request(self, consumer, signature_method):
    """Add oauth parameters and sign the request with the given method.
    
    Args:
      consumer: The OAuthConsumer set with a key and secret.
      signature_method: A supported method for signing the built request.

    """
    params = {
      'oauth_consumer_key': consumer.key,
      'oauth_timestamp': oauth.generate_timestamp(),
      'oauth_nonce': oauth.generate_nonce(),
      'oauth_version': oauth.OAuthRequest.version,
    }
    
    if self.get_security_token():
      self.set_parameter("xoauth_requestor_id", None)
    
    self.set_parameters(params)
    self.oauth_request.sign_request(signature_method, consumer, None)
Beispiel #8
0
    def sign_request(self, consumer, signature_method):
        """Add oauth parameters and sign the request with the given method.
    
    Args:
      consumer: The OAuthConsumer set with a key and secret.
      signature_method: A supported method for signing the built request.

    """
        params = {
            'oauth_consumer_key': consumer.key,
            'oauth_timestamp': oauth.generate_timestamp(),
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_version': oauth.OAuthRequest.version,
        }

        if self.get_security_token():
            self.set_parameter("xoauth_requestor_id", None)

        self.set_parameters(params)
        self.oauth_request.sign_request(signature_method, consumer, None)
    def sign_request(self, consumer, signature_method):
        """Add oauth parameters and sign the request with the given method.
    
    Args:
      consumer: The OAuthConsumer set with a key and secret.
      signature_method: A supported method for signing the built request.

    """
        params = {
            'oauth_consumer_key': consumer.key,
            'oauth_timestamp': oauth.generate_timestamp(),
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_version': oauth.OAuthRequest.version,
        }

        # PHP OAuth library contains a bug which interferes with signing.  Since
        # some containers use this library, we will implement a workaround here.
        if self.use_body_as_signing_parameter:
            params[self.get_post_body()] = ""
        else:
            # Otherwise, use the oauth_body_hash extension to sign the request body.
            if self.post_body:
                if VERBOSE > 0:
                    logging.info("post_body => %s" % str(self.post_body))

                if self.add_bodyhash:
                    body_hash = b64encode(
                        hashlib.sha1(self.get_post_body()).digest())
                    params['oauth_body_hash'] = body_hash

        if self.get_security_token():
            self.set_parameter("xoauth_requestor_id", None)

        self.set_parameters(params)
        if VERBOSE > 0:
            key, raw = signature_method.build_signature_base_string(
                self.oauth_request, consumer, None)
            logging.info("build_signature key => %s" % key)
            logging.info("build_signature raw => %s" % raw)

        self.oauth_request.sign_request(signature_method, consumer, None)
Beispiel #10
0
  def sign_request(self, consumer, signature_method):
    """Add oauth parameters and sign the request with the given method.
    
    Args:
      consumer: The OAuthConsumer set with a key and secret.
      signature_method: A supported method for signing the built request.

    """
    params = {
      'oauth_consumer_key': consumer.key,
      'oauth_timestamp': oauth.generate_timestamp(),
      'oauth_nonce': oauth.generate_nonce(),
      'oauth_version': oauth.OAuthRequest.version,
    }
          
    # PHP OAuth library contains a bug which interferes with signing.  Since
    # some containers use this library, we will implement a workaround here.
    if self.use_body_as_signing_parameter:
      params[self.get_post_body()] = ""
    else:
      # Otherwise, use the oauth_body_hash extension to sign the request body.
      if self.post_body:
        if VERBOSE > 0:
          logging.info("post_body => %s" % str(self.post_body))
          
        body_hash = b64encode(hashlib.sha1(self.get_post_body()).digest())
        params['oauth_body_hash'] = body_hash
      
    if self.get_security_token():
      self.set_parameter("xoauth_requestor_id", None)
    
    self.set_parameters(params)
    if VERBOSE > 0:
      key, raw = signature_method.build_signature_base_string(
                     self.oauth_request, consumer, None)
      logging.info("build_signature key => %s" % key)
      logging.info("build_signature raw => %s" % raw)
      
    self.oauth_request.sign_request(signature_method, consumer, None)
    def build_access_headers(self, method, resource_url, params=None, request_token=None):
        """Build OAuth access headers for a future request.

        Args:
            method: The HTTP method being used (e.g. 'GET' or 'POST').
            resource_url: The full url the request will be made to.
            params: A dictionary of parameters to add to what's already on the url.
                Typically, this would consist of POST parameters.

        Returns:
            A tuple of (header_dict, params) where header_dict is a dictionary
            of header names and values appropriate for passing into dropbox.rest.RESTClient
            and params is a dictionary like the one that was passed in, but augmented with
            oauth-related parameters as appropriate.
        """
        if params is None:
            params = {}
        else:
            params = params.copy()

        oauth_params = {
            'oauth_consumer_key': self.consumer.key,
            'oauth_timestamp': oauth.generate_timestamp(),
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_version': oauth.OAuthRequest.version,
        }

        token = request_token if request_token else self.token

        if token:
            oauth_params['oauth_token'] = token.key

        params.update(oauth_params)

        oauth_request = oauth.OAuthRequest.from_request(method, resource_url, parameters=params)
        oauth_request.sign_request(self.signature_method, self.consumer, token)

        return oauth_request.to_header(), params
Beispiel #12
0
	def __init__(self, tokens, nojsoncallback=True, format='json', parameters=None):

		self.keys = hidden.keys()
		self.dbtokens = tokens

		self.dbtokens["token"].encode("ascii")
		self.dbtokens["token_secret"].encode('ascii')

		if self.dbtokens is not None:

			self.consumer = oauth.OAuthConsumer(self.keys["oauth_consumer_key"], self.keys["oauth_consumer_secret"])
			self.token = oauth.OAuthToken(self.dbtokens["token"].encode("ascii"), self.dbtokens["token_secret"].encode("ascii"))

			if nojsoncallback:
				self.nojsoncallback = 1
			else:
				self.nojsoncallback = 0
			if not parameters:
				parameters = {}

			self.url = "https://api.flickr.com/services/rest"

			defaults = {
				"format": format,
				"nojsoncallback": self.nojsoncallback,
				"oauth_timestamp": oauth.generate_timestamp(),
				"oauth_nonce": oauth.generate_nonce(),
				"signature_method": "HMAC-SHA1",
				"oauth_token": self.token.key,
				"api_key": self.consumer.key
			}
			#print defaults
			self.parameters = defaults

		else:
			print "token is none"
Beispiel #13
0
def oauth_get_request_token(oaConsumer, url):
    '''Get an OAuth request token URL to use for verification. Returns a
       tuple of (token, url). The 'url' parameter indicates the destination
       for redirection once the user has validated the request.'''

    oaSig = oauth.OAuthSignatureMethod_HMAC_SHA1()

    oaReq = oauth.OAuthRequest(
        http_method = 'GET',
        http_url = OAUTH2_ENDPOINT_URL + '/get_request_token',
        parameters = {
            'oauth_nonce' : oauth.generate_nonce(),
            'oauth_timestamp' : oauth.generate_timestamp(),
            'oauth_consumer_key' : oaConsumer.key,
            'oauth_version' : '1.0',
            'xoauth_lang_pref' : 'en-us',
            'oauth_callback' : url,
        }
    )

    oaReq.sign_request(oaSig, oaConsumer, None)

    reqTokenResp = None
    try:
        reqTokenResp = urllib2.urlopen(oaReq.to_url())
        reqTokenRespContent = ''.join(reqTokenResp.readlines())

        oaReqToken = oauth.OAuthToken.from_string(reqTokenRespContent)

        return (
            oaReqToken,
            OAUTH2_ENDPOINT_URL + '/request_auth?' +
                urllib.urlencode([('oauth_token', oaReqToken.key)])
        )
    except urllib2.HTTPError, e:
        raise CascadeHTTPError(e)
Beispiel #14
0
    def call(self, method, params = [{}], id = None, oauthDefaults = {}):
        '''Call the given method using the specified parameters (which are
           passed directly as the 'params' value in the JSON payload).
           Returns a result object derived from un-serializing the response
           JSON data. The optional 'id' value is the Cascade call ID, which
           is not sent in the request if un-specified.

           The 'oauthDefaults' dictionary can be used to specify default OAuth
           parameter values. For example, one can use this to force a specific
           nonce or timestamp value. Any parameters not specifed in this
           dictionary fall back to their OAuth defaults (e.g. generate a new
           nonce).
           
           Raises a CascadeHTTPError if problems arise.'''

        # Populate OAuth parameters
        oauthParameters = {
            'oauth_nonce' : oauth.generate_nonce(),
            'oauth_timestamp' : oauth.generate_timestamp(),
            'oauth_consumer_key' : self.__oaConsumer.key,
            'oauth_version' : '1.0'
        }
        oauthParameters.update(oauthDefaults)

        # Populate Cascade parameters
        data = {
            'method' : method,
            'params' : params
        }
        if id:
            data['id'] = id
        data = simplejson.dumps(data)

        for attemptNo in range(0, 2):
            logging.debug('Making request %d / 2' % (attemptNo + 1))

            # Set the token every time through our loop, as we may have changed
            # our token due to it being stale
            oauthParameters['oauth_token'] = self.__oaToken.key

            # Construct and sign the request within our retry loop so that
            # we pick up any refresh of the access token
            oaReq = oauth.OAuthRequest(
                http_method = 'POST',
                http_url = JSON11_ENDPOINT_URL,
                parameters = oauthParameters
            )
            oaReq.sign_request(self.__oaSig, self.__oaConsumer, self.__oaToken)

            headers = { 'Content-Type' : 'application/json' }
            url = JSON11_ENDPOINT_URL

            if self.__sendAuthorizationHeader:
                headers.update(oaReq.to_header())
            else:
                url = oaReq.to_url()

            logging.debug('HTTP headers: ' + pprint.pformat(headers))

            cascadeResp = None
            try:
                cascadeReq = urllib2.Request(
                    url = url,
                    data = data,
                    headers = headers
                )

                cascadeResp = urllib2.urlopen(cascadeReq)

                return simplejson.loads(''.join(cascadeResp.readlines()))
            except urllib2.HTTPError, e:
                logging.info(
                    'HTTP request failed: code=%d; message=\'%s\'' % (
                        e.code, e.msg
                    )
                )

                # If we see something other than a 401 on our first attempt
                # to make the call, give up. Otherwise, attempt to refresh
                # our access token and try again.
                if attemptNo > 0 or e.code != 401:
                    raise CascadeHTTPError(e)

                logging.info('Refreshing OAuth access token ' + self.__oaToken.key)

                self.__oaToken = oauth_refresh_access_token(
                    self.__oaConsumer,
                    self.__oaToken
                )

                logging.info('New OAuth access token is ' + self.__oaToken.key)
            finally:
Beispiel #15
0
    def user_authorize(self):

        defaults = hidden.keys().copy()
        defaults["oauth_timestamp"] = oauth.generate_timestamp()
        defaults["oauth_nonce"] = oauth.generate_nonce()
        defaults["oauth_signature_method"] = "HMAC-SHA1"
        defaults["oauth_version"] = "1.0"
        defaults["oauth_callback"] = "https://www.flickr.com/"

        # Setup the consumer with api_key and api_secret
        consumer = oauth.OAuthConsumer(defaults["oauth_consumer_key"],
                                       defaults["oauth_consumer_secret"])
        # Create request
        oauth_req = oauth.OAuthRequest(http_method="GET",
                                       http_url=self.url_req_token,
                                       parameters=defaults)
        # Create signature
        oauth_req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                               consumer, None)

        url = oauth_req.to_url()

        print '* Calling Flickr...'
        print
        connection = urllib.urlopen(url)
        data = connection.read()

        request_token = {
            "oauth_token": re.findall("oauth_token=(.+)&", data)[0],
            "oauth_token_secret": re.findall("oauth_token_secret=(.+)",
                                             data)[0]
        }

        #print request_token
        token = oauth.OAuthToken(request_token["oauth_token"],
                                 request_token["oauth_token_secret"])

        print "Go to the following link in your browser:"
        print "http://www.flickr.com/services/oauth/authorize?oauth_token=%s&perms=read" % request_token[
            'oauth_token']
        print

        oauth_verifier = raw_input("Enter the verifier - ")
        print

        defaults["oauth_token"] = request_token["oauth_token"]
        defaults["oauth_verifier"] = oauth_verifier

        del defaults["oauth_consumer_secret"]

        oauth_req = oauth.OAuthRequest(http_method="GET",
                                       http_url=self.url_access_token,
                                       parameters=defaults)
        oauth_req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                               consumer, token)

        url = oauth_req.to_url()
        connection = urllib.urlopen(url)
        data = connection.read()

        defaults["oauth_token"] = re.findall("oauth_token=(.+?)&", data)[0]
        defaults["oauth_token_secret"] = re.findall(
            "oauth_token_secret=(.+?)&", data)[0]
        defaults["username"] = re.findall("username=(.+)", data)[0]
        defaults["user_nsid"] = re.findall("user_nsid=(.+?)&", data)[0]

        self.tokens["token"] = defaults["oauth_token"]
        self.tokens["token_secret"] = defaults["oauth_token_secret"]

        # Replace %40 in user_id, or the request url would be wrong
        if "%40" in defaults["user_nsid"]:
            self.user_id = defaults["user_nsid"].replace("%40", "@")
            print self.user_id
        else:
            self.user_id = defaults["user_nsid"]

        cur.execute('''INSERT INTO Tokens (token, secret) VALUES (?, ?)''',
                    (defaults["oauth_token"], defaults["oauth_token_secret"]))

        # Named placeholders style
        cur.execute('SELECT id FROM Tokens WHERE token=:t AND secret=:ts', {
            "t": defaults["oauth_token"],
            "ts": defaults["oauth_token_secret"]
        })
        token_id = cur.fetchone()[0]

        # Store username in database
        cur.execute(
            '''
			INSERT OR IGNORE INTO Users (name, token_id, user_id) VALUES (?, ?, ?)''',
            (defaults["username"], token_id, self.user_id))

        conn.commit()
Beispiel #16
0
    def post(self):

        # Loop around Cascade call to allow for retrying if we need to
        # refresh our OAuth access token.
        cascadeResp = None
        oaTokStr = self._oaToken.to_string()
        for attemptNo in range(0, 2):
            # We do our own Cascade request / response handling here, as the
            # API doesn't provide access to the underlying HTTP objects, which
            # we want to expose to our callers.
            oaReq = oauth.OAuthRequest(
                http_method = u'POST',
                http_url = cascade.JSON11_ENDPOINT_URL,
                parameters = {
                    u'oauth_nonce' : oauth.generate_nonce(),
                    u'oauth_timestamp' : oauth.generate_timestamp(),
                    u'oauth_consumer_key' : self._oaConsumer.key,
                    u'oauth_token' : self._oaToken.key,
                    u'oauth_version' : u'1.0'
                }
            )
            oaReq.sign_request(self._oaSig, self._oaConsumer, self._oaToken)
            headers = { 'Content-Type' : 'application/json' }
            url = oaReq.to_url();

            try:
                cascadeReq = urllib2.Request(
                    url = url,
                    data = self.request.body,
                    headers = headers
                )
                cascadeResp = urllib2.urlopen(cascadeReq)

                # We've gotten a 200 response, we're done
                break
            except urllib2.HTTPError, e:
                # Only attempt access token refresh if we haven't already done
                # so, and think that it might work.
                #
                # XXX: Note that there appears to be some bug in the Yahoo!
                #      OAuth implementation that causes really stale tokens to
                #      be rejected with 999 rather than 401.
                if attemptNo > 0 or (e.code != 401 and e.code != 999):
                    cascadeResp = e
                    break

                self._oaToken = cascade.oauth_refresh_access_token(
                    self._oaConsumer,
                    self._oaToken
                )
            except DownloadError, e:
                # We see this if we're getting throttled, wherein Yahoo!  will
                # return an HTTP status code 999 and leave the TCP connection
                # open, timing out the request.
                #
                # XXX: Because of the stale OAuth token bug mentioned above, we
                #      consider this a situation where we should refresh our
                #      OAuth token.
                if attemptNo > 0:
                    raise e

                self._oaToken = cascade.oauth_refresh_access_token(
                    self._oaConsumer,
                    self._oaToken
                )
Beispiel #17
0
 def test_gen_timestamp(self):
     exp = int(time.time())
     now = oauth.generate_timestamp()
     self.assertEqual(exp, now) 
Beispiel #18
0
	def user_authorize(self):

		defaults = hidden.keys().copy()
		defaults["oauth_timestamp"] = oauth.generate_timestamp()
		defaults["oauth_nonce"] = oauth.generate_nonce()
		defaults["oauth_signature_method"] = "HMAC-SHA1"
		defaults["oauth_version"] = "1.0"
		defaults["oauth_callback"] = "https://www.flickr.com/"

		# Setup the consumer with api_key and api_secret
		consumer = oauth.OAuthConsumer(defaults["oauth_consumer_key"], defaults["oauth_consumer_secret"])
		# Create request
		oauth_req = oauth.OAuthRequest(http_method="GET", http_url=self.url_req_token, parameters=defaults)
		# Create signature
		oauth_req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),consumer, None)

		url = oauth_req.to_url()

		print '* Calling Flickr...'
		print
		connection = urllib.urlopen(url)
		data = connection.read()

		request_token = {
			"oauth_token": re.findall("oauth_token=(.+)&",data)[0],
			"oauth_token_secret": re.findall("oauth_token_secret=(.+)",data)[0]
		}

		#print request_token
		token = oauth.OAuthToken(request_token["oauth_token"], request_token["oauth_token_secret"])

		print "Go to the following link in your browser:"
		print "http://www.flickr.com/services/oauth/authorize?oauth_token=%s&perms=read" % request_token['oauth_token']
		print

		oauth_verifier = raw_input("Enter the verifier - ")
		print

		defaults["oauth_token"] = request_token["oauth_token"]
		defaults["oauth_verifier"] = oauth_verifier

		del defaults["oauth_consumer_secret"]

		oauth_req = oauth.OAuthRequest(http_method="GET", http_url=self.url_access_token, parameters=defaults)
		oauth_req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),consumer, token)

		url = oauth_req.to_url()
		connection = urllib.urlopen(url)
		data = connection.read()

		defaults["oauth_token"] = re.findall("oauth_token=(.+?)&", data)[0]
		defaults["oauth_token_secret"] = re.findall("oauth_token_secret=(.+?)&", data)[0]
		defaults["username"] = re.findall("username=(.+)",data)[0]
		defaults["user_nsid"] = re.findall("user_nsid=(.+?)&",data)[0]

		self.tokens["token"] = defaults["oauth_token"]
		self.tokens["token_secret"] = defaults["oauth_token_secret"]

		# Replace %40 in user_id, or the request url would be wrong
		if "%40" in defaults["user_nsid"]:
			self.user_id = defaults["user_nsid"].replace("%40","@")
			print self.user_id
		else:
			self.user_id = defaults["user_nsid"]

		cur.execute('''INSERT INTO Tokens (token, secret) VALUES (?, ?)''',
			(defaults["oauth_token"], defaults["oauth_token_secret"]) )

		# Named placeholders style
		cur.execute('SELECT id FROM Tokens WHERE token=:t AND secret=:ts', {"t":defaults["oauth_token"], "ts":defaults["oauth_token_secret"]} )
		token_id = cur.fetchone()[0]

		# Store username in database
		cur.execute('''
			INSERT OR IGNORE INTO Users (name, token_id, user_id) VALUES (?, ?, ?)'''
			,(defaults["username"], token_id, self.user_id) )

		conn.commit()
Beispiel #19
0
def oauth_get_access_token(oaConsumer, oaReqToken):
    '''Get an OAuth access token from the given token (either request or
       access). Returns an oauth.OAuthToken, possibly  with some extra
       instance variables set to reflect presence of OAuth extension
       attributes in the response (e.g.  session handle, expiration time,
       etc). Can be called with an access token to attempt a refresh (which
       still returns a new token).'''

    oaSig = oauth.OAuthSignatureMethod_HMAC_SHA1()

    oaReqParams = {
        'oauth_nonce' : oauth.generate_nonce(),
        'oauth_timestamp' : oauth.generate_timestamp(),
        'oauth_consumer_key' : oaConsumer.key,
        'oauth_token' : oaReqToken.key,
        'oauth_version' : '1.0',
    }

    # If our token has a session handle, add it to our parmeter dictionary.
    # This should only be the case if we're requesting a new access token
    # (i.e. not doing a token refresh, as access tokens do not have a
    # verifier).
    if 'verifier' in oaReqToken.__dict__:
        oaReqParams['oauth_verifier'] = oaReqToken.verifier

    # If our token has a session handle, add it to our parmeter dictionary.
    # This should only be the case if we're doing a token refresh from an
    # access token.
    if 'session_handle' in oaReqToken.__dict__:
        oaReqParams['oauth_session_handle'] = oaReqToken.session_handle

    oaReq = oauth.OAuthRequest(
        http_method = 'GET',
        http_url = OAUTH2_ENDPOINT_URL + '/get_token',
        parameters = oaReqParams
    )

    oaReq.sign_request(oaSig, oaConsumer, oaReqToken)

    accTokenResp = None
    try:
        accTokenResp = urllib2.urlopen(oaReq.to_url())
        accTokenRespContent = ''.join(accTokenResp.readlines())

        accTok = oauth.OAuthToken.from_string(accTokenRespContent)

        # Look for any extra query parameters that provide data from OAuth
        # extensions that we might care about. Specifically, make sure to
        # grab the session handle so that we can refresh the access token.
        accTokParams = cgi.parse_qs(
            accTokenRespContent,
            keep_blank_values = False
        )
        if 'oauth_expires_in' in accTokParams:
            accTok.expires_on = \
                int(time.time()) + \
                int(accTokParams['oauth_expires_in'][0])
        if 'oauth_session_handle' in accTokParams:
            accTok.session_handle = accTokParams['oauth_session_handle'][0]
        if 'oauth_authorization_expires_in' in accTokParams:
            accTok.authorization_expires_on = \
                int(time.time()) + \
                int(accTokParams['oauth_authorization_expires_in'][0])
        if 'xoauth_yahoo_guid' in accTokParams:
            accTok.yahoo_guid = accTokParams['xoauth_yahoo_guid'][0]

        return accTok
    except urllib2.HTTPError, e:
        raise CascadeHTTPError(e)
Beispiel #20
0
def cmd_call(argv):
    '''Make a single Cascade call.'''

    op = OptionParser(
        usage = '''%prog call <method> [options]
        
Calls the Cascade method <method>. Parameters to the call should be passed on
stdin as a JSON blob. The results of the call are written to stdout.'''
    )
    op.add_option(
        '-i', dest = 'input', default = None,
        help = '''set the file from which to read input (default: stdin)'''
    )
    op.add_option(
        '-u', '--url-params', dest = 'urlParams', action = 'store_true',
        default = False,
        help = '''send OAuth parameters as URL query parameters, rather than 
using an Authorization header.'''
    )
    op.add_option(
        '-k', '--oauth-consumer-key', dest = 'oauthConsumerKey', default = None,
        help = '''the OAuth consumer key; required'''
    )
    op.add_option(
        '-s', '--oauth-consumer-secret', dest = 'oauthConsumerSecret', default = None,
        help = '''the OAuth consumer secret; required'''
    )
    op.add_option(
        '-a', '--oauth-access-token', dest = 'oauthAccessToken', default = None,
        help = '''the OAuth access token to use, in the form of a query string
from oauth_token_to_query_string(); this is the preferred method of specifying
an access token, over --oauth-access-token-* (default: %default)'''
    )
    op.add_option(
        '--oauth-access-token-key', dest = 'oauthAccessTokenKey', default = None,
        help = '''the OAuth access token key; required'''
    )
    op.add_option(
        '--oauth-access-token-secret', dest = 'oauthAccessTokenSecret',
        default = None,
        help = '''the OAuth access token secret; required'''
    )
    op.add_option(
        '--oauth-timestamp', dest = 'oauthTimestamp', type = 'int',
        default = oauth.generate_timestamp(),
        help = '''the timestamp to use for OAuth signing, in epoch seconds
(default: %default)'''
    )
    op.add_option(
        '--oauth-nonce', dest = 'oauthNonce', default = oauth.generate_nonce(),
        help = '''the nonce to use for OAuth signing (default: %default)'''
    )

    opts, args = op.parse_args(argv)
    PROG_NAME = op.get_prog_name()

    # Get our method name and parameters
    if len(args) != 1:
        op.print_usage(sys.stderr)
        sys.exit(1)

    methodName = args[0]

    inputFile = sys.stdin
    if opts.input:
        inputFile = open(opts.input, 'r')
    methodParams = simplejson.loads(''.join(inputFile.readlines()))
    if opts.input:
        inputFile.close()

    # Create our OAuth consumer
    if opts.oauthConsumerKey and \
       opts.oauthConsumerSecret:
        oaConsumer = oauth.OAuthConsumer(
            opts.oauthConsumerKey,
            opts.oauthConsumerSecret
        )
    else:
        sys.stderr.write(
            '\'%s\': consumer key options not specified\n' % (PROG_NAME)
        )
        op.print_usage(sys.stderr)
        sys.exit(1)

    # Create our OAuth access token
    if opts.oauthAccessToken:
        oaTok = oauth_token_from_query_string(opts.oauthAccessToken)
    elif opts.oauthAccessTokenKey and \
            opts.oauthAccessTokenSecret:
        oaTok = oauth.OAuthToken(
            opts.oauthAccessTokenKey,
            opts.oauthAccessTokenSecret
        )
    else:
        sys.stderr.write(
            '\'%s\': access token options not specified\n' % (PROG_NAME)
        )
        op.print_usage(sys.stderr)
        sys.exit(1)

    # Make the call, overriding any OAuth parametsrs as specified
    jc = JSON11Client(oaConsumer, oaTok, not opts.urlParams)

    oauthDefaults = {}
    if opts.oauthNonce:
        oauthDefaults['oauth_nonce'] = opts.oauthNonce
    if opts.oauthTimestamp:
        oauthDefaults['oauth_timestamp'] = opts.oauthTimestamp

    try:
        result = jc.call(
            methodName, 
            params = methodParams,
            oauthDefaults = oauthDefaults
        )
    except CascadeHTTPError, e:
        sys.stderr.write('\'%s\': call failed %s\n' % (PROG_NAME, str(e)))
        sys.exit(1)