baton/backend/middleware.py

48 lines
1.4 KiB
Python
Raw Permalink Normal View History

2026-03-20 20:44:00 +02:00
from __future__ import annotations
import secrets
import time
2026-03-20 23:39:28 +02:00
from typing import Optional
2026-03-20 23:39:28 +02:00
from fastapi import Depends, Header, HTTPException, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
2026-03-20 20:44:00 +02:00
from backend import config
2026-03-20 23:39:28 +02:00
_bearer = HTTPBearer(auto_error=False)
_RATE_LIMIT = 5
_RATE_WINDOW = 600 # 10 minutes
2026-03-20 20:44:00 +02:00
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
):
2026-03-20 20:44:00 +02:00
raise HTTPException(status_code=403, detail="Forbidden")
2026-03-20 23:39:28 +02:00
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")