def test_adjust_scheme(self): c = typepad.tpclient.TypePadClient() c.endpoint = 'http://api.typepad.com' c.clear_credentials() self.assertScheme(c.endpoint, 'http') c.clear_credentials() c.add_credentials('a', 'b') self.assertScheme(c.endpoint, 'http') c.clear_credentials() c.add_credentials('a', 'b', domain='api.typepad.com') self.assertScheme(c.endpoint, 'http') c.clear_credentials() c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd')) self.assertScheme(c.endpoint, 'https') c.clear_credentials() c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd'), domain='api.example.com') self.assertScheme(c.endpoint, 'http') c.clear_credentials() c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd'), domain='typepad.com') self.assertScheme(c.endpoint, 'http') # This time for sure!! c.clear_credentials() c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd'), domain='api.typepad.com') self.assertScheme(c.endpoint, 'https') # Try it again. c.clear_credentials() c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd'), domain='api.typepad.com') self.assertScheme(c.endpoint, 'https') # Check that clearing works. c.clear_credentials() self.assertScheme(c.endpoint, 'http')
def get_request(self, headers=None, **kwargs): request = super(Flixject, self).get_request(headers=headers, **kwargs) method = request.get('method', 'GET') # Apply OAuthness. csr = OAuthConsumer(*self.api_token) orq = OAuthRequest.from_consumer_and_token(csr, http_method=method, http_url=request['uri']) # OAuthRequest will strip our query parameters, so add them back in. parts = list(urlparse.urlparse(self._location)) queryargs = cgi.parse_qs(parts[4], keep_blank_values=True) for key, value in queryargs.iteritems(): orq.set_parameter(key, value[0]) # Sign the request. osm = OAuthSignatureMethod_HMAC_SHA1() orq.set_parameter('oauth_signature_method', osm.get_name()) orq.sign_request(osm, csr, None) if method == 'GET': request['uri'] = orq.to_url() else: request['headers'].update(orq.to_header()) return request
def test_consumer_property(self): c = typepad.tpclient.TypePadClient() c.endpoint = 'http://api.typepad.com' # make sure initial credentials are clear self.assert_(len(c.authorizations) == 0) self.assert_(len(c.credentials.credentials) == 0) # we can specify consumer and token as OAuth objects c.consumer = OAuthConsumer('x', 'y') c.token = OAuthToken('z', 'q') self.assert_(len(c.credentials.credentials) == 1) self.assertScheme(c.endpoint, 'https') # we can specify consumer and token as tuples of key/secrets c.consumer = ('a', 'b') c.token = ('a', 'b') self.assert_(len(c.credentials.credentials) == 1) self.assertScheme(c.endpoint, 'https') # assigning "None" to either token or consumer will # effectively clear credentials also c.token = None self.assert_(len(c.credentials.credentials) == 0) self.assertScheme(c.endpoint, 'http') c.clear_credentials() self.assertScheme(c.endpoint, 'http')
def test_responseful(self): request = { 'uri': mox.Func(self.saver('uri')), 'method': 'POST', 'headers': mox.Func(self.saver('headers')), 'body': mox.Func(self.saver('body')), } response = { 'status': 200, 'content-type': 'application/json', } response_content = '{"blahdeblah": true, "anotherthing": "2010-07-06T16:17:05Z"}' http = typepad.TypePadClient() typepad.client = http http.add_credentials( OAuthConsumer('consumertoken', 'consumersecret'), OAuthToken('tokentoken', 'tokensecret'), domain='api.typepad.com', ) mock = mox.Mox() mock.StubOutWithMock(http, 'request') http.request(**request).AndReturn((httplib2.Response(response), response_content)) mock.ReplayAll() class Moose(typepad.TypePadObject): class Snert(typepad.TypePadObject): volume = typepad.fields.Field() target = typepad.fields.Object('User') class SnertResponse(typepad.TypePadObject): blahdeblah = typepad.fields.Field() anotherthing = typepad.fields.Datetime() snert = typepad.fields.ActionEndpoint(api_name='snert', post_type=Snert, response_type=SnertResponse) moose = Moose() moose._location = 'https://api.typepad.com/meese/7.json' ret = moose.snert(volume=10, target=typepad.User(display_name='fred')) self.assert_(ret is not None) self.assert_(isinstance(ret, Moose.SnertResponse)) mock.VerifyAll() self.assert_(self.uri) self.assertEquals(self.uri, 'https://api.typepad.com/meese/7/snert.json') self.assert_(self.headers) self.assert_(self.body) self.assert_(utils.json_equals({ 'volume': 10, 'target': { 'displayName': 'fred', 'objectType': 'User', }, }, self.body))
def __init__(self, domain_name=None): BaseSpider.__init__(self, domain_name) consumer_key = config.get('yammer', 'consumer_key') consumer_secret = config.get('yammer', 'consumer_secret') app_token = config.get('yammer', 'app_token') self.consumer = OAuthConsumer(consumer_key, consumer_secret) self.signature = OAuthSignatureMethod_PLAINTEXT() self.token = OAuthToken.from_string(app_token)
def test_real_file(self): request = { 'uri': mox.Func(self.saver('uri')), 'method': 'POST', 'headers': mox.Func(self.saver('headers')), 'body': mox.Func(self.saver('body')), } response = { 'status': 201, } http = typepad.TypePadClient() typepad.client = http http.add_credentials( OAuthConsumer('consumertoken', 'consumersecret'), OAuthToken('tokentoken', 'tokensecret'), domain='api.typepad.com', ) mock = mox.Mox() mock.StubOutWithMock(http, 'request') http.request(**request).AndReturn((response, '')) mock.ReplayAll() asset = typepad.Photo() asset.title = "One-by-one png" asset.content = "This is a 1×1 transparent PNG." fileobj = file(os.path.join(os.path.dirname(__file__), 'onebyone.png')) brupload = typepad.BrowserUploadEndpoint() brupload.upload(asset, fileobj, "image/png", post_type='photo') mock.VerifyAll() response = self.message_from_response(self.headers, self.body) (filepart,) = [part for part in response.get_payload() if part.get_param('name', header='content-disposition') == 'file'] self.assertEquals(filepart.get_content_type(), 'image/png') # If there's a transfer encoding, it has to be the identity encoding. transenc = filepart.get('content-transfer-encoding') self.assert_(transenc is None or transenc == 'identity') # Check that the file content is equivalent without decoding. fileobj.seek(0) filecontent = fileobj.read() fileobj.close() self.assertEquals(filepart.get_payload(decode=False), filecontent) filelength = filepart.get('content-length') self.assertEquals(int(filelength), len(filecontent))
def auth(request, site): creds = OAUTH_CREDENTIALS.get(site.upper()) if not creds: raise Http404('Site %s not found' % site) urls = creds.get('URLS', {}) if 'DIALOG' in urls: request.session['preauth_url'] = request.META.get('HTTP_REFERER') return HttpResponseRedirect(urls['DIALOG']) ssl = creds.get('SSL', False) server = creds.get('SERVER', '%s.com' % site.lower()) klass = ssl and HTTPSConnection or HTTPConnection request.session['preauth_url'] = request.META.get('HTTP_REFERER') consumer = OAuthConsumer( str(creds['CONSUMER_KEY']), str(creds['CONSUMER_SECRET']) ) oauth_request = OAuthRequest.from_consumer_and_token( consumer, http_url = urls.get('REQUEST_TOKEN') ) oauth_request.sign_request(SIGNATURE_METHOD(), consumer, None) url = oauth_request.to_url() connection = klass(server) connection.request(oauth_request.http_method, url) response = connection.getresponse() resp = response.read() token = OAuthToken.from_string(resp) request.session['unauth_token'] = token auth_url = urls.get('AUTHORISATION') if isinstance(auth_url, (list, tuple)): params = auth_url[1] auth_url = auth_url[0] else: params = {} oauth_request = OAuthRequest.from_consumer_and_token( consumer, token = token, http_url = auth_url, parameters = params ) oauth_request.sign_request(SIGNATURE_METHOD(), consumer, token) return HttpResponseRedirect( oauth_request.to_url() )
def test_redirect(self): request = { 'uri': mox.Func(self.saver('uri')), 'method': 'POST', 'headers': mox.Func(self.saver('headers')), 'body': mox.Func(self.saver('body')), } response = { 'status': 302, 'location': 'http://client.example.com/hi', } http = typepad.TypePadClient() typepad.client = http http.add_credentials( OAuthConsumer('consumertoken', 'consumersecret'), OAuthToken('tokentoken', 'tokensecret'), domain='api.typepad.com', ) mock = mox.Mox() mock.StubOutWithMock(http, 'request') http.request(**request).AndReturn((response, '')) mock.ReplayAll() asset = typepad.Photo() asset.title = "Fake photo" asset.content = "This is a made-up photo for testing automated browser style upload." fileobj = StringIO('hi hello pretend file') brupload = typepad.BrowserUploadEndpoint() brupload.upload(asset, fileobj, "image/png", redirect_to='http://client.example.com/hi', post_type='photo') mock.VerifyAll() # Verify the headers and body. self.assert_(self.headers) self.assert_(self.body) response = self.message_from_response(self.headers, self.body) bodyparts = response.get_payload() self.assertEquals(len(bodyparts), 4) bodyparts = dict((part.get_param('name', header='content-disposition'), part) for part in bodyparts) # Confirm that the redirect_to was sent. self.assert_('redirect_to' in bodyparts) self.assertEquals(bodyparts['redirect_to'].get_payload(), 'http://client.example.com/hi')
def test_responseless(self): request = { 'uri': mox.Func(self.saver('uri')), 'method': 'POST', 'headers': mox.Func(self.saver('headers')), 'body': mox.Func(self.saver('body')), } response = { 'status': 204, # no content } http = typepad.TypePadClient() typepad.client = http http.add_credentials( OAuthConsumer('consumertoken', 'consumersecret'), OAuthToken('tokentoken', 'tokensecret'), domain='api.typepad.com', ) mock = mox.Mox() mock.StubOutWithMock(http, 'request') http.request(**request).AndReturn((httplib2.Response(response), '')) mock.ReplayAll() class Moose(typepad.TypePadObject): class Snert(typepad.TypePadObject): volume = typepad.fields.Field() snert = typepad.fields.ActionEndpoint(api_name='snert', post_type=Snert) moose = Moose() moose._location = 'https://api.typepad.com/meese/7.json' ret = moose.snert(volume=10) self.assert_(ret is None) mock.VerifyAll() self.assert_(self.uri) self.assertEquals(self.uri, 'https://api.typepad.com/meese/7/snert.json') self.assert_(self.headers) self.assert_(self.body) self.assert_(utils.json_equals({ 'volume': 10 }, self.body))
def __init__(self, user, token=None): """Initialize an oauth-authenticated test client. :param user: The user to authenticate. :type user: django.contrib.auth.models.User :param token: Optional token to authenticate `user` with. If no `token` is given, the user's first token will be used. :type token: oauth.oauth.OAuthToken """ super(OAuthAuthenticatedClient, self).__init__() if token is None: # Get the user's first token. token = get_auth_tokens(user)[0] assert token.user == user, "Token does not match User." consumer = token.consumer self.consumer = OAuthConsumer(consumer.key.encode("ascii"), consumer.secret.encode("ascii")) self.token = OAuthToken(token.key.encode("ascii"), token.secret.encode("ascii"))
def validate(self, request, data): signature_method = OAuthSignatureMethod_HMAC_SHA1() consumer = OAuthConsumer(self.CONSUMER_KEY, self.CONSUMER_SECRET) try: oauth_token = data['oauth_token'] oauth_verifier = data.get('oauth_verifier', None) except MultiValueDictKeyError: messages.error(request, lang.BACKEND_ERROR) raise Redirect('publicauth-login') oauth_req = OAuthRequest.from_consumer_and_token( consumer, http_url=self.ACCESS_TOKEN_URL) oauth_req.set_parameter('oauth_token', oauth_token) if oauth_verifier: oauth_req.set_parameter('oauth_verifier', oauth_verifier) oauth_req.sign_request(signature_method, consumer, None) response = urllib.urlopen(oauth_req.to_url()).read() self.identity = urlparse.parse_qs( response, keep_blank_values=False)['oauth_token'][0] return response
def begin(self, request, data): """ Try to get Request Token from OAuth Provider and redirect user to provider's site for approval. """ consumer = OAuthConsumer(self.CONSUMER_KEY, self.CONSUMER_SECRET) signature_method = OAuthSignatureMethod_HMAC_SHA1() callback = request.build_absolute_uri( reverse('publicauth-complete', args=[self.provider])) oauth_req = OAuthRequest.from_consumer_and_token( consumer, callback=callback, http_url=self.REQUEST_TOKEN_URL) oauth_req.sign_request(signature_method, consumer, None) response = urllib.urlopen(oauth_req.to_url()).read() token = OAuthToken.from_string(response) # instatiate token oauth_req = OAuthRequest.from_consumer_and_token( consumer, token, http_url=self.AUTHORIZE_URL) oauth_req.sign_request(signature_method, consumer, token) raise Redirect(oauth_req.to_url())
def __init__(self, consumer_key, consumer_secret, access_token_key=None, access_token_secret=None, proxy_host=None, proxy_port=None, proxy_username=None, proxy_password=None): """ Register applications at https://www.yammer.com/client_applications/new in order to get consumer key and secret. Keyword arguments: consumer key -- identifies a Yammer application consumer secret -- establishes ownership of the consumer key access token key -- an OAuth access token (optional) access token secret -- establishes ownership of the access key (optional) proxy host -- host name of proxy server (optional) proxy port -- port number (optional) proxy username -- used if proxy requires authentication (optional) proxy password -- used if proxy requires authentication (optional) """ self._proxy_host = None self._proxy_host = None self._proxy_username = None self._proxy_password = None self._access_token = None try: self._consumer = OAuthConsumer(consumer_key, consumer_secret) # Could not get HMAC-SHA1 to work but since Yammer is using # HTTPS, plaintext should be fine. # # self._signature = OAuthSignatureMethod_HMAC_SHA1() self._signature = OAuthSignatureMethod_PLAINTEXT() except OAuthError, m: raise YammerError(m.message)
def callback(key, secret, request): token = request.session.get('unauth_token') if not token: raise Exception('No unauthorised token') if token.key != request.GET.get('oauth_token', None): raise Exception('Token does not match') verifier = request.GET.get('oauth_verifier') consumer = OAuthConsumer(str(key), str(secret)) oauth_request = OAuthRequest.from_consumer_and_token( consumer, token=token, http_url='https://twitter.com/oauth/access_token', parameters={'oauth_verifier': verifier}) oauth_request.sign_request(SIGNATURE_METHOD(), consumer, token) url = oauth_request.to_url() access_token = OAuthToken.from_string(urlopen(url).read()) return access_token
def redirect(key, secret, request): consumer = OAuthConsumer(str(key), str(secret)) oauth_request = OAuthRequest.from_consumer_and_token( consumer, http_url='https://twitter.com/oauth/request_token') oauth_request.sign_request(SIGNATURE_METHOD(), consumer, None) url = oauth_request.to_url() connection = HTTPSConnection('twitter.com') connection.request(oauth_request.http_method, url) response = connection.getresponse() resp = response.read() token = OAuthToken.from_string(resp) request.session['unauth_token'] = token auth_url = 'https://twitter.com/oauth/authorize' if isinstance(auth_url, (list, tuple)): params = auth_url[1] auth_url = auth_url[0] else: params = {} oauth_request = OAuthRequest.from_consumer_and_token(consumer, token=token, http_url=auth_url, parameters=params) oauth_request.sign_request(SIGNATURE_METHOD(), consumer, token) if request.is_ajax(): return HttpResponse('<script>document.location = \'%s\';</script>' % oauth_request.to_url()) else: return HttpResponseRedirect(oauth_request.to_url())
def test_basic(self): request = { 'uri': mox.Func(self.saver('uri')), 'method': 'POST', 'headers': mox.Func(self.saver('headers')), 'body': mox.Func(self.saver('body')), } response = { 'status': 201, # created } http = typepad.TypePadClient() typepad.client = http http.add_credentials( OAuthConsumer('consumertoken', 'consumersecret'), OAuthToken('tokentoken', 'tokensecret'), domain='api.typepad.com', ) mock = mox.Mox() mock.StubOutWithMock(http, 'request') http.request(**request).AndReturn((response, '')) mock.ReplayAll() asset = typepad.Photo() asset.title = "Fake photo" asset.content = "This is a made-up photo for testing automated browser style upload." fileobj = StringIO('hi hello pretend file') brupload = typepad.BrowserUploadEndpoint() brupload.upload(asset, fileobj, "image/png", post_type='photo') mock.VerifyAll() self.assert_(self.uri) # We added credentials, so it should be a secure URL. self.assert_(self.uri.startswith('https://api.typepad.com/browser-upload.json')) uriparts = list(urlparse(self.uri)) querydict = cgi.parse_qs(uriparts[4]) # TODO: really verify the signature # Verify the headers and body. self.assert_(self.headers) self.assert_(self.body) responsemsg = self.message_from_response(self.headers, self.body) content_type = responsemsg.get_content_type() self.assert_(content_type) self.assert_(not responsemsg.defects) # Check that the unparsed body has its internal mime headers # separated by full CRLFs, not just LFs. self.assert_('\r\nContent-Type:' in self.body) # Check that boundaries are separated by full CRLFs too. boundary = responsemsg.get_param('boundary') self.assert_(boundary + '\r\n' in self.body) # Make sure we're only putting credentials in the query string, not # the headers. self.assert_('oauth_signature' in querydict) self.assert_('authorization' not in responsemsg) self.assert_('Authorization' not in responsemsg) bodyparts = responsemsg.get_payload() self.assertEquals(len(bodyparts), 3) bodyparts = dict((part.get_param('name', header='content-disposition'), part) for part in bodyparts) self.assertEquals(bodyparts['post_type'].get_payload(), 'photo') self.assert_('redirect_to' not in bodyparts) asset_json = bodyparts['asset'].get_payload() self.assert_(utils.json_equals({ 'title': 'Fake photo', 'content': 'This is a made-up photo for testing automated browser style upload.', 'objectType': 'Photo', }, asset_json)) filepart = bodyparts['file'] self.assertEquals(filepart.get_payload(decode=False), 'hi hello pretend file') filelength = filepart.get('content-length') self.assertEquals(int(filelength), len('hi hello pretend file')) filename = filepart.get_param('filename', header='content-disposition') self.assert_(filename)
def return_auth(request, site): creds = OAUTH_CREDENTIALS.get(site.upper()) if not creds: raise Http404('Site %s not found' % site) urls = creds.get('URLS', {}) ssl = creds.get('SSL', False) server = creds.get('SERVER', '%s.com' % site.lower()) if not 'DIALOG' in urls: token = request.session.get('unauth_token') if not token: return HttpResponse('No unauthorised token') if token.key != request.GET.get('oauth_token', None): if request.session.get('preauth_url'): return HttpResponseRedirect( request.session['preauth_url'] ) else: return HttpResponse('') verifier = request.GET.get('oauth_verifier') consumer = OAuthConsumer( str(creds.get('CONSUMER_KEY')), str(creds.get('CONSUMER_SECRET')) ) oauth_request = OAuthRequest.from_consumer_and_token( consumer, token = token, http_url = urls.get('ACCESS_TOKEN'), parameters = { 'oauth_verifier': verifier } ) oauth_request.sign_request(SIGNATURE_METHOD(), consumer, token) url = oauth_request.to_url() access_token = OAuthToken.from_string( urlopen(url).read() ) if request.user.is_authenticated(): try: token = request.user.oauth_tokens.get( site = site ) token.token = access_token.key token.secret = access_token.secret token.save() except core.OAuthToken.DoesNotExist: request.user.oauth_tokens.create( site = site, token = access_token.key, secret = access_token.secret ) else: return HttpResponse('') else: url = urls.get('ACCESS_TOKEN') % request.GET.get('code') resp = urlopen(url).read() d = {} for (key, value) in [i.split('=') for i in resp.split('&')]: if key: d[key] = value if request.user.is_authenticated(): try: token = request.user.oauth_tokens.get( site = site ) token.token = d['access_token'] token.save() except core.OAuthToken.DoesNotExist: request.user.oauth_tokens.create( site = site, token = d['access_token'] ) else: return HttpResponse('') if request.session.get('preauth_url'): messages.add_message( request, messages.SUCCESS, u'You have been successfully connected to %s.' % creds.get( 'VERBOSE_NAME', site.capitalize() ) ) return HttpResponseRedirect( request.session['preauth_url'] ) else: return HttpResponse('')
def _token_set(self, token): consumer = token.consumer self.consumer = OAuthConsumer(consumer.key, consumer.secret) self.token = OAuthToken(token.key, token.secret)
def __init__(self): self.consumer = OAuthConsumer(GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET)
# Get a Twitter access token for use with Sycorax from oauth.oauth import (OAuthConsumer, OAuthRequest, OAuthToken, OAuthSignatureMethod_HMAC_SHA1 as HMAC) from twitter import ACCESS_TOKEN_URL, AUTHORIZATION_URL, REQUEST_TOKEN_URL from keys import TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET from httplib2 import Http import json import sys import urlparse consumer = OAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET) def get_request_token(): oauth_request = OAuthRequest.from_consumer_and_token( consumer, http_method="POST", http_url=REQUEST_TOKEN_URL, callback="oob") oauth_request.sign_request(HMAC(), consumer, "") headers = oauth_request.to_header() client = Http() response, body = client.request(REQUEST_TOKEN_URL, "POST", headers=headers) token = OAuthToken.from_string(body) return token
def oauth_consumer(self): """Return OAuthConsumer based on information contained in this model""" return OAuthConsumer(self.key, self.secret)