2019-05-11 10:11:12 +00:00
|
|
|
import contextlib
|
2014-02-07 19:59:16 +00:00
|
|
|
|
2019-05-11 10:11:12 +00:00
|
|
|
from auditlog.context import set_actor
|
2013-10-20 13:25:48 +00:00
|
|
|
|
2016-08-17 20:45:02 +00:00
|
|
|
|
2019-05-11 10:11:12 +00:00
|
|
|
@contextlib.contextmanager
|
|
|
|
|
def nullcontext():
|
|
|
|
|
"""Equivalent to contextlib.nullcontext(None) from Python 3.7."""
|
|
|
|
|
yield
|
2013-10-20 13:25:48 +00:00
|
|
|
|
2015-06-03 14:29:40 +00:00
|
|
|
|
2019-05-11 10:11:12 +00:00
|
|
|
class AuditlogMiddleware(object):
|
2013-10-20 13:25:48 +00:00
|
|
|
"""
|
|
|
|
|
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).
|
|
|
|
|
"""
|
|
|
|
|
|
2019-05-11 10:11:12 +00:00
|
|
|
def __init__(self, get_response=None):
|
|
|
|
|
self.get_response = get_response
|
|
|
|
|
|
|
|
|
|
def __call__(self, request):
|
2015-06-03 14:29:40 +00:00
|
|
|
|
2021-06-24 10:04:48 +00:00
|
|
|
if request.META.get("HTTP_X_FORWARDED_FOR"):
|
2019-05-11 10:11:12 +00:00
|
|
|
# In case of proxy, set 'original' address
|
2021-06-24 10:04:48 +00:00
|
|
|
remote_addr = request.META.get("HTTP_X_FORWARDED_FOR").split(",")[0]
|
2019-05-11 10:11:12 +00:00
|
|
|
else:
|
2021-06-24 10:04:48 +00:00
|
|
|
remote_addr = request.META.get("REMOTE_ADDR")
|
2015-06-03 14:29:40 +00:00
|
|
|
|
2021-06-24 10:04:48 +00:00
|
|
|
if hasattr(request, "user") and request.user.is_authenticated:
|
2019-05-11 10:11:12 +00:00
|
|
|
context = set_actor(actor=request.user, remote_addr=remote_addr)
|
|
|
|
|
else:
|
|
|
|
|
context = nullcontext()
|
2018-01-04 19:07:13 +00:00
|
|
|
|
2019-05-11 10:11:12 +00:00
|
|
|
with context:
|
|
|
|
|
return self.get_response(request)
|