fix latin-1 errors

This commit is contained in:
Mateusz Gruszczyński
2025-10-24 20:13:54 +02:00
parent 2aee79e94e
commit c2eb7c765d
2 changed files with 17 additions and 15 deletions

View File

@@ -3,10 +3,13 @@ from fastapi.security import HTTPBasic, HTTPBasicCredentials
from .deps import get_geo
from .config import settings
from .geo import reload_provider
from urllib.parse import quote
import secrets
import ipaddress
import re
import json
import unicodedata
router = APIRouter()
security = HTTPBasic()
@@ -37,6 +40,14 @@ def _check_admin(creds: HTTPBasicCredentials):
return True
def _safe_hdr(v: str) -> str:
try:
v.encode("latin-1")
return v
except UnicodeEncodeError:
return unicodedata.normalize("NFKD", v).encode("ascii", "ignore").decode("ascii") or "?"
def _normalize_ip_str(ip_raw: str) -> str | None:
"""Usuń port, whitespace i ewentualne cudzysłowy"""
if not ip_raw:
@@ -82,13 +93,12 @@ def geo_headers(data: dict) -> dict:
city = data.get("city")
ip_val = data.get("ip")
if ip_val and country:
h["X-IP-ADDRESS"] = ip_val
h["X-COUNTRY"] = country
h["X-IP-ADDRESS"] = _safe_hdr(str(ip_val))
h["X-COUNTRY"] = _safe_hdr(str(country))
if city:
h["X-CITY"] = city
h["X-CITY"] = _safe_hdr(str(city))
return h
def get_client_ip(request: Request) -> str:
"""
Zwraca IP klienta biorąc pod uwagę: