src/notes/middlewares.py
changeset 128 34a75bd8d0b9
equal deleted inserted replaced
127:006c5270128c 128:34a75bd8d0b9
       
     1 """
       
     2 Taken from https://gist.github.com/AndrewJHart/9bb9eaea2523cd2144cf959f48a14194
       
     3 and https://github.com/GetBlimp/django-rest-framework-jwt/issues/45#issuecomment-255383031
       
     4 """
       
     5 from django.contrib.auth.middleware import get_user
       
     6 from django.contrib.auth.models import AnonymousUser
       
     7 from django.utils.functional import SimpleLazyObject
       
     8 from rest_framework_jwt.authentication import JSONWebTokenAuthentication
       
     9 from rest_framework import exceptions
       
    10 
       
    11 
       
    12 def get_user_jwt(request):
       
    13     """
       
    14     Replacement for django session auth get_user & auth.get_user for
       
    15      JSON Web Token authentication. Inspects the token for the user_id,
       
    16      attempts to get that user from the DB & assigns the user on the
       
    17      request object. Otherwise it defaults to AnonymousUser.
       
    18     This will work with existing decorators like LoginRequired, whereas
       
    19     the standard restframework_jwt auth only works at the view level
       
    20     forcing all authenticated users to appear as AnonymousUser ;)
       
    21     Returns: instance of user object or AnonymousUser object
       
    22     """
       
    23     user = get_user(request)
       
    24     if user.is_authenticated:
       
    25         return user
       
    26 
       
    27     jwt_authentication = JSONWebTokenAuthentication()
       
    28     if jwt_authentication.get_jwt_value(request):
       
    29         try:
       
    30             user, _ = jwt_authentication.authenticate(request)
       
    31         except exceptions.AuthenticationFailed:
       
    32             user = None
       
    33 
       
    34     return user or AnonymousUser()
       
    35 
       
    36 
       
    37 class JWTAuthenticationMiddleware(object):
       
    38 
       
    39     def __init__(self, get_response):
       
    40         self.get_response = get_response
       
    41         # One-time configuration and initialization.
       
    42 
       
    43     def __call__(self, request):
       
    44         request.user = SimpleLazyObject(lambda: get_user_jwt(request))
       
    45         return self.get_response(request)