Middleware
Middleware are pieces of code that are executed every time a request is made to the app. It is used to do pre-validations and, in our case, add global values as props to each frontend render. The audit middleware is:
AuditUrlMiddleware
Captures the urls visited by the user and values necessary to record the urls log, according to the defined strategy.
class AuditUrlMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
response = self.get_response(request)
route = resolve(request.path).route
if request.user.is_authenticated:
user = request.user
else:
user = None
path = request.path
method = request.method
try:
params = request.body.decode("utf-8")
except RawPostDataException:
params = ""
user_agent = get_device(request)
ip = get_ip(request)
strategy = models.AuditSettings.load().urls_log_strategy
if strategy == models.AuditSettings.EVERYTHING:
models.AuditUrlLog.create_url_log(
path, method, params, user_agent, ip, user
)
elif strategy == models.AuditSettings.ONLY_WHITELIST:
if bool(models.UrlListLog.objects.filter(path=route, is_active=True)):
models.AuditUrlLog.create_url_log(
path, method, params, user_agent, ip, user
)
elif strategy == models.AuditSettings.EXCEPT_WHITELIST:
if not bool(models.UrlListLog.objects.filter(path=route, is_active=True)):
models.AuditUrlLog.create_url_log(
path, method, params, user_agent, ip, user
)
return response