diff --git a/oauth2app/authenticate.py b/oauth2app/authenticate.py index e6876b5..0edd2ed 100644 --- a/oauth2app/authenticate.py +++ b/oauth2app/authenticate.py @@ -4,9 +4,10 @@ """OAuth 2.0 Authentication""" +try: import simplejson as json +except ImportError: import json from hashlib import sha256 from urlparse import parse_qsl -from simplejson import dumps from django.conf import settings from django.http import HttpResponse from .exceptions import OAuth2Exception @@ -51,8 +52,8 @@ class Authenticator(object): the scope the authenticator will authenticate. *Default None* * *authentication_method:* Accepted authentication methods. Possible - values are: oauth2app.consts.MAC, oauth2app.consts.BEARER, - oauth2app.consts.MAC | oauth2app.consts.BEARER, + values are: oauth2app.consts.MAC, oauth2app.consts.BEARER, + oauth2app.consts.MAC | oauth2app.consts.BEARER, *Default oauth2app.consts.BEARER* """ @@ -65,11 +66,11 @@ class Authenticator(object): attempted_validation = False def __init__( - self, - scope=None, - authentication_method=AUTHENTICATION_METHOD): + self, + scope=None, + authentication_method=AUTHENTICATION_METHOD): if authentication_method not in [BEARER, MAC, BEARER | MAC]: - raise OAuth2Exception("Possible values for authentication_method" + raise OAuth2Exception("Possible values for authentication_method" " are oauth2app.consts.MAC, oauth2app.consts.BEARER, " "oauth2app.consts.MAC | oauth2app.consts.BEARER") self.authentication_method = authentication_method @@ -166,7 +167,7 @@ def _validate_mac(self, mac_header): nonce_timestamp, nonce_string = mac_header["nonce"].split(":") mac = sha256("\n".join([ mac_header["nonce"], # The nonce value generated for the request - self.request.method.upper(), # The HTTP request method + self.request.method.upper(), # The HTTP request method "XXX", # The HTTP request-URI self.request_hostname, # The hostname included in the HTTP request self.request_port, # The port as included in the HTTP request @@ -185,7 +186,7 @@ def _validate_mac(self, mac_header): # the determination of staleness is left up to the server to # define). # 3. Verify the scope and validity of the MAC credentials. - + def _get_user(self): """The user associated with the valid access token. @@ -279,16 +280,16 @@ class JSONAuthenticator(Authenticator): * *scope:* A iterable of oauth2app.models.AccessRange objects. """ - + callback = None - + def __init__(self, scope=None): Authenticator.__init__(self, scope=scope) - + def validate(self, request): self.callback = request.REQUEST.get('callback') return Authenticator.validate(self, request) - + def response(self, data): """Returns a HttpResponse object of JSON serialized data. @@ -296,7 +297,7 @@ def response(self, data): * *data:* Object to be JSON serialized and returned. """ - json_data = dumps(data) + json_data = json.dumps(data) if self.callback is not None: json_data = "%s(%s);" % (self.callback, json_data) response = HttpResponse( @@ -307,7 +308,7 @@ def response(self, data): def error_response(self): """Returns a HttpResponse object of JSON error data.""" if self.error is not None: - content = dumps({ + content = json.dumps({ "error":getattr(self.error, "error", "invalid_request"), "error_description":self.error.message}) else: diff --git a/oauth2app/authorize.py b/oauth2app/authorize.py index 5b563b0..35b0bfa 100644 --- a/oauth2app/authorize.py +++ b/oauth2app/authorize.py @@ -4,8 +4,9 @@ """OAuth 2.0 Authorization""" -import simplejson as json -from django.http import absolute_http_url_re, HttpResponse, HttpResponseRedirect, HttpResponseBadRequest +try: import simplejson as json +except ImportError: import json +from django.http import absolute_http_url_re, HttpResponseRedirect from urllib import urlencode from .consts import ACCESS_TOKEN_EXPIRATION, REFRESHABLE from .consts import CODE, TOKEN, CODE_AND_TOKEN diff --git a/oauth2app/token.py b/oauth2app/token.py index 3549d93..f2c2b4a 100644 --- a/oauth2app/token.py +++ b/oauth2app/token.py @@ -4,11 +4,12 @@ """OAuth 2.0 Token Generation""" +try: import simplejson as json +except ImportError: import json from base64 import b64encode from django.http import HttpResponse from django.contrib.auth import authenticate from django.views.decorators.csrf import csrf_exempt -from simplejson import dumps from .exceptions import OAuth2Exception from .consts import ACCESS_TOKEN_EXPIRATION, REFRESH_TOKEN_LENGTH from .consts import AUTHENTICATION_METHOD, MAC, BEARER, MAC_KEY_LENGTH @@ -313,7 +314,7 @@ def error_response(self): else: e = InvalidRequest("Access Denied.") data = {'error': e.error, 'error_description': u'%s' % e.message} - json_data = dumps(data) + json_data = json.dumps(data) if self.callback is not None: json_data = "%s(%s);" % (self.callback, json_data) return HttpResponse( @@ -355,7 +356,7 @@ def grant_response(self): data['refresh_token'] = access_token.refresh_token if self.scope is not None: data['scope'] = ' '.join(self.scope) - json_data = dumps(data) + json_data = json.dumps(data) if self.callback is not None: json_data = "%s(%s);" % (self.callback, json_data) response = HttpResponse( diff --git a/requirements.txt b/requirements.txt index f870bf9..114797d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,2 @@ Django>=1.2.3 -simplejson>=2.1.5 django-uni-form>=0.8.0 diff --git a/tests/testsite/apps/api/tests/base.py b/tests/testsite/apps/api/tests/base.py index 179b44a..7e5fd5b 100644 --- a/tests/testsite/apps/api/tests/base.py +++ b/tests/testsite/apps/api/tests/base.py @@ -1,6 +1,7 @@ #-*- coding: utf-8 -*- -from simplejson import loads +try: import simplejson as json +except ImportError: import json from django.contrib.auth.models import User from oauth2app.models import Client from django.test.client import Client as DjangoTestClient @@ -20,32 +21,32 @@ class BaseTestCase(unittest.TestCase): - + user = None client_holder = None client_application = None def setUp(self): self.user = User.objects.create_user( - USER_USERNAME, - USER_EMAIL, + USER_USERNAME, + USER_EMAIL, USER_PASSWORD) self.user.first_name = USER_FIRSTNAME self.user.last_name = USER_LASTNAME self.user.save() self.client = User.objects.create_user(CLIENT_USERNAME, CLIENT_EMAIL) - self.client_application = Client.objects.create( - name="TestApplication", + self.client_application = Client.objects.create( + name="TestApplication", user=self.client) - + def tearDown(self): self.user.delete() self.client.delete() self.client_application.delete() - + def get_token(self): user = DjangoTestClient() - user.login(username=USER_USERNAME, password=USER_PASSWORD) + user.login(username=USER_USERNAME, password=USER_PASSWORD) parameters = { "client_id":self.client_application.key, "redirect_uri":REDIRECT_URI, @@ -61,7 +62,7 @@ def get_token(self): "redirect_uri":REDIRECT_URI} basic_auth = b64encode("%s:%s" % (self.client_application.key, self.client_application.secret)) response = client.get( - "/oauth2/token", - parameters, + "/oauth2/token", + parameters, HTTP_AUTHORIZATION="Basic %s" % basic_auth) - return loads(response.content)["access_token"] \ No newline at end of file + return json.loads(response.content)["access_token"] diff --git a/tests/testsite/apps/api/tests/bearer.py b/tests/testsite/apps/api/tests/bearer.py index 4075233..0af96bf 100644 --- a/tests/testsite/apps/api/tests/bearer.py +++ b/tests/testsite/apps/api/tests/bearer.py @@ -1,6 +1,7 @@ #-*- coding: utf-8 -*- -from simplejson import loads +try: import simplejson as json +except ImportError: import json from .base import * @@ -10,18 +11,18 @@ def test_00_bearer(self): client = DjangoTestClient() token = self.get_token() response = client.get( - "/api/email_str", - {}, + "/api/email_str", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) response = client.get( - "/api/email_str", - {}, + "/api/email_str", + {}, HTTP_AUTHORIZATION="Bearer2 %s" % token) self.assertEqual(response.status_code, 401) response = client.get( - "/api/email_str", - {}, + "/api/email_str", + {}, HTTP_AUTHORIZATION="Bearer !!!%s" % token) self.assertEqual(response.status_code, 401) @@ -29,34 +30,34 @@ def test_01_json_bearer(self): client = DjangoTestClient() token = self.get_token() response = client.get( - "/api/email_json", - {}, + "/api/email_json", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 200) - self.assertTrue("email" in loads(response.content)) + self.assertEqual(response.status_code, 200) + self.assertTrue("email" in json.loads(response.content)) response = client.get( - "/api/email_json", - {}, + "/api/email_json", + {}, HTTP_AUTHORIZATION="Bearer2 %s" % token) self.assertEqual(response.status_code, 401) - self.assertTrue("error" in loads(response.content)) + self.assertTrue("error" in json.loads(response.content)) response = client.get( - "/api/email_json", - {}, + "/api/email_json", + {}, HTTP_AUTHORIZATION="Bearer !!!%s" % token) self.assertEqual(response.status_code, 401) - self.assertTrue("error" in loads(response.content)) + self.assertTrue("error" in json.loads(response.content)) def test_02_automatic_fail(self): client = DjangoTestClient() token = self.get_token() response = client.get( - "/api/automatic_error_str", - {}, + "/api/automatic_error_str", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) self.assertEqual(response.status_code, 401) response = client.get( - "/api/automatic_error_json", - {}, + "/api/automatic_error_json", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 401) \ No newline at end of file + self.assertEqual(response.status_code, 401) diff --git a/tests/testsite/apps/api/tests/granttype.py b/tests/testsite/apps/api/tests/granttype.py index 512d522..e233fcc 100644 --- a/tests/testsite/apps/api/tests/granttype.py +++ b/tests/testsite/apps/api/tests/granttype.py @@ -1,6 +1,7 @@ #-*- coding: utf-8 -*- -from simplejson import loads +try: import simplejson as json +except ImportError: import json from base64 import b64encode from django.utils import unittest from django.contrib.auth.models import User @@ -56,4 +57,4 @@ def test_00_grant_type_client_credentials(self): "/oauth2/token", parameters, HTTP_AUTHORIZATION="Basic %s" % basic_auth) - token = loads(response.content) + token = json.loads(response.content) diff --git a/tests/testsite/apps/api/tests/json.py b/tests/testsite/apps/api/tests/json.py index cdcf33f..ede1280 100644 --- a/tests/testsite/apps/api/tests/json.py +++ b/tests/testsite/apps/api/tests/json.py @@ -1,32 +1,33 @@ #-*- coding: utf-8 -*- -from simplejson import loads +try: import simplejson as json +except ImportError: import json from .base import * class JSONTestCase(BaseTestCase): - + def test_00_email(self): client = DjangoTestClient() token = self.get_token() # Sufficient scope. response = client.get( - "/api/email_json", - {}, + "/api/email_json", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 200) - self.assertEqual(loads(response.content)["email"], USER_EMAIL) + self.assertEqual(response.status_code, 200) + self.assertEqual(json.loads(response.content)["email"], USER_EMAIL) response = client.get( - "/api/email_json?callback=foo", - {}, + "/api/email_json?callback=foo", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) # Remove the JSON callback. content = response.content.replace("foo(", "").replace(");", "") - self.assertEqual(loads(content)["email"], USER_EMAIL) + self.assertEqual(json.loads(content)["email"], USER_EMAIL) response = client.get( - "/api/email_json?callback=foo", - {}, + "/api/email_json?callback=foo", + {}, HTTP_AUTHORIZATION="Bearer !!!%s" % token) content = response.content.replace("foo(", "").replace(");", "") - self.assertEqual(response.status_code, 200) - self.assertTrue("error" in loads(content)) \ No newline at end of file + self.assertEqual(response.status_code, 200) + self.assertTrue("error" in json.loads(content)) diff --git a/tests/testsite/apps/api/tests/mac.py b/tests/testsite/apps/api/tests/mac.py index 6b4fe41..709ac74 100644 --- a/tests/testsite/apps/api/tests/mac.py +++ b/tests/testsite/apps/api/tests/mac.py @@ -1,6 +1,7 @@ #-*- coding: utf-8 -*- -from simplejson import loads +try: import simplejson as json +except ImportError: import json from base64 import b64encode from urlparse import urlparse, parse_qs from urllib import urlencode @@ -21,32 +22,32 @@ class MACTestCase(unittest.TestCase): - + user = None client_holder = None client_application = None def setUp(self): self.user = User.objects.create_user( - USER_USERNAME, - USER_EMAIL, + USER_USERNAME, + USER_EMAIL, USER_PASSWORD) self.user.first_name = USER_FIRSTNAME self.user.last_name = USER_LASTNAME self.user.save() self.client = User.objects.create_user(CLIENT_USERNAME, CLIENT_EMAIL) - self.client_application = Client.objects.create( - name="TestApplication", + self.client_application = Client.objects.create( + name="TestApplication", user=self.client) - + def tearDown(self): self.user.delete() self.client.delete() self.client_application.delete() - + def test_00_mac(self): user = DjangoTestClient() - user.login(username=USER_USERNAME, password=USER_PASSWORD) + user.login(username=USER_USERNAME, password=USER_PASSWORD) parameters = { "client_id":self.client_application.key, "redirect_uri":REDIRECT_URI, @@ -62,8 +63,8 @@ def test_00_mac(self): "redirect_uri":REDIRECT_URI} basic_auth = b64encode("%s:%s" % (self.client_application.key, self.client_application.secret)) response = client.get( - "/oauth2/token_mac", - parameters, + "/oauth2/token_mac", + parameters, HTTP_AUTHORIZATION="Basic %s" % basic_auth) - token = loads(response.content) - \ No newline at end of file + token = json.loads(response.content) + diff --git a/tests/testsite/apps/api/tests/responsetype.py b/tests/testsite/apps/api/tests/responsetype.py index 43f3345..f8fa323 100644 --- a/tests/testsite/apps/api/tests/responsetype.py +++ b/tests/testsite/apps/api/tests/responsetype.py @@ -1,12 +1,9 @@ #-*- coding: utf-8 -*- -from simplejson import loads -from base64 import b64encode from urlparse import urlparse, parse_qs from urllib import urlencode from django.utils import unittest from django.test.client import Client as DjangoTestClient -from django.contrib import auth from django.contrib.auth.models import User from oauth2app.models import Client @@ -22,39 +19,39 @@ class ResponseTypeTestCase(unittest.TestCase): - + user = None client_holder = None client_application = None def setUp(self): self.user = User.objects.create_user( - USER_USERNAME, - USER_EMAIL, + USER_USERNAME, + USER_EMAIL, USER_PASSWORD) self.user.first_name = USER_FIRSTNAME self.user.last_name = USER_LASTNAME self.user.save() self.client = User.objects.create_user(CLIENT_USERNAME, CLIENT_EMAIL) - self.client_application = Client.objects.create( - name="TestApplication", + self.client_application = Client.objects.create( + name="TestApplication", user=self.client) def tearDown(self): self.user.delete() self.client.delete() self.client_application.delete() - + def test_00_code(self): user = DjangoTestClient() - user.login(username=USER_USERNAME, password=USER_PASSWORD) + user.login(username=USER_USERNAME, password=USER_PASSWORD) parameters = { "client_id":self.client_application.key, "redirect_uri":REDIRECT_URI, "response_type":"code"} response = user.get("/oauth2/authorize_code?%s" % urlencode(parameters)) qs = parse_qs(urlparse(response['location']).query) - self.assertTrue("code" in qs) + self.assertTrue("code" in qs) parameters = { "client_id":self.client_application.key, "redirect_uri":REDIRECT_URI, @@ -62,10 +59,10 @@ def test_00_code(self): response = user.get("/oauth2/authorize_code?%s" % urlencode(parameters)) qs = parse_qs(urlparse(response['location']).query) self.assertTrue("error" in qs) - + def test_01_token(self): user = DjangoTestClient() - user.login(username=USER_USERNAME, password=USER_PASSWORD) + user.login(username=USER_USERNAME, password=USER_PASSWORD) parameters = { "client_id":self.client_application.key, "redirect_uri":REDIRECT_URI, @@ -83,7 +80,7 @@ def test_01_token(self): def test_02_token_mac(self): user = DjangoTestClient() - user.login(username=USER_USERNAME, password=USER_PASSWORD) + user.login(username=USER_USERNAME, password=USER_PASSWORD) parameters = { "client_id":self.client_application.key, "redirect_uri":REDIRECT_URI, @@ -94,7 +91,7 @@ def test_02_token_mac(self): def test_03_code_and_token(self): user = DjangoTestClient() - user.login(username=USER_USERNAME, password=USER_PASSWORD) + user.login(username=USER_USERNAME, password=USER_PASSWORD) parameters = { "client_id":self.client_application.key, "redirect_uri":REDIRECT_URI, @@ -113,7 +110,7 @@ def test_03_code_and_token(self): self.assertTrue("code" not in qs) fs = parse_qs(urlparse(response['location']).fragment) self.assertTrue("access_token" in fs) - + def test_04_invalid_response_type(self): user = DjangoTestClient() user.login(username=USER_USERNAME, password=USER_PASSWORD) @@ -123,4 +120,4 @@ def test_04_invalid_response_type(self): "response_type":"blah"} response = user.get("/oauth2/authorize_code_and_token?%s" % urlencode(parameters)) qs = parse_qs(urlparse(response['location']).query) - self.assertTrue("error" in qs) + self.assertTrue("error" in qs) diff --git a/tests/testsite/apps/api/tests/scope.py b/tests/testsite/apps/api/tests/scope.py index 41b0654..3bbae28 100644 --- a/tests/testsite/apps/api/tests/scope.py +++ b/tests/testsite/apps/api/tests/scope.py @@ -1,12 +1,12 @@ #-*- coding: utf-8 -*- -from simplejson import loads +try: import simplejson as json +except ImportError: import json from base64 import b64encode from urlparse import urlparse, parse_qs from urllib import urlencode from django.utils import unittest from django.test.client import Client as DjangoTestClient -from django.contrib import auth from django.contrib.auth.models import User from oauth2app.models import Client @@ -22,22 +22,22 @@ class ScopeTestCase(unittest.TestCase): - + user = None client_holder = None client_application = None def setUp(self): self.user = User.objects.create_user( - USER_USERNAME, - USER_EMAIL, + USER_USERNAME, + USER_EMAIL, USER_PASSWORD) self.user.first_name = USER_FIRSTNAME self.user.last_name = USER_LASTNAME self.user.save() self.client = User.objects.create_user(CLIENT_USERNAME, CLIENT_EMAIL) - self.client_application = Client.objects.create( - name="TestApplication", + self.client_application = Client.objects.create( + name="TestApplication", user=self.client) def tearDown(self): @@ -47,7 +47,7 @@ def tearDown(self): def test_00_first_name_scope(self): user = DjangoTestClient() - user.login(username=USER_USERNAME, password=USER_PASSWORD) + user.login(username=USER_USERNAME, password=USER_PASSWORD) parameters = { "client_id":self.client_application.key, "scope":"first_name", @@ -65,32 +65,32 @@ def test_00_first_name_scope(self): "scope":"first_name"} basic_auth = b64encode("%s:%s" % (self.client_application.key, self.client_application.secret)) response = client.get( - "/oauth2/token", - parameters, + "/oauth2/token", + parameters, HTTP_AUTHORIZATION="Basic %s" % basic_auth) - token = loads(response.content)["access_token"] + token = json.loads(response.content)["access_token"] # Sufficient scope. response = client.get( - "/api/first_name_str", - {}, + "/api/first_name_str", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) self.assertEqual(response.content, USER_FIRSTNAME) # Insufficient scope for last_name response = client.get( - "/api/last_name_str", - {}, - HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 403) + "/api/last_name_str", + {}, + HTTP_AUTHORIZATION="Bearer %s" % token) + self.assertEqual(response.status_code, 403) self.assertTrue("insufficient_scope" in str(response)) # Insufficient scope for first_name, last_name response = client.get( - "/api/first_and_last_name_str", - {}, - HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 403) + "/api/first_and_last_name_str", + {}, + HTTP_AUTHORIZATION="Bearer %s" % token) + self.assertEqual(response.status_code, 403) self.assertTrue("insufficient_scope" in str(response)) - + def test_01_no_scope(self): user = DjangoTestClient() user.login(username=USER_USERNAME, password=USER_PASSWORD) @@ -109,35 +109,35 @@ def test_01_no_scope(self): "redirect_uri":REDIRECT_URI} basic_auth = b64encode("%s:%s" % (self.client_application.key, self.client_application.secret)) response = client.get( - "/oauth2/token", - parameters, + "/oauth2/token", + parameters, HTTP_AUTHORIZATION="Basic %s" % basic_auth) - token = loads(response.content)["access_token"] + token = json.loads(response.content)["access_token"] # Sufficient scope. response = client.get( - "/api/email_str", - {}, + "/api/email_str", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) self.assertEqual(response.content, USER_EMAIL) # Insufficient scope for first_name, last_name response = client.get( - "/api/first_and_last_name_str", - {}, - HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 403) + "/api/first_and_last_name_str", + {}, + HTTP_AUTHORIZATION="Bearer %s" % token) + self.assertEqual(response.status_code, 403) self.assertTrue("insufficient_scope" in str(response)) # Insufficient scope for last_name response = client.get( - "/api/last_name_str", - {}, - HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 403) + "/api/last_name_str", + {}, + HTTP_AUTHORIZATION="Bearer %s" % token) + self.assertEqual(response.status_code, 403) self.assertTrue("insufficient_scope" in str(response)) def test_02_dual_scope(self): user = DjangoTestClient() - user.login(username=USER_USERNAME, password=USER_PASSWORD) + user.login(username=USER_USERNAME, password=USER_PASSWORD) parameters = { "client_id":self.client_application.key, "scope":"first_name last_name", @@ -155,22 +155,22 @@ def test_02_dual_scope(self): "scope":"first_name last_name"} basic_auth = b64encode("%s:%s" % (self.client_application.key, self.client_application.secret)) response = client.get( - "/oauth2/token", - parameters, + "/oauth2/token", + parameters, HTTP_AUTHORIZATION="Basic %s" % basic_auth) - token = loads(response.content)["access_token"] + token = json.loads(response.content)["access_token"] # Sufficient scope. response = client.get( - "/api/first_and_last_name_str", - {}, + "/api/first_and_last_name_str", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) self.assertEqual(response.content, USER_FIRSTNAME + " " + USER_LASTNAME) # Sufficient scope. response = client.get( - "/api/first_name_str", - {}, + "/api/first_name_str", + {}, HTTP_AUTHORIZATION="Bearer %s" % token) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) self.assertEqual(response.content, USER_FIRSTNAME) - \ No newline at end of file +