nk20/apps/logs/middlewares.py

78 lines
2.3 KiB
Python
Raw Normal View History

# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
2020-03-11 16:20:16 +00:00
from threading import local
USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user')
IP_ATTR_NAME = getattr(settings, 'LOCAL_IP_ATTR_NAME', '_current_ip')
_thread_locals = local()
def _set_current_user_and_ip(user=None, ip=None):
2020-03-11 19:36:38 +00:00
"""
Store current user and IP address in the local thread.
"""
setattr(_thread_locals, USER_ATTR_NAME, user)
setattr(_thread_locals, IP_ATTR_NAME, ip)
def get_current_user():
2020-03-11 19:36:38 +00:00
"""
:return: The user that performed a request (may be anonymous)
"""
return getattr(_thread_locals, USER_ATTR_NAME, None)
def get_current_ip():
2020-03-11 19:36:38 +00:00
"""
:return: The IP address of the user that has performed a request
"""
return getattr(_thread_locals, IP_ATTR_NAME, None)
def get_current_authenticated_user():
2020-03-11 19:36:38 +00:00
"""
:return: The user that performed a request (must be authenticated, return None if anonymous)
"""
current_user = get_current_user()
if isinstance(current_user, AnonymousUser):
return None
return current_user
class LogsMiddleware(object):
"""
2020-03-11 19:36:38 +00:00
This middleware gets the current user with his or her IP address on each request.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
2020-03-11 19:36:38 +00:00
"""
This function is called on each request.
:param request: The HTTP Request
:return: The HTTP Response
"""
user = request.user
2020-03-11 19:36:38 +00:00
# Get request IP from the headers
# The `REMOTE_ADDR` field may not contain the true IP, if there is a proxy
if 'HTTP_X_FORWARDED_FOR' in request.META:
ip = request.META.get('HTTP_X_FORWARDED_FOR')
else:
ip = request.META.get('REMOTE_ADDR')
2020-03-11 19:36:38 +00:00
# The user and the IP address are stored in the current thread
_set_current_user_and_ip(user, ip)
2020-03-11 19:36:38 +00:00
# The request is then analysed, and the response is generated
response = self.get_response(request)
2020-03-11 19:36:38 +00:00
# We flush the connected user and the IP address for the next requests
_set_current_user_and_ip(None, None)
return response