1
0
mirror of https://gitlab.crans.org/bde/nk20 synced 2024-12-23 07:52:23 +00:00

Trying to get IP

This commit is contained in:
Yohann D'ANELLO 2020-02-27 13:34:38 +01:00
parent 10854eb334
commit 1c762e5444

View File

@ -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),