src/notes/middlewares.py
changeset 128 34a75bd8d0b9
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/notes/middlewares.py	Tue Jul 25 19:11:26 2017 +0200
@@ -0,0 +1,45 @@
+"""
+Taken from https://gist.github.com/AndrewJHart/9bb9eaea2523cd2144cf959f48a14194
+and https://github.com/GetBlimp/django-rest-framework-jwt/issues/45#issuecomment-255383031
+"""
+from django.contrib.auth.middleware import get_user
+from django.contrib.auth.models import AnonymousUser
+from django.utils.functional import SimpleLazyObject
+from rest_framework_jwt.authentication import JSONWebTokenAuthentication
+from rest_framework import exceptions
+
+
+def get_user_jwt(request):
+    """
+    Replacement for django session auth get_user & auth.get_user for
+     JSON Web Token authentication. Inspects the token for the user_id,
+     attempts to get that user from the DB & assigns the user on the
+     request object. Otherwise it defaults to AnonymousUser.
+    This will work with existing decorators like LoginRequired, whereas
+    the standard restframework_jwt auth only works at the view level
+    forcing all authenticated users to appear as AnonymousUser ;)
+    Returns: instance of user object or AnonymousUser object
+    """
+    user = get_user(request)
+    if user.is_authenticated:
+        return user
+
+    jwt_authentication = JSONWebTokenAuthentication()
+    if jwt_authentication.get_jwt_value(request):
+        try:
+            user, _ = jwt_authentication.authenticate(request)
+        except exceptions.AuthenticationFailed:
+            user = None
+
+    return user or AnonymousUser()
+
+
+class JWTAuthenticationMiddleware(object):
+
+    def __init__(self, get_response):
+        self.get_response = get_response
+        # One-time configuration and initialization.
+
+    def __call__(self, request):
+        request.user = SimpleLazyObject(lambda: get_user_jwt(request))
+        return self.get_response(request)