nova-api/api/helpers/network.py

46 lines
1.1 KiB
Python
Raw Normal View History

2023-08-30 20:55:31 +02:00
import os
import time
from dotenv import load_dotenv
load_dotenv()
2023-08-04 17:29:49 +02:00
2023-08-04 03:30:56 +02:00
async def get_ip(request) -> str:
2023-08-12 17:49:31 +02:00
"""Get the IP address of the incoming request."""
2023-08-05 02:30:42 +02:00
xff = None
if request.headers.get('x-forwarded-for'):
xff, *_ = request.headers['x-forwarded-for'].split(', ')
possible_ips = [
xff,
request.headers.get('cf-connecting-ip'),
request.client.host
]
detected_ip = next((i for i in possible_ips if i), None)
return detected_ip
2023-08-27 04:29:16 +02:00
2023-08-30 20:55:31 +02:00
def get_ratelimit_key(request) -> str:
2023-08-27 04:29:16 +02:00
"""Get the IP address of the incoming request."""
xff = None
if request.headers.get('x-forwarded-for'):
xff, *_ = request.headers['x-forwarded-for'].split(', ')
possible_ips = [
xff,
request.headers.get('cf-connecting-ip'),
request.client.host
]
detected_ip = next((i for i in possible_ips if i), None)
2023-08-30 20:55:31 +02:00
for whitelisted_ip in os.getenv('NO_RATELIMIT_IPS', '').split():
if whitelisted_ip in detected_ip:
custom_key = f'whitelisted-{time.time()}'
return custom_key
2023-08-27 04:29:16 +02:00
return detected_ip