NDOJ/judge/user_log.py

29 lines
1 KiB
Python
Raw Normal View History

2020-01-21 06:35:58 +00:00
from django.utils.timezone import now
2023-08-30 23:46:47 +00:00
from django.conf import settings
2024-01-14 00:52:11 +00:00
from django.core.cache import cache
2020-01-21 06:35:58 +00:00
from judge.models import Profile
class LogUserAccessMiddleware(object):
def __init__(self, get_response=None):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
2022-05-14 17:57:27 +00:00
if (
hasattr(request, "user")
and request.user.is_authenticated
and not getattr(request, "no_profile_update", False)
2024-01-14 00:52:11 +00:00
and not cache.get(f"user_log_update_{request.user.id}")
2022-05-14 17:57:27 +00:00
):
updates = {"last_access": now()}
2020-01-21 06:35:58 +00:00
# Decided on using REMOTE_ADDR as nginx will translate it to the external IP that hits it.
2023-08-30 23:46:47 +00:00
if request.META.get(settings.META_REMOTE_ADDRESS_KEY):
updates["ip"] = request.META.get(settings.META_REMOTE_ADDRESS_KEY)
2020-01-21 06:35:58 +00:00
Profile.objects.filter(user_id=request.user.pk).update(**updates)
2024-01-14 00:52:11 +00:00
cache.set(f"user_log_update_{request.user.id}", True, 120)
2020-01-21 06:35:58 +00:00
return response