Files

30 lines
962 B
Python

from django.contrib.auth.models import AnonymousUser
from rest_framework_simplejwt.authentication import JWTAuthentication
class JWTRequestActorMiddleware:
"""
Resolve Bearer tokens before DRF runs so middleware-driven audit hooks
can see the authenticated actor on API requests.
"""
def __init__(self, get_response):
self.get_response = get_response
self.authenticator = JWTAuthentication()
def __call__(self, request):
current_user = getattr(request, "user", None)
if not getattr(current_user, "is_authenticated", False):
try:
authenticated = self.authenticator.authenticate(request)
except Exception:
authenticated = None
if authenticated is not None:
request.user = authenticated[0]
elif current_user is None:
request.user = AnonymousUser()
return self.get_response(request)