add get_client_ip util function

This commit is contained in:
Antoine Bartuccio 2024-07-22 09:49:08 +02:00
parent 03d15ddded
commit 58ff5b934a
2 changed files with 17 additions and 1 deletions

View File

@ -25,6 +25,7 @@ from typing import Optional
import PIL import PIL
from django.conf import settings from django.conf import settings
from django.core.files.base import ContentFile from django.core.files.base import ContentFile
from django.http import HttpRequest
from django.utils import timezone from django.utils import timezone
from PIL import ExifTags from PIL import ExifTags
from PIL.Image import Resampling from PIL.Image import Resampling
@ -297,3 +298,16 @@ def bbcode_to_markdown(text):
new_text.append(line) new_text.append(line)
return "\n".join(new_text) return "\n".join(new_text)
def get_client_ip(request: HttpRequest) -> str | None:
headers = (
"X_FORWARDED_FOR", # Common header for proixes
"FORWARDED", # Standard header defined by RFC 7239.
"REMOTE_ADDR", # Default IP Address (direct connection)
)
for header in headers:
if (ip := request.META.get(header)) is not None:
return ip
return None

View File

@ -4,12 +4,14 @@ from typing import Any
from django.http import HttpRequest, HttpResponse from django.http import HttpRequest, HttpResponse
from core.utils import get_client_ip
def custom_honeypot_error( def custom_honeypot_error(
request: HttpRequest, context: dict[str, Any] request: HttpRequest, context: dict[str, Any]
) -> HttpResponse: ) -> HttpResponse:
logging.warning( logging.warning(
f"[{strftime('%c', localtime())}] " f"[{strftime('%c', localtime())}] "
f"HoneyPot blocked user with ip {request.META.get('X-Forwarded-For')}" f"HoneyPot blocked user with ip {get_client_ip(request)}"
) )
return HttpResponse("Upon reading this, the http client was enlightened.") return HttpResponse("Upon reading this, the http client was enlightened.")