From 1c762e54447bb9fa92b1032289637dd7f39ff03c Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Thu, 27 Feb 2020 13:34:38 +0100 Subject: [PATCH] Trying to get IP --- apps/logs/signals.py | 51 +++++++++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/apps/logs/signals.py b/apps/logs/signals.py index 74392d18..b26da5c1 100644 --- a/apps/logs/signals.py +++ b/apps/logs/signals.py @@ -10,19 +10,23 @@ from django.dispatch import receiver from .models import Changelog -def get_user_in_signal(sender, **kwargs): - user = None +def get_request_in_signal(sender, **kwargs): + req = None for entry in reversed(inspect.stack()): try: - user = entry[0].f_locals['request'].user + req = entry[0].f_locals['request'] + # Check if there is a user + # noinspection PyStatementEffect + req.user break except: pass - if not user: + if not req: print("WARNING: Attempt to save " + str(sender) + " with no user") - return user + return req + EXCLUDED = [ 'changelog', @@ -40,12 +44,22 @@ def save_object(sender, instance, **kwargs): previous = sender.objects.filter(pk=instance.pk).all() - user = get_user_in_signal(sender, **kwargs) - if previous.exists: - previous_json = serializers.serialize('json', previous)[1:-1] - else: - previous_json = None - instance_json = serializers.serialize('json', [instance, ],)[1:-1] + req = get_request_in_signal(sender, **kwargs) + try: + user = req.user + if 'X-Real-Ip' in req.headers: + ip = req.headers.get('X-Real-Ip') + else: + ip = req.headers.get('REMOTE_ADDR') + print(ip) + print(req.headers) + except: + user = None + ip = None + + from rest_framework.renderers import JSONRenderer + previous_json = JSONRenderer().render(previous) + instance_json = JSONRenderer().render(instance) Changelog.objects.create(user=user, model=ContentType.objects.get_for_model(instance), instance_pk=instance.pk, @@ -54,13 +68,26 @@ def save_object(sender, instance, **kwargs): action=("edit" if previous.exists() else "create") )#.save() + @receiver(pre_delete) def delete_object(sender, instance, **kwargs): model_name = sender.__name__ if model_name.lower() in EXCLUDED: return - user = get_user_in_signal(sender, **kwargs) + req = get_request_in_signal(sender, **kwargs) + try: + user = req.user + if 'X-Real-Ip' in req.headers: + ip = req.headers.get('X-Real-Ip') + else: + ip = req.headers.get('REMOTE_ADDR') + print(ip) + print(req.headers) + except: + user = None + ip = None + instance_json = serializers.serialize('json', [instance, ])[1:-1] Changelog.objects.create(user=user, model=ContentType.objects.get_for_model(instance),