Skip to content

Commit

Permalink
Merge branch 'master' of git://github.com/renanivo/django-oauth-toolk…
Browse files Browse the repository at this point in the history
…it into foo
  • Loading branch information
synasius committed Mar 26, 2015
2 parents cc9cb4d + c754690 commit 8a43351
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
8 changes: 8 additions & 0 deletions oauth2_provider/middleware.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.contrib.auth import authenticate
from django.utils.cache import patch_vary_headers


class OAuth2TokenMiddleware(object):
Expand All @@ -16,6 +17,9 @@ class OAuth2TokenMiddleware(object):
tries to authenticate user with the OAuth2 access token and set request.user field. Setting
also request._cached_user field makes AuthenticationMiddleware use that instead of the one from
the session.
It also adds 'Authorization' to the 'Vary' header. So that django's cache middleware or a
reverse proxy can create proper cache keys
"""
def process_request(self, request):
# do something only if request contains a Bearer token
Expand All @@ -24,3 +28,7 @@ def process_request(self, request):
user = authenticate(request=request)
if user:
request.user = request._cached_user = user

def process_response(self, request, response):
patch_vary_headers(response, ('Authorization',))
return response
22 changes: 22 additions & 0 deletions oauth2_provider/tests/test_auth_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from django.contrib.auth.models import AnonymousUser
from django.utils.timezone import now, timedelta
from django.conf.global_settings import MIDDLEWARE_CLASSES
from django.http import HttpResponse

from ..compat import get_user_model
from ..models import get_application_model
Expand Down Expand Up @@ -112,3 +113,24 @@ def test_middleware_success(self):
request = self.factory.get("/a-resource", **auth_headers)
m.process_request(request)
self.assertEqual(request.user, self.user)

def test_middleware_response(self):
m = OAuth2TokenMiddleware()
auth_headers = {
'HTTP_AUTHORIZATION': 'Bearer ' + 'tokstr',
}
request = self.factory.get("/a-resource", **auth_headers)
response = HttpResponse()
processed = m.process_response(request, response)
self.assertIs(response, processed)

def test_middleware_response_header(self):
m = OAuth2TokenMiddleware()
auth_headers = {
'HTTP_AUTHORIZATION': 'Bearer ' + 'tokstr',
}
request = self.factory.get("/a-resource", **auth_headers)
response = HttpResponse()
m.process_response(request, response)
self.assertIn('Vary', response)
self.assertIn('Authorization', response['Vary'])

0 comments on commit 8a43351

Please sign in to comment.