Created
December 9, 2013 16:08
-
-
Save breyten/7874673 to your computer and use it in GitHub Desktop.
Middleware for Django to authenticate a user with an OAuth token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pprint import pprint | |
import re | |
from django.conf import settings | |
from django.contrib.auth.models import User, check_password | |
from django.contrib.auth import authenticate, login | |
from apps.api.authentication import verify_access_token, OAuthError | |
class OAuth2Middleware( object ): | |
"""Authentication Middleware for logging in with a token. | |
Backend will get user. | |
""" | |
def process_request(self, request): | |
#if not hasattr(request, 'user'): | |
# raise ImproperlyConfigured() | |
token = None | |
if 'HTTP_AUTHORIZATION' not in request.META: | |
if "oauth2_token" not in request.GET: | |
return | |
#print "authentication via get request params!" | |
token = request.GET["oauth2_token"] | |
else: | |
#print "authenticating via authorization header!" | |
auth_header = request.META['HTTP_AUTHORIZATION'] | |
auth_method, token = re.split(re.compile(r'\s+', re.U), auth_header, 1) | |
if token is None: | |
return | |
full_token = None | |
try: | |
full_token = verify_access_token(token) | |
except OAuthError, e: | |
pass | |
if full_token is None: | |
return | |
user = full_token.user | |
# this is an ugly fix to make the login work | |
# See the authenticate method at: | |
# https://github.com/django/django/blob/master/django/contrib/auth/__init__.py | |
user.backend = "%s.%s" % (self.__module__, self.__class__.__name__) | |
#print "User:" | |
#pprint(user) | |
request.user = user | |
login(request, user) | |
def get_user(self, user_id): | |
try: | |
return User.objects.get(pk=user_id) | |
except User.DoesNotExist: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment