Skip to content

Commit

Permalink
Prefer simplejson, but fall back to json
Browse files Browse the repository at this point in the history
  • Loading branch information
hpk committed Nov 2, 2012
1 parent 8624f18 commit f8205e2
Show file tree
Hide file tree
Showing 11 changed files with 154 additions and 150 deletions.
31 changes: 16 additions & 15 deletions oauth2app/authenticate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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*
"""
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -279,24 +280,24 @@ 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.
**Args:**
* *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(
Expand All @@ -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:
Expand Down
5 changes: 3 additions & 2 deletions oauth2app/authorize.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions oauth2app/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
Django>=1.2.3
simplejson>=2.1.5
django-uni-form>=0.8.0
25 changes: 13 additions & 12 deletions tests/testsite/apps/api/tests/base.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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,
Expand All @@ -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"]
return json.loads(response.content)["access_token"]
47 changes: 24 additions & 23 deletions tests/testsite/apps/api/tests/bearer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#-*- coding: utf-8 -*-

from simplejson import loads
try: import simplejson as json
except ImportError: import json
from .base import *


Expand All @@ -10,53 +11,53 @@ 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)

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)
self.assertEqual(response.status_code, 401)
5 changes: 3 additions & 2 deletions tests/testsite/apps/api/tests/granttype.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
29 changes: 15 additions & 14 deletions tests/testsite/apps/api/tests/json.py
Original file line number Diff line number Diff line change
@@ -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))
self.assertEqual(response.status_code, 200)
self.assertTrue("error" in json.loads(content))
Loading

0 comments on commit f8205e2

Please sign in to comment.