From 3b56be6f7118dc8f3651f06465a23da723466947 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 13:43:16 +0100 Subject: [PATCH 01/19] added travis.yml file --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..73d7df91 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,5 @@ +python: + - "2.6" + - "2.7" + - "3.2" + From 62f2c480acb425c95eb1280c8452d6899221c4fd Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 13:48:41 +0100 Subject: [PATCH 02/19] added language to travis.yml --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index 73d7df91..cbec2b4c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,5 @@ +language: python + python: - "2.6" - "2.7" From bb3788f9779d4ab85b06862012e7f012f44045a5 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 13:55:16 +0100 Subject: [PATCH 03/19] added requirements.txt --- requirements.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..e69de29b From 594ae600bc1400d05982138702d97932d3755c46 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 13:56:24 +0100 Subject: [PATCH 04/19] added requirements --- requirements.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/requirements.txt b/requirements.txt index e69de29b..09c3c031 100644 --- a/requirements.txt +++ b/requirements.txt @@ -0,0 +1,3 @@ +httplib2 +coverage +mock From e1c05e6e8c9f7bdb91214dd33cafef1c37ed4572 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 14:00:48 +0100 Subject: [PATCH 05/19] added script key --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index cbec2b4c..5ff4a952 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,4 +4,7 @@ python: - "2.6" - "2.7" - "3.2" + +script: + python -m tests.test_oauth From d330a0f85f2e76432747421b4c9cfe0c7b8b80bf Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 14:07:57 +0100 Subject: [PATCH 06/19] added travis build status to readme, added .env to ignores and changed the coding directive that was failing the python 3.2 build --- .gitignore | 1 + README.md | 3 +++ tests/test_oauth.py | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 74df2303..4d0ab5f0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *.py? *.egg-info *.swp +.env diff --git a/README.md b/README.md index 3dca1e34..9ccedec8 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ + +https://secure.travis-ci.org/knowsis/python-oauth2.png?branch=master,develop + # Overview This code was originally forked from [Leah Culver and Andy Smith's oauth.py code](http://github.com/leah/python-oauth/). Some of the tests come from a [fork by Vic Fryzel](http://github.com/shellsage/python-oauth), while a revamped Request class and more tests were merged in from [Mark Paschal's fork](http://github.com/markpasc/python-oauth). A number of notable differences exist between this code and its forefathers: diff --git a/tests/test_oauth.py b/tests/test_oauth.py index 099e5794..cf2f4870 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -1,4 +1,4 @@ -# -*- coding: utf-8 -*- +# coding=utf-8 """ The MIT License From 6a81754aeeeb93a5545ff92c375c9cc2c62861ef Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 14:12:01 +0100 Subject: [PATCH 07/19] fixed issue with try except format for python 3 --- tests/test_oauth.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_oauth.py b/tests/test_oauth.py index cf2f4870..91e94e5b 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -49,19 +49,19 @@ class TestError(unittest.TestCase): def test_message(self): try: raise oauth.Error - except oauth.Error, e: + except oauth.Error as e: self.assertEqual(e.message, 'OAuth error occurred.') msg = 'OMG THINGS BROKE!!!!' try: raise oauth.Error(msg) - except oauth.Error, e: + except oauth.Error as e: self.assertEqual(e.message, msg) def test_str(self): try: raise oauth.Error - except oauth.Error, e: + except oauth.Error as e: self.assertEquals(str(e), 'OAuth error occurred.') class TestGenerateFunctions(unittest.TestCase): From ceb621496e6cbe9bb088550ddc39916d236efa43 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 14:19:57 +0100 Subject: [PATCH 08/19] removed python 3.2 for now --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 5ff4a952..8802067f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,7 @@ language: python python: - "2.6" - "2.7" - - "3.2" + script: python -m tests.test_oauth From 0cb9d97b57502189c65c4fa4714b5dc1067b5c55 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 14:23:46 +0100 Subject: [PATCH 09/19] updated README --- README.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9ccedec8..d0bfd93a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,13 @@ -https://secure.travis-ci.org/knowsis/python-oauth2.png?branch=master,develop + + +.. image:: https://secure.travis-ci.org/knowsis/python-oauth2.png?branch=develop + :target: https://secure.travis-ci.org/knowsis/python-oauth2 + + +Forked from simplegeo/python-oauth2 as they do not seem to be maintaining the repository anymore + + # Overview From c3625d948efb1701d362e8097a5a0dd140275e38 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 14:24:47 +0100 Subject: [PATCH 10/19] renamed README --- README.md => README.rst | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename README.md => README.rst (100%) diff --git a/README.md b/README.rst similarity index 100% rename from README.md rename to README.rst From 7e73de18ca5c778e4ce53db7995e4a8de34ff7e4 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 16:32:35 +0100 Subject: [PATCH 11/19] Changed client tests so that the httplib2.http.request calls (with oauth2.Client) are mocked. Had issues with the oauth sandbox not being available and unit tests should not rely on external services. --- tests/test_oauth.py | 41 ++++++++++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/tests/test_oauth.py b/tests/test_oauth.py index 91e94e5b..3a525907 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -33,6 +33,7 @@ import urlparse from types import ListType import mock +from mock import patch import httplib2 # Fix for python2.5 compatibility @@ -1192,30 +1193,40 @@ class Blah(): self.fail("Client.__init__() accepted invalid Token.") except ValueError: pass - + def test_access_token_get(self): """Test getting an access token via GET.""" - client = oauth.Client(self.consumer, None) - resp, content = client.request(self._uri('request_token'), "GET") - - self.assertEquals(int(resp['status']), 200) + + with patch('httplib2.Http.request') as mockRequest: + + mockRequest.return_value = {'status':200},'' + client = oauth.Client(self.consumer, None) + resp, content = client.request(self._uri('request_token'), "GET") + self.assertEquals(int(resp['status']), 200) def test_access_token_post(self): - """Test getting an access token via POST.""" - client = oauth.Client(self.consumer, None) - resp, content = client.request(self._uri('request_token'), "POST") + """Test getting an access token via POST.""" - self.assertEquals(int(resp['status']), 200) + with patch('httplib2.Http.request') as mockRequest: + + mockRequest.return_value = {'status':200},'oauth_token=123&oauth_token_secret=abcd' + + client = oauth.Client(self.consumer, None) + resp, content = client.request(self._uri('request_token'), "POST") - res = dict(parse_qsl(content)) - self.assertTrue('oauth_token' in res) - self.assertTrue('oauth_token_secret' in res) + self.assertEquals(int(resp['status']), 200) + + res = dict(parse_qsl(content)) + self.assertTrue('oauth_token' in res) + self.assertTrue('oauth_token_secret' in res) def _two_legged(self, method): client = oauth.Client(self.consumer, None) - - return client.request(self._uri('two_legged'), method, - body=urllib.urlencode(self.body)) + with patch('httplib2.Http.request') as mockRequest: + + mockRequest.return_value = {'status':200},'' + return client.request(self._uri('two_legged'), method, + body=urllib.urlencode(self.body)) def test_two_legged_post(self): """A test of a two-legged OAuth POST request.""" From 6f4c31f154aa23fac28732f49d94177c235f2f0a Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Wed, 8 Aug 2012 16:45:36 +0100 Subject: [PATCH 12/19] allow for the same parameter name to appear more than once in the querystring --- oauth2/__init__.py | 9 ++++++--- tests/test_oauth.py | 13 +++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/oauth2/__init__.py b/oauth2/__init__.py index 835270e3..65132d16 100644 --- a/oauth2/__init__.py +++ b/oauth2/__init__.py @@ -470,11 +470,11 @@ def get_normalized_parameters(self): query = urlparse.urlparse(self.url)[4] url_items = self._split_url_string(query).items() - url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ] + url_items = [(to_utf8(k), to_utf8_optional_iterator(v)) for k, v in url_items if k != 'oauth_signature' ] items.extend(url_items) items.sort() - encoded_str = urllib.urlencode(items) + encoded_str = urllib.urlencode(items, True) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) @@ -608,7 +608,10 @@ def _split_url_string(param_str): """Turn URL string into parameters.""" parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True) for k, v in parameters.iteritems(): - parameters[k] = urllib.unquote(v[0]) + if len(v) == 1: + parameters[k] = urllib.unquote(v[0]) + else: + parameters[k] = sorted([urllib.unquote(s) for s in v]) return parameters diff --git a/tests/test_oauth.py b/tests/test_oauth.py index 3a525907..8e9b7432 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -575,6 +575,19 @@ def test_get_normalized_parameters_duplicate(self): self.assertEquals(expected, res) + def test_get_normalized_parameters_multiple(self): + + url = "http://example.com/v2/search/videos?oauth_nonce=79815175&oauth_timestamp=1295397962&oauth_consumer_key=mykey&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&offset=10&oauth_signature=spWLI%2FGQjid7sQVd5%2FarahRxzJg%3D&tag=one&tag=two" + expected='oauth_consumer_key=mykey&oauth_nonce=79815175&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1295397962&oauth_version=1.0&offset=10&tag=one&tag=two' + + req = oauth.Request("GET", url) + + res = req.get_normalized_parameters() + + self.assertEquals(expected, res) + + + def test_get_normalized_parameters_from_url(self): # example copied from # https://github.com/ciaranj/node-oauth/blob/master/tests/oauth.js From e879bd1e14a709e41e346698f678ad0f4d92e6cb Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Fri, 10 Aug 2012 11:57:34 +0100 Subject: [PATCH 13/19] added fix for double encoding of the qs parameters! --- README.rst | 13 +++++-------- oauth2/__init__.py | 46 ++++++++++++++++++++++----------------------- tests/test_oauth.py | 11 +++++++++++ 3 files changed, 39 insertions(+), 31 deletions(-) diff --git a/README.rst b/README.rst index d0bfd93a..1e8980d4 100644 --- a/README.rst +++ b/README.rst @@ -1,17 +1,14 @@ +python-oauth2 +============= - - -.. image:: https://secure.travis-ci.org/knowsis/python-oauth2.png?branch=develop - :target: https://secure.travis-ci.org/knowsis/python-oauth2 - - -Forked from simplegeo/python-oauth2 as they do not seem to be maintaining the repository anymore +# Forked from simplegeo/python-oauth2 +Seeing as they do not seem to be maintaining the repository anymore # Overview -This code was originally forked from [Leah Culver and Andy Smith's oauth.py code](http://github.com/leah/python-oauth/). Some of the tests come from a [fork by Vic Fryzel](http://github.com/shellsage/python-oauth), while a revamped Request class and more tests were merged in from [Mark Paschal's fork](http://github.com/markpasc/python-oauth). A number of notable differences exist between this code and its forefathers: +The original repositories code was originally forked from [Leah Culver and Andy Smith's oauth.py code](http://github.com/leah/python-oauth/). Some of the tests come from a [fork by Vic Fryzel](http://github.com/shellsage/python-oauth), while a revamped Request class and more tests were merged in from [Mark Paschal's fork](http://github.com/markpasc/python-oauth). A number of notable differences exist between this code and its forefathers: * 100% unit test coverage. * The DataStore object has been completely ripped out. While creating unit tests for the library I found several substantial bugs with the implementation and confirmed with Andy Smith that it was never fully baked. diff --git a/oauth2/__init__.py b/oauth2/__init__.py index 835270e3..00847199 100644 --- a/oauth2/__init__.py +++ b/oauth2/__init__.py @@ -475,6 +475,7 @@ def get_normalized_parameters(self): items.sort() encoded_str = urllib.urlencode(items) + # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) @@ -485,11 +486,6 @@ def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: - # according to - # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html - # section 4.1.1 "OAuth Consumers MUST NOT include an - # oauth_body_hash parameter on requests with form-encoded - # request bodies." self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest()) if 'oauth_consumer_key' not in self: @@ -500,24 +496,25 @@ def sign_request(self, signature_method, consumer, token): self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token) - + @classmethod def make_timestamp(cls): """Get seconds since epoch (UTC).""" return str(int(time.time())) - + @classmethod def make_nonce(cls): """Generate pseudorandom number.""" return str(random.randint(0, 100000000)) - + @classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" + if parameters is None: parameters = {} - + # Headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] @@ -531,22 +528,25 @@ def from_request(cls, http_method, http_url, headers=None, parameters=None, except: raise Error('Unable to parse OAuth parameters from ' 'Authorization header.') - + # GET or POST query string. if query_string: query_params = cls._split_url_string(query_string) parameters.update(query_params) - + # URL parameters. param_str = urlparse.urlparse(http_url)[4] # query url_params = cls._split_url_string(param_str) parameters.update(url_params) - + + res = urlparse.urlparse(http_url) + url = urlparse.urlunparse((res[0],res[1],res[2],'','','')) + if parameters: - return cls(http_method, http_url, parameters) - + return cls(http_method, url, parameters) + return None - + @classmethod def from_consumer_and_token(cls, consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None, @@ -560,7 +560,7 @@ def from_consumer_and_token(cls, consumer, token=None, 'oauth_nonce': cls.make_nonce(), 'oauth_version': cls.version, } - + defaults.update(parameters) parameters = defaults @@ -568,24 +568,24 @@ def from_consumer_and_token(cls, consumer, token=None, parameters['oauth_token'] = token.key if token.verifier: parameters['oauth_verifier'] = token.verifier - + return Request(http_method, http_url, parameters, body=body, is_form_encoded=is_form_encoded) - + @classmethod def from_token_and_callback(cls, token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} - + parameters['oauth_token'] = token.key - + if callback: parameters['oauth_callback'] = callback - + return cls(http_method, http_url, parameters) - + @staticmethod def _split_header(header): """Turn Authorization: header into parameters.""" @@ -602,7 +602,7 @@ def _split_header(header): # Remove quotes and unescape the value. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params - + @staticmethod def _split_url_string(param_str): """Turn URL string into parameters.""" diff --git a/tests/test_oauth.py b/tests/test_oauth.py index 91e94e5b..e5e9171e 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -506,6 +506,7 @@ def test_signature_base_string_nonascii_nonutf8(self): url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\u2766,+CA' req = oauth.Request("GET", url) + req.version ="2.0" self.failUnlessReallyEqual(req.normalized_url, u'http://api.simplegeo.com/1.0/places/address.json') req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') @@ -888,6 +889,16 @@ def test_from_request(self): # Test that a boned from_request() call returns None req = oauth.Request.from_request("GET", url) self.assertEquals(None, req) + + + + # Test that a boned from_request() call returns None + url_with_qs = 'http://www.oauth.net?foo=1&bar=2' + + req = oauth.Request.from_request("GET", url_with_qs) + params = req.get_normalized_parameters() + self.assertEquals(params, 'bar=2&foo=1') + def test_from_token_and_callback(self): url = "http://sp.example.com/" From 414cc33388c962d23f21ab9a1ec2b9c642d99d32 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Fri, 10 Aug 2012 12:14:53 +0100 Subject: [PATCH 14/19] updated version --- oauth2/_version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oauth2/_version.py b/oauth2/_version.py index 9d779eaa..6311b2b0 100644 --- a/oauth2/_version.py +++ b/oauth2/_version.py @@ -1,6 +1,6 @@ # This is the version of this source code. -manual_verstr = "1.5" +manual_verstr = "1.5.1" From a861f59c7c9c7cbcc31b103a2d54301542ce947e Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Fri, 10 Aug 2012 12:20:57 +0100 Subject: [PATCH 15/19] reverted to markdown extension --- README.md | 365 +++++++++++++++++++++++++++++++++++++++++++++++++++++ README.rst | 2 +- 2 files changed, 366 insertions(+), 1 deletion(-) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..c25c388f --- /dev/null +++ b/README.md @@ -0,0 +1,365 @@ +python-oauth2 +============= + +# Forked from simplegeo/python-oauth2 +Seeing as they do not seem to be maintaining the repository anymore + +[![Build Status](https://secure.travis-ci.org/knowsis/python-oauth2.png?branch=master)](http://travis-ci.org/knowsis/python-oauth2) + +# Overview + +The original repositories code was originally forked from [Leah Culver and Andy Smith's oauth.py code](http://github.com/leah/python-oauth/). Some of the tests come from a [fork by Vic Fryzel](http://github.com/shellsage/python-oauth), while a revamped Request class and more tests were merged in from [Mark Paschal's fork](http://github.com/markpasc/python-oauth). A number of notable differences exist between this code and its forefathers: + +* 100% unit test coverage. +* The DataStore object has been completely ripped out. While creating unit tests for the library I found several substantial bugs with the implementation and confirmed with Andy Smith that it was never fully baked. +* Classes are no longer prefixed with OAuth. +* The Request class now extends from dict. +* The library is likely no longer compatible with Python 2.3. +* The Client class works and extends from httplib2. It's a thin wrapper that handles automatically signing any normal HTTP request you might wish to make. + +# Signing a Request + + import oauth2 as oauth + import time + + # Set the API endpoint + url = "http://example.com/photos" + + # Set the base oauth_* parameters along with any other parameters required + # for the API call. + params = { + 'oauth_version': "1.0", + 'oauth_nonce': oauth.generate_nonce(), + 'oauth_timestamp': int(time.time()) + 'user': 'joestump', + 'photoid': 555555555555 + } + + # Set up instances of our Token and Consumer. The Consumer.key and + # Consumer.secret are given to you by the API provider. The Token.key and + # Token.secret is given to you after a three-legged authentication. + token = oauth.Token(key="tok-test-key", secret="tok-test-secret") + consumer = oauth.Consumer(key="con-test-key", secret="con-test-secret") + + # Set our token/key parameters + params['oauth_token'] = token.key + params['oauth_consumer_key'] = consumer.key + + # Create our request. Change method, etc. accordingly. + req = oauth.Request(method="GET", url=url, parameters=params) + + # Sign the request. + signature_method = oauth.SignatureMethod_HMAC_SHA1() + req.sign_request(signature_method, consumer, token) + +# Using the Client + +The oauth2.Client is based on httplib2 and works just as you'd expect it to. The only difference is the first two arguments to the constructor are an instance of oauth2.Consumer and oauth2.Token (oauth2.Token is only needed for three-legged requests). + + import oauth2 as oauth + + # Create your consumer with the proper key/secret. + consumer = oauth.Consumer(key="your-twitter-consumer-key", + secret="your-twitter-consumer-secret") + + # Request token URL for Twitter. + request_token_url = "http://twitter.com/oauth/request_token" + + # Create our client. + client = oauth.Client(consumer) + + # The OAuth Client request works just like httplib2 for the most part. + resp, content = client.request(request_token_url, "GET") + print resp + print content + +# Twitter Three-legged OAuth Example + +Below is an example of how one would go through a three-legged OAuth flow to +gain access to protected resources on Twitter. This is a simple CLI script, but +can be easily translated to a web application. + + import urlparse + import oauth2 as oauth + + consumer_key = 'my_key_from_twitter' + consumer_secret = 'my_secret_from_twitter' + + request_token_url = 'http://twitter.com/oauth/request_token' + access_token_url = 'http://twitter.com/oauth/access_token' + authorize_url = 'http://twitter.com/oauth/authorize' + + consumer = oauth.Consumer(consumer_key, consumer_secret) + client = oauth.Client(consumer) + + # Step 1: Get a request token. This is a temporary token that is used for + # having the user authorize an access token and to sign the request to obtain + # said access token. + + resp, content = client.request(request_token_url, "GET") + if resp['status'] != '200': + raise Exception("Invalid response %s." % resp['status']) + + request_token = dict(urlparse.parse_qsl(content)) + + print "Request Token:" + print " - oauth_token = %s" % request_token['oauth_token'] + print " - oauth_token_secret = %s" % request_token['oauth_token_secret'] + print + + # Step 2: Redirect to the provider. Since this is a CLI script we do not + # redirect. In a web application you would redirect the user to the URL + # below. + + print "Go to the following link in your browser:" + print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token']) + print + + # After the user has granted access to you, the consumer, the provider will + # redirect you to whatever URL you have told them to redirect to. You can + # usually define this in the oauth_callback argument as well. + accepted = 'n' + while accepted.lower() == 'n': + accepted = raw_input('Have you authorized me? (y/n) ') + oauth_verifier = raw_input('What is the PIN? ') + + # Step 3: Once the consumer has redirected the user back to the oauth_callback + # URL you can request the access token the user has approved. You use the + # request token to sign this request. After this is done you throw away the + # request token and use the access token returned. You should store this + # access token somewhere safe, like a database, for future use. + token = oauth.Token(request_token['oauth_token'], + request_token['oauth_token_secret']) + token.set_verifier(oauth_verifier) + client = oauth.Client(consumer, token) + + resp, content = client.request(access_token_url, "POST") + access_token = dict(urlparse.parse_qsl(content)) + + print "Access Token:" + print " - oauth_token = %s" % access_token['oauth_token'] + print " - oauth_token_secret = %s" % access_token['oauth_token_secret'] + print + print "You may now access protected resources using the access tokens above." + print + +# Logging into Django w/ Twitter + +Twitter also has the ability to authenticate a user [via an OAuth flow](http://apiwiki.twitter.com/Sign-in-with-Twitter). This +flow is exactly like the three-legged OAuth flow, except you send them to a +slightly different URL to authorize them. + +In this example we'll look at how you can implement this login flow using +Django and python-oauth2. + +## Set up a Profile model + +You'll need a place to store all of your Twitter OAuth credentials after the +user has logged in. In your app's `models.py` file you should add something +that resembles the following model. + + class Profile(models.Model): + user = models.ForeignKey(User) + oauth_token = models.CharField(max_length=200) + oauth_secret = models.CharField(max_length=200) + +## Set up your Django views + +### `urls.py` + +Your `urls.py` should look something like the following. Basically, you need to +have a login URL, a callback URL that Twitter will redirect your users back to, +and a logout URL. + +In this example `^login/` and `twitter_login` will send the user to Twitter to +be logged in, `^login/authenticated/` and `twitter_authenticated` will confirm +the login, create the account if necessary, and log the user into the +application, and `^logout`/ logs the user out in the `twitter_logout` view. + + + from django.conf.urls.defaults import * + from django.contrib import admin + from mytwitterapp.views import twitter_login, twitter_logout, \ + twitter_authenticated + + admin.autodiscover() + + urlpatterns = patterns('', + url(r'^admin/doc/', include('django.contrib.admindocs.urls')), + url(r'^admin/', include(admin.site.urls)), + url(r'^login/?$', twitter_login), + url(r'^logout/?$', twitter_logout), + url(r'^login/authenticated/?$', twitter_authenticated), + ) + +### `views.py` + +*NOTE:* The following code was coded for Python 2.4 so some of the libraries +and code here might need to be updated if you are using Python 2.6+. + + # Python + import oauth2 as oauth + import cgi + + # Django + from django.shortcuts import render_to_response + from django.http import HttpResponseRedirect + from django.conf import settings + from django.contrib.auth import authenticate, login, logout + from django.contrib.auth.models import User + from django.contrib.auth.decorators import login_required + + # Project + from mytwitterapp.models import Profile + + # It's probably a good idea to put your consumer's OAuth token and + # OAuth secret into your project's settings. + consumer = oauth.Consumer(settings.TWITTER_TOKEN, settings.TWITTER_SECRET) + client = oauth.Client(consumer) + + request_token_url = 'http://twitter.com/oauth/request_token' + access_token_url = 'http://twitter.com/oauth/access_token' + + # This is the slightly different URL used to authenticate/authorize. + authenticate_url = 'http://twitter.com/oauth/authenticate' + + def twitter_login(request): + # Step 1. Get a request token from Twitter. + resp, content = client.request(request_token_url, "GET") + if resp['status'] != '200': + raise Exception("Invalid response from Twitter.") + + # Step 2. Store the request token in a session for later use. + request.session['request_token'] = dict(cgi.parse_qsl(content)) + + # Step 3. Redirect the user to the authentication URL. + url = "%s?oauth_token=%s" % (authenticate_url, + request.session['request_token']['oauth_token']) + + return HttpResponseRedirect(url) + + + @login_required + def twitter_logout(request): + # Log a user out using Django's logout function and redirect them + # back to the homepage. + logout(request) + return HttpResponseRedirect('/') + + def twitter_authenticated(request): + # Step 1. Use the request token in the session to build a new client. + token = oauth.Token(request.session['request_token']['oauth_token'], + request.session['request_token']['oauth_token_secret']) + client = oauth.Client(consumer, token) + + # Step 2. Request the authorized access token from Twitter. + resp, content = client.request(access_token_url, "GET") + if resp['status'] != '200': + print content + raise Exception("Invalid response from Twitter.") + + """ + This is what you'll get back from Twitter. Note that it includes the + user's user_id and screen_name. + { + 'oauth_token_secret': 'IcJXPiJh8be3BjDWW50uCY31chyhsMHEhqJVsphC3M', + 'user_id': '120889797', + 'oauth_token': '120889797-H5zNnM3qE0iFoTTpNEHIz3noL9FKzXiOxwtnyVOD', + 'screen_name': 'heyismysiteup' + } + """ + access_token = dict(cgi.parse_qsl(content)) + + # Step 3. Lookup the user or create them if they don't exist. + try: + user = User.objects.get(username=access_token['screen_name']) + except User.DoesNotExist: + # When creating the user I just use their screen_name@twitter.com + # for their email and the oauth_token_secret for their password. + # These two things will likely never be used. Alternatively, you + # can prompt them for their email here. Either way, the password + # should never be used. + user = User.objects.create_user(access_token['screen_name'], + '%s@twitter.com' % access_token['screen_name'], + access_token['oauth_token_secret']) + + # Save our permanent token and secret for later. + profile = Profile() + profile.user = user + profile.oauth_token = access_token['oauth_token'] + profile.oauth_secret = access_token['oauth_token_secret'] + profile.save() + + # Authenticate the user and log them in using Django's pre-built + # functions for these things. + user = authenticate(username=access_token['screen_name'], + password=access_token['oauth_token_secret']) + login(request, user) + + return HttpResponseRedirect('/') + + +### `settings.py` + +* You'll likely want to set `LOGIN_URL` to `/login/` so that users are properly redirected to your Twitter login handler when you use `@login_required` in other parts of your Django app. +* You can also set `AUTH_PROFILE_MODULE = 'mytwitterapp.Profile'` so that you can easily access the Twitter OAuth token/secret for that user using the `User.get_profile()` method in Django. + +# XOAUTH for IMAP and SMTP + +Gmail supports OAuth over IMAP and SMTP via a standard they call XOAUTH. This allows you to authenticate against Gmail's IMAP and SMTP servers using an OAuth token and secret. It also has the added benefit of allowing you to use vanilla SMTP and IMAP libraries. The `python-oauth2` package provides both IMAP and SMTP libraries that implement XOAUTH and wrap `imaplib.IMAP4_SSL` and `smtplib.SMTP`. This allows you to connect to Gmail with OAuth credentials using standard Python libraries. + +## IMAP + + import oauth2 as oauth + import oauth2.clients.imap as imaplib + + # Set up your Consumer and Token as per usual. Just like any other + # three-legged OAuth request. + consumer = oauth.Consumer('your_consumer_key', 'your_consumer_secret') + token = oauth.Token('your_users_3_legged_token', + 'your_users_3_legged_token_secret') + + # Setup the URL according to Google's XOAUTH implementation. Be sure + # to replace the email here with the appropriate email address that + # you wish to access. + url = "https://mail.google.com/mail/b/your_users_email@gmail.com/imap/" + + conn = imaplib.IMAP4_SSL('imap.googlemail.com') + conn.debug = 4 + + # This is the only thing in the API for impaplib.IMAP4_SSL that has + # changed. You now authenticate with the URL, consumer, and token. + conn.authenticate(url, consumer, token) + + # Once authenticated everything from the impalib.IMAP4_SSL class will + # work as per usual without any modification to your code. + conn.select('INBOX') + print conn.list() + + +## SMTP + + import oauth2 as oauth + import oauth2.clients.smtp as smtplib + + # Set up your Consumer and Token as per usual. Just like any other + # three-legged OAuth request. + consumer = oauth.Consumer('your_consumer_key', 'your_consumer_secret') + token = oauth.Token('your_users_3_legged_token', + 'your_users_3_legged_token_secret') + + # Setup the URL according to Google's XOAUTH implementation. Be sure + # to replace the email here with the appropriate email address that + # you wish to access. + url = "https://mail.google.com/mail/b/your_users_email@gmail.com/smtp/" + + conn = smtplib.SMTP('smtp.googlemail.com', 587) + conn.set_debuglevel(True) + conn.ehlo('test') + conn.starttls() + + # Again the only thing modified from smtplib.SMTP is the authenticate + # method, which works identically to the imaplib.IMAP4_SSL method. + conn.authenticate(url, consumer, token) + + diff --git a/README.rst b/README.rst index 1e8980d4..c25c388f 100644 --- a/README.rst +++ b/README.rst @@ -4,7 +4,7 @@ python-oauth2 # Forked from simplegeo/python-oauth2 Seeing as they do not seem to be maintaining the repository anymore - +[![Build Status](https://secure.travis-ci.org/knowsis/python-oauth2.png?branch=master)](http://travis-ci.org/knowsis/python-oauth2) # Overview From c0cd32c6677e81c7199ef713862c7b55b4358d00 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Fri, 10 Aug 2012 12:33:40 +0100 Subject: [PATCH 16/19] added develop build status --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index c25c388f..e8b94114 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,15 @@ python-oauth2 # Forked from simplegeo/python-oauth2 Seeing as they do not seem to be maintaining the repository anymore + +Master [![Build Status](https://secure.travis-ci.org/knowsis/python-oauth2.png?branch=master)](http://travis-ci.org/knowsis/python-oauth2) +Develop +[![Build Status](https://secure.travis-ci.org/knowsis/python-oauth2.png?branch=develop)](http://travis-ci.org/knowsis/python-oauth2) + + + # Overview The original repositories code was originally forked from [Leah Culver and Andy Smith's oauth.py code](http://github.com/leah/python-oauth/). Some of the tests come from a [fork by Vic Fryzel](http://github.com/shellsage/python-oauth), while a revamped Request class and more tests were merged in from [Mark Paschal's fork](http://github.com/markpasc/python-oauth). A number of notable differences exist between this code and its forefathers: From 2d08d1ca2ff0399801a73e900792d493d5cd978b Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Tue, 21 Aug 2012 16:35:07 +0100 Subject: [PATCH 17/19] removed unneed guff --- Makefile | 155 ------------------ README.rst | 365 ----------------------------------------- debian/changelog | 408 ---------------------------------------------- debian/compat | 1 - debian/control | 24 --- debian/copyright | 21 --- debian/pycompat | 1 - debian/pyversions | 1 - debian/rules | 12 -- setup.py | 40 ----- 10 files changed, 1028 deletions(-) delete mode 100644 Makefile delete mode 100644 README.rst delete mode 100644 debian/changelog delete mode 100644 debian/compat delete mode 100644 debian/control delete mode 100644 debian/copyright delete mode 100644 debian/pycompat delete mode 100644 debian/pyversions delete mode 100755 debian/rules delete mode 100755 setup.py diff --git a/Makefile b/Makefile deleted file mode 100644 index 57472bd1..00000000 --- a/Makefile +++ /dev/null @@ -1,155 +0,0 @@ -PYTHON = $(shell test -x bin/python && echo bin/python || \ - echo `which python`) -PYVERS = $(shell $(PYTHON) -c 'import sys; print "%s.%s" % sys.version_info[0:2]') -VIRTUALENV = $(shell /bin/echo -n `which virtualenv || \ - which virtualenv-$(PYVERS) || \ - which virtualenv$(PYVERS)`) -VIRTUALENV += --no-site-packages -PAGER ?= less -DEPS := $(shell find $(PWD)/deps -type f -printf "file://%p ") -COVERAGE = $(shell test -x bin/coverage && echo bin/coverage || echo true) -SETUP = $(PYTHON) ./setup.py -EZ_INSTALL = $(SETUP) easy_install -f "$(DEPS)" -PYLINT = bin/pylint -PLATFORM = $(shell $(PYTHON) -c "from pkg_resources import get_build_platform; print get_build_platform()") -OS := $(shell uname) -EGG := $(shell $(SETUP) --fullname)-py$(PYVERS).egg -SDIST := $(shell $(SETUP) --fullname).tar.gs -SRCDIR := oauth2 -SOURCES := $(shell find $(SRCDIR) -type f -name \*.py -not -name 'test_*') -TESTS := $(shell find $(SRCDIR) -type f -name test_\*.py) -COVERED := $(SOURCES) -ROOT = $(shell pwd) -ROOTCMD = fakeroot -SIGN_KEY ?= nerds@simplegeo.com -BUILD_NUMBER ?= 1 - - -.PHONY: test dev clean extraclean debian/changelog - -all: egg -egg: dist/$(EGG) - -dist/$(EGG): - $(SETUP) bdist_egg - -sdist: - $(SETUP) sdist - -debian/changelog: - -git branch -D changelog - git checkout -b changelog - git-dch -a -N $(shell $(SETUP) --version) --debian-branch changelog \ - --snapshot --snapshot-number=$(BUILD_NUMBER) - -deb: debian/changelog - test -d dist/deb || mkdir -p dist/deb - dpkg-buildpackage -r$(ROOTCMD) -k$(SIGN_KEY) - mv ../python-oauth2_* dist/deb - -test: - $(SETUP) test --with-coverage --cover-package=oauth2 - -sdist: - python setup.py sdist - -xunit.xml: bin/nosetests $(SOURCES) $(TESTS) - $(SETUP) test --with-xunit --xunit-file=$@ - -bin/nosetests: bin/easy_install - @$(EZ_INSTALL) nose - -coverage: .coverage - @$(COVERAGE) html -d $@ $(COVERED) - -coverage.xml: .coverage - @$(COVERAGE) xml $(COVERED) - -.coverage: $(SOURCES) $(TESTS) bin/coverage bin/nosetests - -@$(COVERAGE) run $(SETUP) test - -bin/coverage: bin/easy_install - @$(EZ_INSTALL) coverage - -profile: .profile bin/pyprof2html - bin/pyprof2html -o $@ $< - -.profile: $(SOURCES) bin/nosetests - -$(SETUP) test -q --with-profile --profile-stats-file=$@ - -bin/pyprof2html: bin/easy_install bin/ - @$(EZ_INSTALL) pyprof2html - -docs: $(SOURCES) bin/epydoc - @echo bin/epydoc -q --html --no-frames -o $@ ... - @bin/epydoc -q --html --no-frames -o $@ $(SOURCES) - -bin/epydoc: bin/easy_install - @$(EZ_INSTALL) epydoc - -bin/pep8: bin/easy_install - @$(EZ_INSTALL) pep8 - -pep8: bin/pep8 - @bin/pep8 --repeat --ignore E225 $(SRCDIR) - -pep8.txt: bin/pep8 - @bin/pep8 --repeat --ignore E225 $(SRCDIR) > $@ - -lint: bin/pylint - -$(PYLINT) -f colorized $(SRCDIR) - -lint.html: bin/pylint - -$(PYLINT) -f html $(SRCDIR) > $@ - -lint.txt: bin/pylint - -$(PYLINT) -f parseable $(SRCDIR) > $@ - -bin/pylint: bin/easy_install - @$(EZ_INSTALL) pylint - -README.html: README.mkd | bin/markdown - bin/markdown -e utf-8 $^ -f $@ - -bin/markdown: bin/easy_install - @$(EZ_INSTALL) Markdown - - -# Development setup -rtfm: - $(PAGER) README.mkd - -tags: TAGS.gz - -TAGS.gz: TAGS - gzip $^ - -TAGS: $(SOURCES) - ctags -eR . - -env: bin/easy_install - -bin/easy_install: - $(VIRTUALENV) . - -test -f deps/setuptools* && $@ -U deps/setuptools* - -dev: develop -develop: env - nice -n 20 $(SETUP) develop - @echo " ---------------------------------------------" - @echo " To activate the development environment, run:" - @echo " . bin/activate" - @echo " ---------------------------------------------" - -clean: -clean: - find . -type f -name \*.pyc -exec rm {} \; - rm -rf build dist TAGS TAGS.gz digg.egg-info tmp .coverage \ - coverage coverage.xml docs lint.html lint.txt profile \ - .profile *.egg xunit.xml - @if test "$(OS)" = "Linux"; then $(ROOTCMD) debian/rules clean; fi - - -xclean: extraclean -extraclean: clean - rm -rf bin lib .Python include diff --git a/README.rst b/README.rst deleted file mode 100644 index c25c388f..00000000 --- a/README.rst +++ /dev/null @@ -1,365 +0,0 @@ -python-oauth2 -============= - -# Forked from simplegeo/python-oauth2 -Seeing as they do not seem to be maintaining the repository anymore - -[![Build Status](https://secure.travis-ci.org/knowsis/python-oauth2.png?branch=master)](http://travis-ci.org/knowsis/python-oauth2) - -# Overview - -The original repositories code was originally forked from [Leah Culver and Andy Smith's oauth.py code](http://github.com/leah/python-oauth/). Some of the tests come from a [fork by Vic Fryzel](http://github.com/shellsage/python-oauth), while a revamped Request class and more tests were merged in from [Mark Paschal's fork](http://github.com/markpasc/python-oauth). A number of notable differences exist between this code and its forefathers: - -* 100% unit test coverage. -* The DataStore object has been completely ripped out. While creating unit tests for the library I found several substantial bugs with the implementation and confirmed with Andy Smith that it was never fully baked. -* Classes are no longer prefixed with OAuth. -* The Request class now extends from dict. -* The library is likely no longer compatible with Python 2.3. -* The Client class works and extends from httplib2. It's a thin wrapper that handles automatically signing any normal HTTP request you might wish to make. - -# Signing a Request - - import oauth2 as oauth - import time - - # Set the API endpoint - url = "http://example.com/photos" - - # Set the base oauth_* parameters along with any other parameters required - # for the API call. - params = { - 'oauth_version': "1.0", - 'oauth_nonce': oauth.generate_nonce(), - 'oauth_timestamp': int(time.time()) - 'user': 'joestump', - 'photoid': 555555555555 - } - - # Set up instances of our Token and Consumer. The Consumer.key and - # Consumer.secret are given to you by the API provider. The Token.key and - # Token.secret is given to you after a three-legged authentication. - token = oauth.Token(key="tok-test-key", secret="tok-test-secret") - consumer = oauth.Consumer(key="con-test-key", secret="con-test-secret") - - # Set our token/key parameters - params['oauth_token'] = token.key - params['oauth_consumer_key'] = consumer.key - - # Create our request. Change method, etc. accordingly. - req = oauth.Request(method="GET", url=url, parameters=params) - - # Sign the request. - signature_method = oauth.SignatureMethod_HMAC_SHA1() - req.sign_request(signature_method, consumer, token) - -# Using the Client - -The oauth2.Client is based on httplib2 and works just as you'd expect it to. The only difference is the first two arguments to the constructor are an instance of oauth2.Consumer and oauth2.Token (oauth2.Token is only needed for three-legged requests). - - import oauth2 as oauth - - # Create your consumer with the proper key/secret. - consumer = oauth.Consumer(key="your-twitter-consumer-key", - secret="your-twitter-consumer-secret") - - # Request token URL for Twitter. - request_token_url = "http://twitter.com/oauth/request_token" - - # Create our client. - client = oauth.Client(consumer) - - # The OAuth Client request works just like httplib2 for the most part. - resp, content = client.request(request_token_url, "GET") - print resp - print content - -# Twitter Three-legged OAuth Example - -Below is an example of how one would go through a three-legged OAuth flow to -gain access to protected resources on Twitter. This is a simple CLI script, but -can be easily translated to a web application. - - import urlparse - import oauth2 as oauth - - consumer_key = 'my_key_from_twitter' - consumer_secret = 'my_secret_from_twitter' - - request_token_url = 'http://twitter.com/oauth/request_token' - access_token_url = 'http://twitter.com/oauth/access_token' - authorize_url = 'http://twitter.com/oauth/authorize' - - consumer = oauth.Consumer(consumer_key, consumer_secret) - client = oauth.Client(consumer) - - # Step 1: Get a request token. This is a temporary token that is used for - # having the user authorize an access token and to sign the request to obtain - # said access token. - - resp, content = client.request(request_token_url, "GET") - if resp['status'] != '200': - raise Exception("Invalid response %s." % resp['status']) - - request_token = dict(urlparse.parse_qsl(content)) - - print "Request Token:" - print " - oauth_token = %s" % request_token['oauth_token'] - print " - oauth_token_secret = %s" % request_token['oauth_token_secret'] - print - - # Step 2: Redirect to the provider. Since this is a CLI script we do not - # redirect. In a web application you would redirect the user to the URL - # below. - - print "Go to the following link in your browser:" - print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token']) - print - - # After the user has granted access to you, the consumer, the provider will - # redirect you to whatever URL you have told them to redirect to. You can - # usually define this in the oauth_callback argument as well. - accepted = 'n' - while accepted.lower() == 'n': - accepted = raw_input('Have you authorized me? (y/n) ') - oauth_verifier = raw_input('What is the PIN? ') - - # Step 3: Once the consumer has redirected the user back to the oauth_callback - # URL you can request the access token the user has approved. You use the - # request token to sign this request. After this is done you throw away the - # request token and use the access token returned. You should store this - # access token somewhere safe, like a database, for future use. - token = oauth.Token(request_token['oauth_token'], - request_token['oauth_token_secret']) - token.set_verifier(oauth_verifier) - client = oauth.Client(consumer, token) - - resp, content = client.request(access_token_url, "POST") - access_token = dict(urlparse.parse_qsl(content)) - - print "Access Token:" - print " - oauth_token = %s" % access_token['oauth_token'] - print " - oauth_token_secret = %s" % access_token['oauth_token_secret'] - print - print "You may now access protected resources using the access tokens above." - print - -# Logging into Django w/ Twitter - -Twitter also has the ability to authenticate a user [via an OAuth flow](http://apiwiki.twitter.com/Sign-in-with-Twitter). This -flow is exactly like the three-legged OAuth flow, except you send them to a -slightly different URL to authorize them. - -In this example we'll look at how you can implement this login flow using -Django and python-oauth2. - -## Set up a Profile model - -You'll need a place to store all of your Twitter OAuth credentials after the -user has logged in. In your app's `models.py` file you should add something -that resembles the following model. - - class Profile(models.Model): - user = models.ForeignKey(User) - oauth_token = models.CharField(max_length=200) - oauth_secret = models.CharField(max_length=200) - -## Set up your Django views - -### `urls.py` - -Your `urls.py` should look something like the following. Basically, you need to -have a login URL, a callback URL that Twitter will redirect your users back to, -and a logout URL. - -In this example `^login/` and `twitter_login` will send the user to Twitter to -be logged in, `^login/authenticated/` and `twitter_authenticated` will confirm -the login, create the account if necessary, and log the user into the -application, and `^logout`/ logs the user out in the `twitter_logout` view. - - - from django.conf.urls.defaults import * - from django.contrib import admin - from mytwitterapp.views import twitter_login, twitter_logout, \ - twitter_authenticated - - admin.autodiscover() - - urlpatterns = patterns('', - url(r'^admin/doc/', include('django.contrib.admindocs.urls')), - url(r'^admin/', include(admin.site.urls)), - url(r'^login/?$', twitter_login), - url(r'^logout/?$', twitter_logout), - url(r'^login/authenticated/?$', twitter_authenticated), - ) - -### `views.py` - -*NOTE:* The following code was coded for Python 2.4 so some of the libraries -and code here might need to be updated if you are using Python 2.6+. - - # Python - import oauth2 as oauth - import cgi - - # Django - from django.shortcuts import render_to_response - from django.http import HttpResponseRedirect - from django.conf import settings - from django.contrib.auth import authenticate, login, logout - from django.contrib.auth.models import User - from django.contrib.auth.decorators import login_required - - # Project - from mytwitterapp.models import Profile - - # It's probably a good idea to put your consumer's OAuth token and - # OAuth secret into your project's settings. - consumer = oauth.Consumer(settings.TWITTER_TOKEN, settings.TWITTER_SECRET) - client = oauth.Client(consumer) - - request_token_url = 'http://twitter.com/oauth/request_token' - access_token_url = 'http://twitter.com/oauth/access_token' - - # This is the slightly different URL used to authenticate/authorize. - authenticate_url = 'http://twitter.com/oauth/authenticate' - - def twitter_login(request): - # Step 1. Get a request token from Twitter. - resp, content = client.request(request_token_url, "GET") - if resp['status'] != '200': - raise Exception("Invalid response from Twitter.") - - # Step 2. Store the request token in a session for later use. - request.session['request_token'] = dict(cgi.parse_qsl(content)) - - # Step 3. Redirect the user to the authentication URL. - url = "%s?oauth_token=%s" % (authenticate_url, - request.session['request_token']['oauth_token']) - - return HttpResponseRedirect(url) - - - @login_required - def twitter_logout(request): - # Log a user out using Django's logout function and redirect them - # back to the homepage. - logout(request) - return HttpResponseRedirect('/') - - def twitter_authenticated(request): - # Step 1. Use the request token in the session to build a new client. - token = oauth.Token(request.session['request_token']['oauth_token'], - request.session['request_token']['oauth_token_secret']) - client = oauth.Client(consumer, token) - - # Step 2. Request the authorized access token from Twitter. - resp, content = client.request(access_token_url, "GET") - if resp['status'] != '200': - print content - raise Exception("Invalid response from Twitter.") - - """ - This is what you'll get back from Twitter. Note that it includes the - user's user_id and screen_name. - { - 'oauth_token_secret': 'IcJXPiJh8be3BjDWW50uCY31chyhsMHEhqJVsphC3M', - 'user_id': '120889797', - 'oauth_token': '120889797-H5zNnM3qE0iFoTTpNEHIz3noL9FKzXiOxwtnyVOD', - 'screen_name': 'heyismysiteup' - } - """ - access_token = dict(cgi.parse_qsl(content)) - - # Step 3. Lookup the user or create them if they don't exist. - try: - user = User.objects.get(username=access_token['screen_name']) - except User.DoesNotExist: - # When creating the user I just use their screen_name@twitter.com - # for their email and the oauth_token_secret for their password. - # These two things will likely never be used. Alternatively, you - # can prompt them for their email here. Either way, the password - # should never be used. - user = User.objects.create_user(access_token['screen_name'], - '%s@twitter.com' % access_token['screen_name'], - access_token['oauth_token_secret']) - - # Save our permanent token and secret for later. - profile = Profile() - profile.user = user - profile.oauth_token = access_token['oauth_token'] - profile.oauth_secret = access_token['oauth_token_secret'] - profile.save() - - # Authenticate the user and log them in using Django's pre-built - # functions for these things. - user = authenticate(username=access_token['screen_name'], - password=access_token['oauth_token_secret']) - login(request, user) - - return HttpResponseRedirect('/') - - -### `settings.py` - -* You'll likely want to set `LOGIN_URL` to `/login/` so that users are properly redirected to your Twitter login handler when you use `@login_required` in other parts of your Django app. -* You can also set `AUTH_PROFILE_MODULE = 'mytwitterapp.Profile'` so that you can easily access the Twitter OAuth token/secret for that user using the `User.get_profile()` method in Django. - -# XOAUTH for IMAP and SMTP - -Gmail supports OAuth over IMAP and SMTP via a standard they call XOAUTH. This allows you to authenticate against Gmail's IMAP and SMTP servers using an OAuth token and secret. It also has the added benefit of allowing you to use vanilla SMTP and IMAP libraries. The `python-oauth2` package provides both IMAP and SMTP libraries that implement XOAUTH and wrap `imaplib.IMAP4_SSL` and `smtplib.SMTP`. This allows you to connect to Gmail with OAuth credentials using standard Python libraries. - -## IMAP - - import oauth2 as oauth - import oauth2.clients.imap as imaplib - - # Set up your Consumer and Token as per usual. Just like any other - # three-legged OAuth request. - consumer = oauth.Consumer('your_consumer_key', 'your_consumer_secret') - token = oauth.Token('your_users_3_legged_token', - 'your_users_3_legged_token_secret') - - # Setup the URL according to Google's XOAUTH implementation. Be sure - # to replace the email here with the appropriate email address that - # you wish to access. - url = "https://mail.google.com/mail/b/your_users_email@gmail.com/imap/" - - conn = imaplib.IMAP4_SSL('imap.googlemail.com') - conn.debug = 4 - - # This is the only thing in the API for impaplib.IMAP4_SSL that has - # changed. You now authenticate with the URL, consumer, and token. - conn.authenticate(url, consumer, token) - - # Once authenticated everything from the impalib.IMAP4_SSL class will - # work as per usual without any modification to your code. - conn.select('INBOX') - print conn.list() - - -## SMTP - - import oauth2 as oauth - import oauth2.clients.smtp as smtplib - - # Set up your Consumer and Token as per usual. Just like any other - # three-legged OAuth request. - consumer = oauth.Consumer('your_consumer_key', 'your_consumer_secret') - token = oauth.Token('your_users_3_legged_token', - 'your_users_3_legged_token_secret') - - # Setup the URL according to Google's XOAUTH implementation. Be sure - # to replace the email here with the appropriate email address that - # you wish to access. - url = "https://mail.google.com/mail/b/your_users_email@gmail.com/smtp/" - - conn = smtplib.SMTP('smtp.googlemail.com', 587) - conn.set_debuglevel(True) - conn.ehlo('test') - conn.starttls() - - # Again the only thing modified from smtplib.SMTP is the authenticate - # method, which works identically to the imaplib.IMAP4_SSL method. - conn.authenticate(url, consumer, token) - - diff --git a/debian/changelog b/debian/changelog deleted file mode 100644 index 7a462a73..00000000 --- a/debian/changelog +++ /dev/null @@ -1,408 +0,0 @@ -python-oauth2 (1.5.211) maverick; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Tue, 13 Dec 2011 17:39:07 +0000 - -python-oauth2 (1.5.210) maverick; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Fri, 09 Dec 2011 01:17:31 +0000 - -python-oauth2 (1.5.170) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Mon, 02 May 2011 23:48:16 +0000 - -python-oauth2 (1.5.169) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Fri, 15 Apr 2011 21:29:41 +0000 - -python-oauth2 (1.5.168) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Tue, 05 Apr 2011 23:13:18 +0000 - -python-oauth2 (1.5.167) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Thu, 17 Feb 2011 21:56:49 +0000 - -python-oauth2 (1.5.166) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * fix encoding of non-ascii data into postdata, really fixes #48 this - time (comes with test) - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Tue, 15 Feb 2011 17:23:00 +0000 - -python-oauth2 (1.5.165) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * get_normalized_parameters() is required to exclude any - oauth_signature that was already there, and it is required to - preserve duplicate keys, even with identical values ref #46, fixes - pull/49, thanks @zyegfryed - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Mon, 07 Feb 2011 19:24:56 +0000 - -python-oauth2 (1.5.164) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * make it actually inspect the request, and fix the test to require - the right things of the request ref #46, ref pull/49, thanks - @zyegfryed - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Mon, 07 Feb 2011 18:53:56 +0000 - -python-oauth2 (1.5.163) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * add test of #46; fixes #46 - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Fri, 04 Feb 2011 18:14:56 +0000 - -python-oauth2 (1.5.162) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * import parse_qs from cgi if it can't be imported from urlparse, thus - regaining compatibility with Python 2.5 fixes #47 thanks to @vtsao, - @subsume, @worksology - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Fri, 04 Feb 2011 17:50:56 +0000 - -python-oauth2 (1.5.161) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * Include all parameters from URL, even ones that begin with "oauth_", - in signature base. effectively reverts - https://github.com/simplegeo/python- - oauth2/commit/50ca9578f598faff5427e58814e2f45d01d3261c fixes #27 - Thanks to @robhudson for the bug report and help debugging. - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Thu, 03 Feb 2011 18:03:59 +0000 - -python-oauth2 (1.5.160) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * add another unicode test case to the tests just to show to user - saevarom on github - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Thu, 03 Feb 2011 00:01:55 +0000 - -python-oauth2 (1.5.159) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Thu, 03 Feb 2011 00:00:04 +0000 - -python-oauth2 (1.5.158) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * keep empty params parsed from the URL (fixes #22) - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Wed, 02 Feb 2011 19:34:25 +0000 - -python-oauth2 (1.5.155) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * use multiple values under the same key from the body (fixes #23) - Thanks to rogerm, ideasculptor, jiivan, timgraham. - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Tue, 01 Feb 2011 23:43:56 +0000 - -python-oauth2 (1.5.154) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Tue, 01 Feb 2011 18:03:58 +0000 - -python-oauth2 (1.5.153) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * add work-around for bug unicode-handling in urlparse in Python < - 2.7, including tests - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Tue, 01 Feb 2011 16:31:56 +0000 - -python-oauth2 (1.5.152) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * another test for handling of non-ascii, non-utf-8 urls - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Fri, 28 Jan 2011 18:14:34 +0000 - -python-oauth2 (1.5.151) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Thu, 27 Jan 2011 05:31:55 +0000 - -python-oauth2 (1.5.150) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Wed, 26 Jan 2011 17:15:25 +0000 - -python-oauth2 (1.5.149) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * add the body-hash header as specified in - http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth- - bodyhash.html - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Wed, 26 Jan 2011 17:11:34 +0000 - -python-oauth2 (1.5.148) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * default body is the empty string rather than None; add the Realm - header - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Wed, 26 Jan 2011 17:02:34 +0000 - -python-oauth2 (1.5.147) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * pass the body and the is_form_encoding flag in to the Request object - (for future use in implementing the hash-of-body extension) - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Tue, 25 Jan 2011 17:39:34 +0000 - -python-oauth2 (1.5.146) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * refactor internals of the way Client.request() decides whether this - is a x-www-form-urlencoded request or not - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Tue, 25 Jan 2011 17:30:38 +0000 - -python-oauth2 (1.5.145) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * update version number from 1.4 to 1.5 - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Mon, 24 Jan 2011 22:08:36 +0000 - -python-oauth2 (1.4.144) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * more thorough unit tests for non-ascii urls, params, and query-args- - in-url - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Mon, 24 Jan 2011 22:02:34 +0000 - -python-oauth2 (1.4.143) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * use two-part version number -- version is manually modified, build- - number is automatically modified - - [ Simple Geebus ] - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Mon, 24 Jan 2011 20:21:20 +0000 - -python-oauth2 (1.4.134) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Mon, 24 Jan 2011 18:30:58 +0000 - -python-oauth2 (1.4.133) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * handle unicode objects and utf-8 strings in url and params and - encode them to utf-8 when serializing - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Mon, 24 Jan 2011 18:25:54 +0000 - -python-oauth2 (1.4.132) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Mon, 24 Jan 2011 17:39:52 +0000 - -python-oauth2 (1.4.131) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Mon, 24 Jan 2011 17:32:18 +0000 - -python-oauth2 (1.4.130) lucid; urgency=low - - * UNRELEASED - - -- SimpleGeo Nerds Mon, 24 Jan 2011 17:22:46 +0000 - -python-oauth2 (1.4.129) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * change manually-managed version number from 1.3 to 1.4 - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Fri, 21 Jan 2011 19:52:32 +0000 - -python-oauth2 (1.3.128) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * raise an exception if the URL passed in is not a unicode object nor - ascii We can't submit a correct URL with arbitrary bytes -- we have - to submit a utf-8 encoded unicode string. (Otherwise we'll cause - either a rejection or a signature mismatch in the server, which is - what has happened at SimpleGeo.) If the caller passes in non-ascii - things in a str then it would be better for them to change their - code to decode it to unicode before passing it in than for us to - decode it, since they have a better chance of knowing what encoding - it is in -- if we did it we would be guessing. - * fix flaws pointed out by ieure, plus test failures I'm not entirely - sure it is appropriate to allow .url and .normalized_url to be non- - existent in addition to allowing them to be None, but I don't really - understand the intent of the url setter. - * Oh, after we've made sure it can be converted to unicode, just leave - it as a unicode object after that. - * raise more specific error message if argument to to_unicode() is - neither unicode nor str - * a couple of cleanups suggested by ieure in code review - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Mon, 10 Jan 2011 22:42:35 +0000 - -python-oauth2 (1.3.127) lucid; urgency=low - - [ Zooko Ofsimplegeo ] - * run tests when building - * raise exception from a test just to see if hudson is *really* - running these tests. I don't see the test results. - * put version number in a file where it can be read and written by - various things (including hudson) - * make oauth2.__version__ exist, rename VERSION to OAUTH_VERSION for - clarity - * debian/control -- build-dep pyflakes - * fix pyflakes - * build-dep requires python-coverage - * switch from nosetests to the builtin test runner Just because it - doesn't seem to currently use any feature of nosetest and this way - we can reduce the dependencies by one. We'll feel free to switch it - back to using nosetests (and add the dep to debian/control this - time) if we want to use some extra feature of nose. - * remove test failure which was inserted just to see if hudson was - running the tests properly - * Fix bug inserted by pyflakes inspired cleanup earlier -- it turns - out that _get_version() wasn't dead code but was having a necessary - side-effect. Add new method named _check_version() to be clearer - about what it does compared to _get_version() - * port tests from mox to mock because they were failing and I don't - understand mox. now they are working. add mock to the python and - debian deps. remove apparently left-over line of code that runs - "sign()" at the end of checking a signature - - [ SimpleGeo Nerds ] - - -- SimpleGeo Nerds Tue, 04 Jan 2011 19:39:34 +0000 - -python-oauth2 (1.2.1) lucid; urgency=low - - [ Joe Stump ] - * Fixed a minor spelling error, added tests for - oauth2.Error.__str__(), and added a test for build_xoauth_string(). - * Added a 'make test' command to the Makefile. - * Added a bunch of new tests. 100% coverage has lapsed a bit. Fixing - now. - - [ Ian Eure ] - * Update deb rule in makefile to sign packages and move them to - dist/deb. - - [ Joe Stump ] - * Implemented a 'fix' for a bug in certain OAuth providers. - http://bit.ly/aUrH43 - - [ Ian Eure ] - * Update packaging. - * Fix version disparity. - - [ coulix ] - * get normalised parameters should not take into account oauth_ params - - [ Mathias Herberts ] - * Modified get_normalized_parameters so it does not encode '~' for - full conformance with RFC 5849 section 3.6 - - [ Peter Bengtsson ] - * made it python 2.4 compatible - - [ Roderic Campbell ] - * tok != token. con != consumer. May be confusing for people not - actually reading the code. - - [ Ian Eure ] - - -- Ian Eure Mon, 28 Jun 2010 12:02:02 -0700 - -python-oauth2 (1.2.1pre2) unstable; urgency=low - - * Fix version disparity between setup.py & debian/changelog. - - -- Ian Eure Fri, 11 Jun 2010 16:11:41 -0700 - -python-oauth2 (1.2.1pre1) unstable; urgency=low - - * Make a native package. - * Increment version. - * Make debian/rules executable. - * Update standards-version, maintainers. - * Remvoe unneeded python-central build dependency. - - -- Ian Eure Fri, 11 Jun 2010 16:09:01 -0700 - -python-oauth2 (1.0.0-1simplegeo01) karmic; urgency=low - - * Initial build for SimpleGeo - - -- SimpleGeo Nerds Wed, 21 Oct 2009 23:24:00 -0700 diff --git a/debian/compat b/debian/compat deleted file mode 100644 index 7ed6ff82..00000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -5 diff --git a/debian/control b/debian/control deleted file mode 100644 index de0d42fa..00000000 --- a/debian/control +++ /dev/null @@ -1,24 +0,0 @@ -Source: python-oauth2 -Section: python -Priority: optional -Maintainer: SimpleGeo Nerds -Uploaders: Chris Lea , Ian Eure -Standards-Version: 3.8.4 -XS-Python-Version: all -Build-Depends: debhelper (>= 4.1.13), cdbs (>= 0.4.49), python, python-setuptools, python-support, pyflakes, python-coverage (>= 2.85), python-mock -Homepage: http://github.com/simplegeo/python-oauth2 - -Package: python-oauth2 -Architecture: all -XB-Python-Version: ${python:Versions} -Depends: ${python:Depends}, python-httplib2 -Provides: ${python:Provides} -Suggests: -Description: A Python OAuth class with several useful - features. - . - * 100% unit test coverage. - * The Request class now extends from dict. - * The Client class works and extends from httplib2. - It's a thin wrapper that handles automatically signing - any normal HTTP request you might wish to make. diff --git a/debian/copyright b/debian/copyright deleted file mode 100644 index 8f5e8bda..00000000 --- a/debian/copyright +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License - -Copyright (c) 2007 Leah Culver - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/debian/pycompat b/debian/pycompat deleted file mode 100644 index 0cfbf088..00000000 --- a/debian/pycompat +++ /dev/null @@ -1 +0,0 @@ -2 diff --git a/debian/pyversions b/debian/pyversions deleted file mode 100644 index b3dc41eb..00000000 --- a/debian/pyversions +++ /dev/null @@ -1 +0,0 @@ -2.5- diff --git a/debian/rules b/debian/rules deleted file mode 100755 index 4608bb84..00000000 --- a/debian/rules +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/make -f -# -*- mode: makefile; coding: utf-8 -*- - -DEB_PYTHON_SYSTEM = pysupport - -include /usr/share/cdbs/1/rules/debhelper.mk -include /usr/share/cdbs/1/class/python-distutils.mk - -build/python-oauth2:: - pyflakes oauth2 - python-coverage run --branch --include=oauth2/* setup.py test - python-coverage html -d $(ARTIFACTS)/htmlcov diff --git a/setup.py b/setup.py deleted file mode 100755 index acc41e17..00000000 --- a/setup.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -from setuptools import setup, find_packages -import os, re - -PKG='oauth2' -VERSIONFILE = os.path.join('oauth2', '_version.py') -verstr = "unknown" -try: - verstrline = open(VERSIONFILE, "rt").read() -except EnvironmentError: - pass # Okay, there is no version file. -else: - MVSRE = r"^manual_verstr *= *['\"]([^'\"]*)['\"]" - mo = re.search(MVSRE, verstrline, re.M) - if mo: - mverstr = mo.group(1) - else: - print "unable to find version in %s" % (VERSIONFILE,) - raise RuntimeError("if %s.py exists, it must be well-formed" % (VERSIONFILE,)) - AVSRE = r"^auto_build_num *= *['\"]([^'\"]*)['\"]" - mo = re.search(AVSRE, verstrline, re.M) - if mo: - averstr = mo.group(1) - else: - averstr = '' - verstr = '.'.join([mverstr, averstr]) - -setup(name=PKG, - version=verstr, - description="library for OAuth version 1.0", - author="Joe Stump", - author_email="joe@simplegeo.com", - url="http://github.com/simplegeo/python-oauth2", - packages = find_packages(), - install_requires = ['httplib2'], - license = "MIT License", - keywords="oauth", - zip_safe = True, - test_suite="tests", - tests_require=['coverage', 'mock']) From dd1dafb1b9620dc1e97d2ae0cee9d0fdfac6c263 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Tue, 21 Aug 2012 18:07:35 +0100 Subject: [PATCH 18/19] updated version number and added the setup.py file back in --- oauth2/_version.py | 6 ++---- setup.py | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 setup.py diff --git a/oauth2/_version.py b/oauth2/_version.py index 6311b2b0..7ddff06d 100644 --- a/oauth2/_version.py +++ b/oauth2/_version.py @@ -1,11 +1,9 @@ # This is the version of this source code. -manual_verstr = "1.5.1" +manual_verstr = "1.6" - -auto_build_num = "211" - +auto_build_num = "212" verstr = manual_verstr + "." + auto_build_num diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..f9c61c06 --- /dev/null +++ b/setup.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +from setuptools import setup, find_packages +import os, re + +PKG='oauth2' +VERSIONFILE = os.path.join('oauth2', '_version.py') +verstr = "unknown" +try: + verstrline = open(VERSIONFILE, "rt").read() +except EnvironmentError: + pass # Okay, there is no version file. +else: + MVSRE = r"^manual_verstr *= *['\"]([^'\"]*)['\"]" + mo = re.search(MVSRE, verstrline, re.M) + if mo: + mverstr = mo.group(1) + else: + print "unable to find version in %s" % (VERSIONFILE,) + raise RuntimeError("if %s.py exists, it must be well-formed" % (VERSIONFILE,)) + AVSRE = r"^auto_build_num *= *['\"]([^'\"]*)['\"]" + mo = re.search(AVSRE, verstrline, re.M) + if mo: + averstr = mo.group(1) + else: + averstr = '' + verstr = '.'.join([mverstr, averstr]) + +setup(name=PKG, + version=verstr, + description="library for OAuth version 2.0", + author="Joe Stump/Mark Unsworth", + author_email="mark@knows.is", + url="http://github.com/knowsis/python-oauth2", + packages = find_packages(exclude=["tests"]), + install_requires = ['httplib2'], + license = "MIT License", + keywords="oauth", + zip_safe = True, + test_suite="tests", + tests_require=['coverage', 'mock']) From 81865af1c6cea6b36fb1e32c1132badd0bfb5a23 Mon Sep 17 00:00:00 2001 From: Mark Unsworth Date: Tue, 9 Dec 2014 12:56:07 +0000 Subject: [PATCH 19/19] Update _version.py --- oauth2/_version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oauth2/_version.py b/oauth2/_version.py index 7ddff06d..e1ba5cdc 100644 --- a/oauth2/_version.py +++ b/oauth2/_version.py @@ -1,6 +1,6 @@ # This is the version of this source code. -manual_verstr = "1.6" +manual_verstr = "1.7" auto_build_num = "212"