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