django-auditlog/auditlog/middleware.py
2022-08-08 11:53:03 +02:00

29 lines
948 B
Python

import contextlib
from auditlog.context import set_actor
class AuditlogMiddleware:
"""
Middleware to couple the request's user to log items. This is accomplished by currying the
signal receiver with the user from the request (or None if the user is not authenticated).
"""
def __init__(self, get_response=None):
self.get_response = get_response
def __call__(self, request):
if request.headers.get("X-Forwarded-For"):
# In case of proxy, set 'original' address
remote_addr = request.headers.get("X-Forwarded-For").split(",")[0]
else:
remote_addr = request.META.get("REMOTE_ADDR")
if hasattr(request, "user") and request.user.is_authenticated:
context = set_actor(actor=request.user, remote_addr=remote_addr)
else:
context = contextlib.nullcontext()
with context:
return self.get_response(request)