Commits

Vladimir Mihailenco committed 2587acd

Cleanup API

Comments (0)

Files changed (2)

oauth_provider/decorators.py

 try:
     from functools import update_wrapper
 except ImportError:
-    from django.utils.functional import update_wrapper  # Python 2.3, 2.4 fallback.
+    # Python 2.3, 2.4 fallback.
+    from django.utils.functional import update_wrapper
 
 from django.utils.translation import ugettext as _
 
-from utils import initialize_server_request, send_oauth_error, get_oauth_request
+from utils import send_oauth_error
+from utils import get_oauth_request
+from utils import get_oauth_server
 from consts import OAUTH_PARAMETERS_NAMES
 from store import store, InvalidTokenError
 
+
 def oauth_required(view_func=None, resource_name=None):
     return CheckOAuth(view_func, resource_name)
 
+
 class CheckOAuth(object):
     """
     Class that checks that the OAuth parameters passes the given test, raising
         self.view_func = view_func
         self.resource_name = resource_name
         update_wrapper(self, view_func)
-        
+
     def __get__(self, obj, cls=None):
         view_func = self.view_func.__get__(obj, cls)
         return CheckOAuth(view_func, self.resource_name)
-    
+
     def __call__(self, request, *args, **kwargs):
         if self.is_valid_request(request):
             oauth_request = get_oauth_request(request)
-            consumer = store.get_consumer(request, oauth_request, 
+            consumer = store.get_consumer(request, oauth_request,
                             oauth_request.get_parameter('oauth_consumer_key'))
             try:
-                token = store.get_access_token(request, oauth_request, 
-                                consumer, oauth_request.get_parameter('oauth_token'))
+                token = store.get_access_token(request, oauth_request,
+                    consumer, oauth_request.get_parameter('oauth_token'))
             except InvalidTokenError:
-                return send_oauth_error(Error(_('Invalid access token: %s') % oauth_request.get_parameter('oauth_token')))
+                return send_oauth_error(Error(_('Invalid access token: %s') %
+                    oauth_request.get_parameter('oauth_token')))
             try:
-                parameters = self.validate_token(request, consumer, token)
+                self.validate_token(oauth_request, consumer, token)
             except Error, e:
                 return send_oauth_error(e)
-            
-            if self.resource_name and token.resource.name != self.resource_name:
-                return send_oauth_error(Error(_('You are not allowed to access this resource.')))
+
+            if (self.resource_name and
+                    token.resource.name != self.resource_name):
+                return send_oauth_error(Error(
+                    _('You are not allowed to access this resource.')))
             elif consumer and token:
                 return self.view_func(request, *args, **kwargs)
-        
+
         return send_oauth_error(Error(_('Invalid request parameters.')))
 
     @staticmethod
         return is_in(auth_params) or is_in(request.REQUEST)
 
     @staticmethod
-    def validate_token(request, consumer, token):
-        oauth_server, oauth_request = initialize_server_request(request)
+    def validate_token(oauth_request, consumer, token):
+        oauth_server = get_oauth_server()
         return oauth_server.verify_request(oauth_request, consumer, token)

oauth_provider/utils.py

 
 from consts import MAX_URL_LENGTH
 
+
 OAUTH_REALM_KEY_NAME = getattr(settings, 'OAUTH_REALM_KEY_NAME', '')
-OAUTH_SIGNATURE_METHODS = getattr(settings, 'OAUTH_SIGNATURE_METHODS', ['plaintext', 'hmac-sha1'])
-OAUTH_BLACKLISTED_HOSTNAMES = getattr(settings, 'OAUTH_BLACKLISTED_HOSTNAMES', [])
+OAUTH_SIGNATURE_METHODS = getattr(settings, 'OAUTH_SIGNATURE_METHODS',
+                                  ['plaintext', 'hmac-sha1'])
+OAUTH_BLACKLISTED_HOSTNAMES = getattr(settings, 'OAUTH_BLACKLISTED_HOSTNAMES',
+                                      [])
 
-def initialize_server_request(request):
+
+def get_oauth_server():
     """Shortcut for initialization."""
-    # Django converts Authorization header in HTTP_AUTHORIZATION
-    # Warning: it doesn't happen in tests but it's useful, do not remove!
-    auth_header = {}
-    if 'Authorization' in request.META:
-        auth_header = {'Authorization': request.META['Authorization']}
-    elif 'HTTP_AUTHORIZATION' in request.META:
-        auth_header =  {'Authorization': request.META['HTTP_AUTHORIZATION']}
-   
-    # Don't include extra parameters when request.method is POST and 
-    # request.MIME['CONTENT_TYPE'] is "application/x-www-form-urlencoded" 
-    # (See http://oauth.net/core/1.0a/#consumer_req_param).
-    # But there is an issue with Django's test Client and custom content types
-    # so an ugly test is made here, if you find a better solution...
-    parameters = {}
-    if request.method == "POST" and \
-        (request.META.get('CONTENT_TYPE') == "application/x-www-form-urlencoded" \
-            or request.META.get('SERVER_NAME') == 'testserver'):
-        parameters = dict((k, v.encode('utf-8')) for (k, v) in request.REQUEST.iteritems())
+    oauth_server = oauth.Server()
+    if 'plaintext' in OAUTH_SIGNATURE_METHODS:
+        oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())
+    if 'hmac-sha1' in OAUTH_SIGNATURE_METHODS:
+        oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
+    return oauth_server
 
-    oauth_request = oauth.Request.from_request(request.method, 
-                                              request.build_absolute_uri(request.path), 
-                                              headers=auth_header,
-                                              parameters=parameters,
-                                              query_string=request.META.get('QUERY_STRING', ''))
-    if oauth_request:
-        oauth_server = oauth.Server()
-        if 'plaintext' in OAUTH_SIGNATURE_METHODS:
-            oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())
-        if 'hmac-sha1' in OAUTH_SIGNATURE_METHODS:
-            oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
-    else:
-        oauth_server = None
-    return oauth_server, oauth_request
 
 def send_oauth_error(err=None):
     """Shortcut for sending an error."""
         response[k] = v
     return response
 
+
 def get_oauth_request(request):
     """ Converts a Django request object into an `oauth2.Request` object. """
-    headers = {}
-    if 'HTTP_AUTHORIZATION' in request.META:
-        headers['Authorization'] = request.META['HTTP_AUTHORIZATION']
-    return oauth.Request.from_request(request.method, 
-                                      request.build_absolute_uri(request.path), 
-                                      headers, 
-                                      dict((k, v.encode('utf-8')) for (k, v) in request.REQUEST.iteritems()))
+
+    # Django converts Authorization header in HTTP_AUTHORIZATION
+    # Warning: it doesn't happen in tests but it's useful, do not remove!
+    auth_header = {}
+    if 'Authorization' in request.META:
+        auth_header = {'Authorization': request.META['Authorization']}
+    elif 'HTTP_AUTHORIZATION' in request.META:
+        auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}
+
+    parameters = dict((k, v.encode('utf-8'))
+                      for (k, v) in request.REQUEST.iteritems())
+    return oauth.Request.from_request(request.method,
+        request.build_absolute_uri(),
+        headers=auth_header,
+        parameters=parameters,
+        query_string=request.META.get('QUERY_STRING', ''))
+
 
 def verify_oauth_request(request, oauth_request, consumer, token=None):
     """ Helper function to verify requests. """
     from store import store
 
     # Check nonce
-    if not store.check_nonce(request, oauth_request, oauth_request['oauth_nonce']):
+    if not store.check_nonce(request, oauth_request,
+                             oauth_request['oauth_nonce']):
         return False
 
     # Verify request
     try:
-        oauth_server = oauth.Server()
-        oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
-        oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())
+        oauth_server = get_oauth_server()
 
         # Ensure the passed keys and secrets are ascii, or HMAC will complain.
-        consumer = oauth.Consumer(consumer.key.encode('ascii', 'ignore'), consumer.secret.encode('ascii', 'ignore'))
+        consumer = oauth.Consumer(consumer.key.encode('ascii', 'ignore'),
+                                  consumer.secret.encode('ascii', 'ignore'))
         if token is not None:
-            token = oauth.Token(token.key.encode('ascii', 'ignore'), token.secret.encode('ascii', 'ignore'))
+            token = oauth.Token(token.key.encode('ascii', 'ignore'),
+                                token.secret.encode('ascii', 'ignore'))
 
         oauth_server.verify_request(oauth_request, consumer, token)
-    except oauth.Error, err:
+    except oauth.Error:
         return False
 
     return True
 
     missing = list(param for param in params if param not in oauth_request)
     if missing:
-        return HttpResponseBadRequest('Missing OAuth parameters: %s' % (', '.join(missing)))
+        return HttpResponseBadRequest('Missing OAuth parameters: %s' %
+                                      (', '.join(missing)))
 
     return None
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.