from __future__ import annotations import secrets import time from typing import Optional from fastapi import Depends, Header, HTTPException, Request from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from backend import config _bearer = HTTPBearer(auto_error=False) _RATE_LIMIT = 5 _RATE_WINDOW = 600 # 10 minutes async def verify_webhook_secret( x_telegram_bot_api_secret_token: str = Header(default=""), ) -> None: if not secrets.compare_digest( x_telegram_bot_api_secret_token, config.WEBHOOK_SECRET ): raise HTTPException(status_code=403, detail="Forbidden") async def verify_admin_token( credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer), ) -> None: if credentials is None or not secrets.compare_digest( credentials.credentials, config.ADMIN_TOKEN ): raise HTTPException(status_code=401, detail="Unauthorized") async def rate_limit_register(request: Request) -> None: counters = request.app.state.rate_counters client_ip = request.client.host if request.client else "unknown" now = time.time() count, window_start = counters.get(client_ip, (0, now)) if now - window_start >= _RATE_WINDOW: count = 0 window_start = now count += 1 counters[client_ip] = (count, window_start) if count > _RATE_LIMIT: raise HTTPException(status_code=429, detail="Too Many Requests")