Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Move Client and Server into their own modules. #96

Open
wants to merge 2 commits into from

1 participant

Joshua Roesslein
Joshua Roesslein

This avoids the httplib2 dependency unless you need the client.

This does change the name spacing a bit, so this patch may need tweaking
to not break compatibility. With the current changes to import the client you have to:

from oauth2.client import Client

Seen others requesting to remove to make this a soft dependency.
I had no need for the client and seemed funny to still depend on httplib2.

joshthecoder added some commits
Joshua Roesslein joshthecoder Move Client and Server into their own modules.
This avoids the httplib2 dependency unless you need the client.
4b8bc8c
Joshua Roesslein joshthecoder Restore version. fd871fb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 12, 2011
  1. Joshua Roesslein

    Move Client and Server into their own modules.

    joshthecoder authored
    This avoids the httplib2 dependency unless you need the client.
Commits on Nov 13, 2011
  1. Joshua Roesslein

    Restore version.

    joshthecoder authored
This page is out of date. Refresh to see the latest.
168 oauth2/__init__.py
View
@@ -29,7 +29,6 @@
import urlparse
import hmac
import binascii
-import httplib2
try:
from urlparse import parse_qs
@@ -46,7 +45,6 @@
import sha
import _version
-
__version__ = _version.__version__
OAUTH_VERSION = '1.0' # Hi Blaine!
@@ -612,172 +610,6 @@ def _split_url_string(param_str):
return parameters
-class Client(httplib2.Http):
- """OAuthClient is a worker to attempt to execute a request."""
-
- def __init__(self, consumer, token=None, cache=None, timeout=None,
- proxy_info=None):
-
- if consumer is not None and not isinstance(consumer, Consumer):
- raise ValueError("Invalid consumer.")
-
- if token is not None and not isinstance(token, Token):
- raise ValueError("Invalid token.")
-
- self.consumer = consumer
- self.token = token
- self.method = SignatureMethod_HMAC_SHA1()
-
- httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info)
-
- def set_signature_method(self, method):
- if not isinstance(method, SignatureMethod):
- raise ValueError("Invalid signature method.")
-
- self.method = method
-
- def request(self, uri, method="GET", body='', headers=None,
- redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
- DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded'
-
- if not isinstance(headers, dict):
- headers = {}
-
- if method == "POST":
- headers['Content-Type'] = headers.get('Content-Type',
- DEFAULT_POST_CONTENT_TYPE)
-
- is_form_encoded = \
- headers.get('Content-Type') == 'application/x-www-form-urlencoded'
-
- if is_form_encoded and body:
- parameters = parse_qs(body)
- else:
- parameters = None
-
- req = Request.from_consumer_and_token(self.consumer,
- token=self.token, http_method=method, http_url=uri,
- parameters=parameters, body=body, is_form_encoded=is_form_encoded)
-
- req.sign_request(self.method, self.consumer, self.token)
-
- schema, rest = urllib.splittype(uri)
- if rest.startswith('//'):
- hierpart = '//'
- else:
- hierpart = ''
- host, rest = urllib.splithost(rest)
-
- realm = schema + ':' + hierpart + host
-
- if is_form_encoded:
- body = req.to_postdata()
- elif method == "GET":
- uri = req.to_url()
- else:
- headers.update(req.to_header(realm=realm))
-
- return httplib2.Http.request(self, uri, method=method, body=body,
- headers=headers, redirections=redirections,
- connection_type=connection_type)
-
-
-class Server(object):
- """A skeletal implementation of a service provider, providing protected
- resources to requests from authorized consumers.
-
- This class implements the logic to check requests for authorization. You
- can use it with your web server or web framework to protect certain
- resources with OAuth.
- """
-
- timestamp_threshold = 300 # In seconds, five minutes.
- version = OAUTH_VERSION
- signature_methods = None
-
- def __init__(self, signature_methods=None):
- self.signature_methods = signature_methods or {}
-
- def add_signature_method(self, signature_method):
- self.signature_methods[signature_method.name] = signature_method
- return self.signature_methods
-
- def verify_request(self, request, consumer, token):
- """Verifies an api call and checks all the parameters."""
-
- self._check_version(request)
- self._check_signature(request, consumer, token)
- parameters = request.get_nonoauth_parameters()
- return parameters
-
- def build_authenticate_header(self, realm=''):
- """Optional support for the authenticate header."""
- return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
-
- def _check_version(self, request):
- """Verify the correct version of the request for this server."""
- version = self._get_version(request)
- if version and version != self.version:
- raise Error('OAuth version %s not supported.' % str(version))
-
- def _get_version(self, request):
- """Return the version of the request for this server."""
- try:
- version = request.get_parameter('oauth_version')
- except:
- version = OAUTH_VERSION
-
- return version
-
- def _get_signature_method(self, request):
- """Figure out the signature with some defaults."""
- try:
- signature_method = request.get_parameter('oauth_signature_method')
- except:
- signature_method = SIGNATURE_METHOD
-
- try:
- # Get the signature method object.
- signature_method = self.signature_methods[signature_method]
- except:
- signature_method_names = ', '.join(self.signature_methods.keys())
- raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
-
- return signature_method
-
- def _get_verifier(self, request):
- return request.get_parameter('oauth_verifier')
-
- def _check_signature(self, request, consumer, token):
- timestamp, nonce = request._get_timestamp_nonce()
- self._check_timestamp(timestamp)
- signature_method = self._get_signature_method(request)
-
- try:
- signature = request.get_parameter('oauth_signature')
- except:
- raise MissingSignature('Missing oauth_signature.')
-
- # Validate the signature.
- valid = signature_method.check(request, consumer, token, signature)
-
- if not valid:
- key, base = signature_method.signing_base(request, consumer, token)
-
- raise Error('Invalid signature. Expected signature base '
- 'string: %s' % base)
-
- def _check_timestamp(self, timestamp):
- """Verify that timestamp is recentish."""
- timestamp = int(timestamp)
- now = int(time.time())
- lapsed = now - timestamp
- if lapsed > self.timestamp_threshold:
- raise Error('Expired timestamp: given %d and now %s has a '
- 'greater difference than threshold %d' % (timestamp, now,
- self.timestamp_threshold))
-
-
class SignatureMethod(object):
"""A way of signing requests.
97 oauth2/client.py
View
@@ -0,0 +1,97 @@
+"""
+The MIT License
+
+Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
+
+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.
+"""
+
+import httplib2
+import oauth2
+import urllib
+
+class Client(httplib2.Http):
+ """OAuthClient is a worker to attempt to execute a request."""
+
+ def __init__(self, consumer, token=None, cache=None, timeout=None,
+ proxy_info=None):
+
+ if consumer is not None and not isinstance(consumer, oauth2.Consumer):
+ raise ValueError("Invalid consumer.")
+
+ if token is not None and not isinstance(token, oauth2.Token):
+ raise ValueError("Invalid token.")
+
+ self.consumer = consumer
+ self.token = token
+ self.method = oauth2.SignatureMethod_HMAC_SHA1()
+
+ httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info)
+
+ def set_signature_method(self, method):
+ if not isinstance(method, oauth2.SignatureMethod):
+ raise ValueError("Invalid signature method.")
+
+ self.method = method
+
+ def request(self, uri, method="GET", body='', headers=None,
+ redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
+ DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded'
+
+ if not isinstance(headers, dict):
+ headers = {}
+
+ if method == "POST":
+ headers['Content-Type'] = headers.get('Content-Type',
+ DEFAULT_POST_CONTENT_TYPE)
+
+ is_form_encoded = \
+ headers.get('Content-Type') == 'application/x-www-form-urlencoded'
+
+ if is_form_encoded and body:
+ parameters = oauth2.parse_qs(body)
+ else:
+ parameters = None
+
+ req = oauth2.Request.from_consumer_and_token(self.consumer,
+ token=self.token, http_method=method, http_url=uri,
+ parameters=parameters, body=body, is_form_encoded=is_form_encoded)
+
+ req.sign_request(self.method, self.consumer, self.token)
+
+ schema, rest = urllib.splittype(uri)
+ if rest.startswith('//'):
+ hierpart = '//'
+ else:
+ hierpart = ''
+ host, rest = urllib.splithost(rest)
+
+ realm = schema + ':' + hierpart + host
+
+ if is_form_encoded:
+ body = req.to_postdata()
+ elif method == "GET":
+ uri = req.to_url()
+ else:
+ headers.update(req.to_header(realm=realm))
+
+ return httplib2.Http.request(self, uri, method=method, body=body,
+ headers=headers, redirections=redirections,
+ connection_type=connection_type)
+
122 oauth2/server.py
View
@@ -0,0 +1,122 @@
+"""
+The MIT License
+
+Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
+
+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.
+"""
+
+import oauth2
+import time
+
+class Server(object):
+ """A skeletal implementation of a service provider, providing protected
+ resources to requests from authorized consumers.
+
+ This class implements the logic to check requests for authorization. You
+ can use it with your web server or web framework to protect certain
+ resources with OAuth.
+ """
+
+ timestamp_threshold = 300 # In seconds, five minutes.
+ version = oauth2.OAUTH_VERSION
+ signature_methods = None
+
+ def __init__(self, signature_methods=None):
+ self.signature_methods = signature_methods or {}
+
+ def add_signature_method(self, signature_method):
+ self.signature_methods[signature_method.name] = signature_method
+ return self.signature_methods
+
+ def verify_request(self, request, consumer, token):
+ """Verifies an api call and checks all the parameters."""
+
+ self._check_version(request)
+ self._check_signature(request, consumer, token)
+ parameters = request.get_nonoauth_parameters()
+ return parameters
+
+ def build_authenticate_header(self, realm=''):
+ """Optional support for the authenticate header."""
+ return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
+
+ def _check_version(self, request):
+ """Verify the correct version of the request for this server."""
+ version = self._get_version(request)
+ if version and version != self.version:
+ raise oauth2.Error('OAuth version %s not supported.' % str(version))
+
+ def _get_version(self, request):
+ """Return the version of the request for this server."""
+ try:
+ version = request.get_parameter('oauth_version')
+ except:
+ version = oauth2.OAUTH_VERSION
+
+ return version
+
+ def _get_signature_method(self, request):
+ """Figure out the signature with some defaults."""
+ try:
+ signature_method = request.get_parameter('oauth_signature_method')
+ except:
+ signature_method = oauth2.SIGNATURE_METHOD
+
+ try:
+ # Get the signature method object.
+ signature_method = self.signature_methods[signature_method]
+ except:
+ signature_method_names = ', '.join(self.signature_methods.keys())
+ raise oauth2.Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
+
+ return signature_method
+
+ def _get_verifier(self, request):
+ return request.get_parameter('oauth_verifier')
+
+ def _check_signature(self, request, consumer, token):
+ timestamp, nonce = request._get_timestamp_nonce()
+ self._check_timestamp(timestamp)
+ signature_method = self._get_signature_method(request)
+
+ try:
+ signature = request.get_parameter('oauth_signature')
+ except:
+ raise oauth2.MissingSignature('Missing oauth_signature.')
+
+ # Validate the signature.
+ valid = signature_method.check(request, consumer, token, signature)
+
+ if not valid:
+ key, base = signature_method.signing_base(request, consumer, token)
+
+ raise oauth2.Error('Invalid signature. Expected signature base '
+ 'string: %s' % base)
+
+ def _check_timestamp(self, timestamp):
+ """Verify that timestamp is recentish."""
+ timestamp = int(timestamp)
+ now = int(time.time())
+ lapsed = now - timestamp
+ if lapsed > self.timestamp_threshold:
+ raise oauth2.Error('Expired timestamp: given %d and now %s has a '
+ 'greater difference than threshold %d' % (timestamp, now,
+ self.timestamp_threshold))
+
38 tests/test_oauth.py
View
@@ -27,6 +27,8 @@
import os
import unittest
import oauth2 as oauth
+from oauth2.client import Client
+from oauth2.server import Server
import random
import time
import urllib
@@ -655,7 +657,7 @@ def test_get_normalized_parameters_ignores_auth_signature(self):
def test_set_signature_method(self):
consumer = oauth.Consumer('key', 'secret')
- client = oauth.Client(consumer)
+ client = Client(consumer)
class Blah:
pass
@@ -959,16 +961,16 @@ def setUp(self):
self.request.sign_request(signature_method, self.consumer, self.token)
def test_init(self):
- server = oauth.Server(signature_methods={'HMAC-SHA1' : oauth.SignatureMethod_HMAC_SHA1()})
+ server = Server(signature_methods={'HMAC-SHA1' : oauth.SignatureMethod_HMAC_SHA1()})
self.assertTrue('HMAC-SHA1' in server.signature_methods)
self.assertTrue(isinstance(server.signature_methods['HMAC-SHA1'],
oauth.SignatureMethod_HMAC_SHA1))
- server = oauth.Server()
+ server = Server()
self.assertEquals(server.signature_methods, {})
def test_add_signature_method(self):
- server = oauth.Server()
+ server = Server()
res = server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
self.assertTrue(len(res) == 1)
self.assertTrue('HMAC-SHA1' in res)
@@ -982,7 +984,7 @@ def test_add_signature_method(self):
oauth.SignatureMethod_PLAINTEXT))
def test_verify_request(self):
- server = oauth.Server()
+ server = Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
parameters = server.verify_request(self.request, self.consumer,
@@ -996,7 +998,7 @@ def test_verify_request(self):
self.assertEquals(parameters['multi'], ['FOO','BAR'])
def test_build_authenticate_header(self):
- server = oauth.Server()
+ server = Server()
headers = server.build_authenticate_header('example.com')
self.assertTrue('WWW-Authenticate' in headers)
self.assertEquals('OAuth realm="example.com"',
@@ -1024,7 +1026,7 @@ def test_no_version(self):
signature_method = oauth.SignatureMethod_HMAC_SHA1()
self.request.sign_request(signature_method, self.consumer, self.token)
- server = oauth.Server()
+ server = Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
parameters = server.verify_request(self.request, self.consumer,
@@ -1053,7 +1055,7 @@ def test_invalid_version(self):
signature_method = oauth.SignatureMethod_HMAC_SHA1()
request.sign_request(signature_method, consumer, token)
- server = oauth.Server()
+ server = Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
self.assertRaises(oauth.Error, server.verify_request, request, consumer, token)
@@ -1081,7 +1083,7 @@ def test_invalid_signature_method(self):
signature_method = SignatureMethod_Bad()
request.sign_request(signature_method, consumer, token)
- server = oauth.Server()
+ server = Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
self.assertRaises(oauth.Error, server.verify_request, request,
@@ -1111,7 +1113,7 @@ def test_missing_signature(self):
request.sign_request(signature_method, consumer, token)
del request['oauth_signature']
- server = oauth.Server()
+ server = Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
self.assertRaises(oauth.MissingSignature, server.verify_request,
@@ -1181,28 +1183,28 @@ class Blah():
pass
try:
- client = oauth.Client(Blah())
+ client = Client(Blah())
self.fail("Client.__init__() accepted invalid Consumer.")
except ValueError:
pass
consumer = oauth.Consumer('token', 'secret')
try:
- client = oauth.Client(consumer, Blah())
+ client = Client(consumer, 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)
+ client = 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)
+ client = Client(self.consumer, None)
resp, content = client.request(self._uri('request_token'), "POST")
self.assertEquals(int(resp['status']), 200)
@@ -1212,7 +1214,7 @@ def test_access_token_post(self):
self.assertTrue('oauth_token_secret' in res)
def _two_legged(self, method):
- client = oauth.Client(self.consumer, None)
+ client = Client(self.consumer, None)
return client.request(self._uri('two_legged'), method,
body=urllib.urlencode(self.body))
@@ -1237,7 +1239,7 @@ def test_multipart_post_does_not_alter_body(self, mockHttpRequest):
}
content_type, body = self.create_simple_multipart_data(data)
- client = oauth.Client(self.consumer, None)
+ client = Client(self.consumer, None)
uri = self._uri('two_legged')
def mockrequest(cl, ur, **kw):
@@ -1260,7 +1262,7 @@ def mockrequest(cl, ur, **kw):
@mock.patch('httplib2.Http.request')
def test_url_with_query_string(self, mockHttpRequest):
uri = 'http://example.com/foo/bar/?show=thundercats&character=snarf'
- client = oauth.Client(self.consumer, None)
+ client = Client(self.consumer, None)
random_result = random.randint(1,100)
def mockrequest(cl, ur, **kw):
@@ -1292,7 +1294,7 @@ def mockrequest(cl, ur, **kw):
@mock.patch('httplib2.Http.request')
@mock.patch('oauth2.Request.from_consumer_and_token')
def test_multiple_values_for_a_key(self, mockReqConstructor, mockHttpRequest):
- client = oauth.Client(self.consumer, None)
+ client = Client(self.consumer, None)
request = oauth.Request("GET", "http://example.com/fetch.php", parameters={'multi': ['1', '2']})
mockReqConstructor.return_value = request
Something went wrong with that request. Please try again.