This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
2019-12-05 13:33:55 +00:00
|
|
|
"""http helpers"""
|
|
|
|
from typing import Any, Dict, Optional
|
|
|
|
|
|
|
|
from django.http import HttpRequest
|
|
|
|
|
|
|
|
|
|
|
|
def _get_client_ip_from_meta(meta: Dict[str, Any]) -> Optional[str]:
|
|
|
|
"""Attempt to get the client's IP by checking common HTTP Headers.
|
|
|
|
Returns none if no IP Could be found"""
|
|
|
|
headers = (
|
2019-12-31 11:51:16 +00:00
|
|
|
"HTTP_X_FORWARDED_FOR",
|
|
|
|
"HTTP_X_REAL_IP",
|
|
|
|
"REMOTE_ADDR",
|
2019-12-05 13:33:55 +00:00
|
|
|
)
|
|
|
|
for _header in headers:
|
|
|
|
if _header in meta:
|
2020-09-20 11:36:23 +00:00
|
|
|
return meta.get(_header).split(", ")[0]
|
2019-12-05 13:33:55 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
2020-05-09 19:31:29 +00:00
|
|
|
def get_client_ip(request: Optional[HttpRequest]) -> Optional[str]:
|
2019-12-05 13:33:55 +00:00
|
|
|
"""Attempt to get the client's IP by checking common HTTP Headers.
|
|
|
|
Returns none if no IP Could be found"""
|
2020-05-09 19:31:29 +00:00
|
|
|
if request:
|
|
|
|
return _get_client_ip_from_meta(request.META)
|
2020-07-07 15:05:31 +00:00
|
|
|
return None
|