Source code for abstract.middleware.expose_user
import contextlib
from rest_framework_simplejwt.authentication import JWTAuthentication
from abstract.managers import BaseManager
from abstract.models import BaseModel
[docs]
class InjectUserObj:
"""
Middleware to inject the current user into the Base Model Class.
This middleware retrieves the current authenticated user from the request
and injects it into the Base Model Class for tracking user interactions.
Args:
get_response (callable): The next middleware in the chain or the view.
"""
def __init__(self, get_response):
"""
Initializes the InjectUserObj middleware.
Args:
get_response (callable): The next middleware in the chain or the view.
"""
self.get_response = get_response
def __call__(self, request):
"""
Process a request to inject the current authenticated user into the Base Model Class.
This method is called for each request.
Args:
request (HttpRequest): The request object generated by the Django Web Server.
Returns:
HttpResponse: The HTTP response generated by the view or middleware chain.
"""
if not request.user.is_authenticated:
auth_header = request.headers.get("Authorization", "").split()
if len(auth_header) == 2 and auth_header[0].lower() == "bearer":
with contextlib.suppress(Exception):
request.user = JWTAuthentication().get_user(
JWTAuthentication().get_validated_token(auth_header[1])
)
BaseModel.operating_user = (
request.user if request.user.is_authenticated else None
)
return self.get_response(request)