src/notes/middlewares.py
author ymh <ymh.work@gmail.com>
Sat, 01 Dec 2018 02:38:12 +0100
changeset 188 00cf90eb0f5a
parent 128 34a75bd8d0b9
permissions -rw-r--r--
Correct index file and add a favicon. increment version

"""
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)