def _get_auth_headers(self, method, url): oauth_params = { 'oauth_version': "1.0", 'oauth_nonce': generate_nonce(), 'oauth_timestamp': int(time.time()) } oauth_request = OAuthRequest(method, url, parameters=oauth_params) consumer = Consumer(self.current_user, self.oauth_secret) oauth_request.sign_request(SignatureMethod_HMAC_SHA1(), consumer, None) auth_headers = oauth_request.to_header() auth_headers['Authorization'] = auth_headers['Authorization'].encode('utf-8') return auth_headers
def get_auth_url(self, callback_url): # get request token oauth_request = Request.from_consumer_and_token( self.consumer, http_method="POST", http_url=self.request_token_url, parameters={'oauth_callback': callback_url}) oauth_request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, None) token = self.fetch_request_token(oauth_request) # get authorization url oauth_request = Request.from_token_and_callback( token=token, http_url=self.authorization_url) return oauth_request.to_url(), token
def oauth_authorization_request(self, token): """Generate OAuth request to authorize token.""" params = self.auth_extra_arguments() or {} params.update(self.get_scope_argument()) return OAuthRequest.from_token_and_callback( token=token, callback=self.redirect_uri, http_url=self.AUTHORIZATION_URL, parameters=params )
def oauth_authorization_request(self, token): """Generate OAuth request to authorize token.""" return OAuthRequest.from_consumer_and_token( self.consumer, token=token, http_url=self.AUTHORIZATION_URL )
def _get_signed_oauth_request(self, path, method, data=None): data = data if data is not None else self._data url = self._url_base + path method = method if method else 'GET' req = Request.from_consumer_and_token(self.consumer, {}, method, url, data) req.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, None) return req
def request( self, uri, method="GET", body="", headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None, parameters=None, ): if not isinstance(headers, dict): headers = {} req = Request.from_consumer_and_token( self.consumer, token=self.token, http_method=method, http_url=uri, parameters=parameters, body=body, is_form_encoded=True, ) req.sign_request(self.method, self.consumer, self.token) uri = req.to_url() return httplib2.Http.request( self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type, )
def get_access_token(self, key, secret, verifier): token = Token(key, secret) token.set_verifier(verifier) oauth_request = Request.from_consumer_and_token( self.consumer, http_method="POST", token=token, http_url=self.request_token_url) oauth_request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, None) return self.fetch_access_token(oauth_request)
def oauth_authorization_request(self, token): """Generate OAuth request to authorize token.""" params = self.auth_extra_arguments() or {} params.update(self.get_scope_argument()) params.update({"oauth_nonce":OAuthRequest.make_nonce()}) params.update({"oauth_timestamp":OAuthRequest.make_timestamp()}) params.update({"method": "profile.get_auth"}) request = OAuthRequest.from_token_and_callback( token=token, callback=self.redirect_uri, http_url=self.AUTHORIZATION_URL, parameters=params ) request.is_form_encoded = True consumer = OAuthConsumer(*self.get_key_and_secret()) request.sign_request(SignatureMethod_HMAC_SHA1(), consumer, token) return request
def get_access_token(self, request_key=None, request_secret=None, token=None): if request_key and request_secret: request_token = Token(request_key, request_secret) assert request_token is not None request = Request.from_consumer_and_token(self.consumer, token=request_token, http_url=ACCESS_TOKEN_URL) request.sign_request(_signature_method, self.consumer, request_token) return self.fetch_token(request)[:3]
def _make_request(self, requestURL, param=None): request = Request.from_consumer_and_token(consumer=self.consumer, token=self.token, http_method='POST', http_url=requestURL, parameters=param, is_form_encoded=True) request.sign_request(self.sign_method, self.consumer, self.token) return request
def get_oauth_request(self, url=None, token=None, **params): request = OAuthRequest.from_consumer_and_token( self.get_consumer(), token=token, http_url=url or self.ENDPOINT, parameters=params ) request.sign_request(SignatureMethod_HMAC_SHA1(), self.get_consumer(), token) return request
def test_two_legged_api(self): request = Request.from_consumer_and_token(self.consumer, None, 'GET', self.two_legged_api_url, {'msg': 'expected response'}) request.sign_request(self.signature_method, self.consumer, None) response = self.client.get(self.two_legged_api_path, request) self.assertEquals(response.status_code, 200) self.assertIn('world', response.content)
def query(self, query, pprint=False): self.oauth_params.update({'sql': query}) oauth_request = Request.from_consumer_and_token( self.consumer, token=self.token, http_method='POST', http_url=self.url, parameters=self.oauth_params) oauth_request.sign_request(self.signature_method_hmac_sha1, self.consumer, self.token) return self.parse(self.access_resource(oauth_request).splitlines(), pprint)
def auth(callback_url): # setup client = SimpleClient(SERVER, REQUEST_TOKEN_URL, ACCESS_TOKEN_URL) consumer = Consumer(CONSUMER_KEY, CONSUMER_SECRET) # get request token oauth_request = Request.from_consumer_and_token( consumer, http_method="POST", http_url=client.request_token_url, parameters={'oauth_callback': callback_url}) oauth_request.sign_request(SignatureMethod_HMAC_SHA1(), consumer, None) token = client.fetch_request_token(oauth_request) cache.set('app.root.view.post::oauth_token', token.key, 300) cache.set('app.root.view.post::oauth_token_secret', token.secret, 300) oauth_request = Request.from_token_and_callback( token=token, http_url=AUTHORIZATION_URL) return oauth_request.to_url()
def oauth_post_request(self, token, url, params): """Generate OAuth request, setups callback url""" if 'oauth_verifier' in self.data: params['oauth_verifier'] = self.data['oauth_verifier'] request = OAuthRequest.from_consumer_and_token(self.consumer, token=token, http_url=url, parameters=params, http_method='POST') request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, token) return request
def oauth_request(self, token, url, extra_params=None): """Generate OAuth request, setups callback url""" params = {"oauth_callback": self.redirect_uri} if extra_params: params.update(extra_params) if "oauth_verifier" in self.data: params["oauth_verifier"] = self.data["oauth_verifier"] request = OAuthRequest.from_consumer_and_token(self.consumer, token=token, http_url=url, parameters=params) request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, token) return request
def oauth_authorization_request_(self, token): """Generate OAuth request to authorize token.""" request = OAuthRequest.from_token_and_callback( token=token, http_url=self.AUTHORIZATION_URL, ) request.is_form_encoded = True consumer = OAuthConsumer(*self.get_key_and_secret()) request.sign_request(SignatureMethod_HMAC_SHA1(), consumer, token) return request
def get_stream_file(self,content_path): url = "https://files.one.ubuntu.com" + content_path.replace(' ','%20') # Get Oauth1 signature req = Requ.from_consumer_and_token(self.consumer, token=self.token, http_method='GET', http_url=url, parameters=None, body='') req.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, self.token) realm = "https://files.one.ubuntu.com" header = req.to_header(realm=realm) return requests.get(url, stream=True, headers=header)
def oauth_request(self, token, url, extra_params=None): params = {'oauth_callback': self.redirect_uri} if extra_params: params.update(extra_params) if 'oauth_verifier' in self.data: params['oauth_verifier'] = self.data['oauth_verifier'] request = OAuthRequest.from_consumer_and_token( self.consumer, token=token, http_url=url, parameters=params) request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, token) return request
def get_request_token(self, callback='oob'): path = self.get_oauth_path('get_request_token') url = self.get_url(path) request = Request.from_consumer_and_token(self.consumer, None, 'GET', url, {'oauth_callback': callback}) request.sign_request(self.signature_method, self.consumer, None) response = self.client.get(path, request) self.assertEquals(response.status_code, 200) params = dict(parse_qsl(response.content)) return Token(params['oauth_token'], params['oauth_token_secret'])
def _get_request(self, consumer, token, uri, **kwargs): """Prepare an oauth request based on arguments""" request = Request.from_consumer_and_token( consumer, token, http_url=uri, http_method=kwargs.get("method", HTTP_METHOD), parameters=kwargs.get("params"), body=kwargs.get("body", ""), is_form_encoded=bool(kwargs.get("body", False)), ) request.sign_request(self.method, consumer, token) return request
def test_three_legged_api(self): consumer = OAConsumer(self.consumer.key, self.consumer.secret) access_token = self.get_access_token(CALLBACK_URL) request = Request.from_consumer_and_token(consumer, access_token, 'GET', self.three_legged_api_url, {'msg': 'expected response'}) request.sign_request(self.signature_method, consumer, access_token) response = self.client.get(self.three_legged_api_path, request) self.assertEquals(response.status_code, 200) self.assertIn('world', response.content)
def access_token_request(self, token, url, extra_params=None): """Generate Access token request, setups callback url""" params = {} if extra_params: params.update(extra_params) if 'oauth_verifier' in self.data: params['oauth_verifier'] = self.data['oauth_verifier'] request = OAuthRequest.from_consumer_and_token(self.consumer, token=token, http_url=url, parameters=params) request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, token) return request
def oauth_request(cyclone_req): "returns an oauth2.Request object from a cyclone request" """ parameters = dict method = str url = str """ params = {} for x in cyclone_req.arguments.iterkeys(): params[x] = cyclone_req.arguments[x][0] ret = Request.from_request(cyclone_req.method, '%s://%s%s' % \ (cyclone_req.protocol, cyclone_req.host, cyclone_req.path), cyclone_req.headers, params, cyclone_req.query) return ret
def oauth_request(self, token, url, extra_params=None): """Generate OAuth request, setups callback url""" params = {'oauth_callback': self.redirect_uri} if extra_params: params.update(extra_params) if 'oauth_verifier' in self.data: params['oauth_verifier'] = self.data['oauth_verifier'] request = OAuthRequest.from_consumer_and_token(self.consumer, token=token, http_url=url, parameters=params) request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, token) return request
def make_authorization_url(self): """ Generate the authorization URL on the Mobile Vikings site. You can redirect your user to this page to allow her to grant your application access to her data. Returns a `str`. """ request = Request.from_consumer_and_token( consumer=self.consumer, token=self.request_token, http_url=self.AUTHORIZE_TOKEN_URL, ) return request.to_url()
def signing_base(self, request: oauth2.Request, consumer: oauth2.Consumer, token: oauth2.Token) -> Tuple[str, str]: if not hasattr(request, 'normalized_url') or request.normalized_url is None: raise ValueError("Base URL for request is not set.") sig = ( oauth2.escape(request.method), oauth2.escape(request.normalized_url), oauth2.escape(request.get_normalized_parameters()), ) key = f'oauth.escape(consumer.secret)&{oauth2.escape(token.secret) if token else ""}' raw = '&'.join(sig) return key, raw
def oauth_request(self, token, url, oauth_verifier=None, extra_params=None): """Generate OAuth request, setups callback url""" params = {} if self.redirect_uri: params['oauth_callback'] = self.redirect_uri if extra_params: params.update(extra_params) if oauth_verifier: params['oauth_verifier'] = oauth_verifier request = OAuthRequest.from_consumer_and_token(self.consumer, token=token, http_url=url, parameters=params) request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, token) return request
def request(self, uri, method="GET", body='', headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None, parameters=None): if not isinstance(headers, dict): headers = {} req = Request.from_consumer_and_token(self.consumer, token=self.token, http_method=method, http_url=uri, parameters=parameters, body=body, is_form_encoded=True) req.sign_request(self.method, self.consumer, self.token) uri = req.to_url() return httplib2.Http.request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type)
def verifySignature(self, secret): """See L{IOAuthCredentials#verifySignature}.""" consumer = Consumer(key=self.consumerKey, secret=secret) oauthRequest = Request.from_request( self.method, self.url, headers=self.headers, query_string=self.arguments) # verify the request has been oauth authorized, we only support # HMAC-SHA1, reject OAuth signatures if they use a different method if self.signatureMethod != 'HMAC-SHA1': raise NotImplementedError( 'Unknown signature method: %s' % self.signatureMethod) signatureMethod = SignatureMethod_HMAC_SHA1() result = signatureMethod.check(oauthRequest, consumer, None, self.signature) return result
def sign(self, credentials, request, env): """Sign request""" # pylint: disable-msg=C0103 POST_CONTENT_TYPE = "application/x-www-form-urlencoded" consumer = self._get_consumer(credentials) token = self._get_token(credentials) if not consumer or not token: raise AuthError("Missing oauth tokens") # POST headers = request.headers if request.verb == "POST": assert "content-type" in headers # Only hash body and generate oauth_hash for body if # Content-Type != form-urlencoded isform = headers.get("content-type") == POST_CONTENT_TYPE # process post contents if required body, parameters = env.get("body", ""), None if isform and body: contents = body if hasattr(body, "read"): contents = body.read() body.seek(0) parameters = parse_qs(contents) # update request uri oauth_request = Request.from_consumer_and_token( consumer, token, request.verb, url_concat(request.uri, env["params"]), parameters, body, isform ) # sign oauth_request.sign_request(self.method, consumer, token) # process body if form or uri if a get/head if isform: env["body"] = oauth_request.to_postdata() elif request.verb in ("GET", "HEAD"): # remove params and update uri store params request.uri = oauth_request.to_url() env["params"] = None else: headers.update(oauth_request.to_header(realm=self._get_realm(request.uri)))
def verifySignature(self, secret): """See L{IOAuthCredentials#verifySignature}.""" consumer = Consumer(key=self.consumerKey, secret=secret) oauthRequest = Request.from_request(self.method, self.url, headers=self.headers, query_string=self.arguments) # verify the request has been oauth authorized, we only support # HMAC-SHA1, reject OAuth signatures if they use a different method if self.signatureMethod != 'HMAC-SHA1': raise NotImplementedError('Unknown signature method: %s' % self.signatureMethod) signatureMethod = SignatureMethod_HMAC_SHA1() result = signatureMethod.check(oauthRequest, consumer, None, self.signature) return result
def build_consumer_oauth_request(backend, token, url, redirect_uri='/', oauth_verifier=None, extra_params=None): """Builds a Consumer OAuth request.""" params = {'oauth_callback': redirect_uri} if extra_params: params.update(extra_params) if oauth_verifier: params['oauth_verifier'] = oauth_verifier consumer = OAuthConsumer(*backend.get_key_and_secret()) request = OAuthRequest.from_consumer_and_token(consumer, token=token, http_url=url, parameters=params) request.sign_request(SignatureMethod_HMAC_SHA1(), consumer, token) return request
def get_access_token(self, callback): path = self.get_oauth_path('get_access_token') url = self.get_url(path) consumer = Consumer(self.consumer.key, self.consumer.secret) request_token = self.get_request_token(callback) response = self.authorize_request_token(request_token.key) params = dict(parse_qsl(response['Location'][len(callback)+1:])) request_token.set_verifier(params['oauth_verifier']) request = Request.from_consumer_and_token(consumer, request_token, 'POST', url) request.sign_request(self.signature_method, consumer, request_token) response = self.client.post(path, request) self.assertEquals(response.status_code, 200) params = dict(parse_qsl(response.content)) return Token(params['oauth_token'], params['oauth_token_secret'])
class Base(object): """ Base class for all Photobucket APIs. """ # Photobucket API main endpoint DOMAIN = 'api.photobucket.com' # Used per API to define the main URI for that specific API. # E.g URI = /album/! - Will send a request to self.DOMAIN + /album/! # The ! is a special character used by Photobucket to indicate an identifier. # Ex. /album/!?id=identifier # All the APIs use an identifier for about 98% of all their methods, that's why # its already in the URI to save me the burden of putting it in almost every call :). URI = '/' # Url for user authentication. LOGIN = '******' def __init__(self, key, secret, token=None, token_secret=None, subdomain=None): """ Base API Class. All Photobucket APIs need to subclass. @key: Your photobucket API Key. @secret: Your photobucket API secret. @token: Can be a request or access token. @token_secret: Can be a request or access secret. @subdomain: The subdomain or "silo" to use when required by API. See http://bit.ly/Nla3WD """ self.key = key self.secret = secret self.token = token self.token_secret = token_secret self.subdomain = subdomain or self.DOMAIN def get_timestamp(self): return self.make_request('time', base_uri=Base.URI) # These four methods send pass Base.URI as base_uri to allow access # from any Photobucket API ( Album.ping ) since they are essential. def ping(self, method="GET"): return self.make_request('ping', base_uri=Base.URI, method=method) def login_request(self): """ Get a login request token to use during web authentication. """ return self.make_request('login/request', base_uri=Base.URI, method='POST') def get_access_token(self): return self.make_request('login/access', base_uri=Base.URI, method='POST') def get_login_url(self, token=None, extra=None): """ Returns the login url for the provided token. This assumes that token or self.token is a Request Token. """ if self.token is None and token is None: raise PhotobucketAPIError( "token needs to be set on instance or provided.") params = {} if extra: params['extra'] = extra params.update(dict(oauth_token=token or self.token)) return "%s?%s" % (self.LOGIN, urllib.urlencode(params)) def make_request(self, url, base_uri=None, params=None, auth=REQUIRED, method="GET", silo=False, **kwargs): """ Makes a request to Photobucket API. @url: The REST path to be requested after the [identifier]. By default this value is appended to self.URI. E.g. self.URI = /album/! url = /share/all The uri to request will be /album/!/share/all @base_uri: Allows for a quick override of self.URI per call. @params: A dictionary of parameters to send with the request. @auth: An Integer that determines whether this request needs to be authenticated. @method: The HTTP method to be used. @silo: Boolean. If True then this request will be sent to a specific silo/subdomain. """ params = params or dict() body = kwargs.get('body', '') headers = { 'User-Agent': 'python-photobucket/0.2 (Language=Python)', 'Content-type': 'application/x-www-form-urlencoded' } headers.update(kwargs.get('extra_headers', {})) # Unless explicitly provided, set the default response format to json. params.setdefault('format', 'json') if 'id' in params: params['id'] = self.clean_identifier(params['id']) # Remove all params with a value of "None" params = remove_empty(params) # Begin auth stuff... token = None consumer = OAuthConsumer(key=self.key, secret=self.secret) if auth in (REQUIRED, OPTIONAL): # Setup the oauth token try: token = Token(key=self.token, secret=self.token_secret) except ValueError, e: if auth == REQUIRED: # Only raise the exception if auth is required. raise PhotobucketAPIError( "Token and Token secret must be set.") # Give priority to base_uri since its a quick override of class.URI req_uri = "%s%s" % (base_uri or self.URI, url) if silo: # This request has to be sent to a specific "silo" or "subdomain". uri = "http://%s%s" % (self.subdomain, req_uri) # Don't allow redirects if this is to be sent to a specific silo. # For in photobucket's own words.. # "Photobucket ultimately prefers that you use the information given, rather than relying on the redirects" allow_redirects = False else: uri = "http://%s%s" % (self.DOMAIN, req_uri) allow_redirects = True req = OAuthRequest.from_consumer_and_token(consumer, token, method, uri, parameters=params, body=body) # Make sure to ALWAYS pass the main domain to the signature instead of the actual url to be requested. req.normalized_url = "http://%s%s" % (self.DOMAIN, req_uri) req.sign_request(SignatureMethod_HMAC_SHA1(), consumer, token) try: # I do this to take advantage of the already defined requests and their default values. response = getattr(requests, method.lower())(req.to_url(), headers=headers, allow_redirects=allow_redirects) #response.raise_for_status(allow_redirects=allow_redirects) except AttributeError: raise PhotobucketAPIError('Invalid Http method') except HTTPError, e: # This whole handling is still in Beta. # Because I'm still deciding on whether to keep it # or use "safe_mode" for all "POST" requests. To take advantage of Photobucket's redirect. # Suggestions are more than welcome... if e.response.status_code == REDIRECT: # Need to catch a redirect error because that means that user sent a request # without a "silo" so it needs to be stored. content = self.parse_response(e.response.content, params['format']) # Not too sure about this... self.subdomain = content['content']['subdomain'].split('//')[1] return self.make_request(url, base_uri, params, auth, method, silo, **kwargs) error = PhotobucketError(e.message) error.response = e.response raise error
def get_request(self, url=None, parameters=None): return Request(url=url, parameters=parameters)
def oauth_authorization_request(self, token): """Generate OAuth request to authorize token.""" return OAuthRequest.from_consumer_and_token( self.consumer, token=token, http_url=self.AUTHORIZATION_URL)
def getRequest(self, parameter, parser): return Request(self.Session, parameter, self.Timeout, parser)