ifixkart-backend/app/core/limiter.py

46 lines
1.5 KiB
Python

import os
from slowapi import Limiter
from starlette.requests import Request
from app.core.config.Config import settings
def get_real_client_ip(request: Request) -> str:
"""
Extracts the true client IP address, safely prioritizing X-Forwarded-For
and X-Real-IP headers set by upstream trusted reverse proxies (e.g. Nginx).
"""
forwarded_for = request.headers.get("x-forwarded-for") or request.headers.get("X-Forwarded-For")
if forwarded_for:
client_ip = forwarded_for.split(",")[0].strip()
if client_ip:
return client_ip
real_ip = request.headers.get("x-real-ip") or request.headers.get("X-Real-IP")
if real_ip:
return real_ip.strip()
if request.client and request.client.host:
return request.client.host
return "127.0.0.1"
# Shared Redis storage backend for SlowAPI across all multi-worker processes
# Uses DB index 1 to keep rate limit keys separate from general cache (DB 0)
redis_rate_limit_url = os.getenv("RATE_LIMIT_REDIS_URL", "redis://127.0.0.1:6379/1")
try:
import redis
_r = redis.from_url(redis_rate_limit_url, socket_connect_timeout=1)
_r.ping()
_storage_uri = redis_rate_limit_url
except Exception:
_storage_uri = "memory://"
limiter = Limiter(
key_func=get_real_client_ip,
default_limits=["120/minute"],
storage_uri=_storage_uri
)
# A local swarm originates from one IP. Rate limits are a production protection,
# not part of the journey under test, so disable them only in simulation mode.
if settings.SIMULATION_MODE:
limiter.enabled = False