Improve docs and security defaults
This commit is contained in:
@@ -46,21 +46,33 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
path = request.url.path or ""
|
||||
|
||||
# Apply rate limiting to auth endpoints that accept credentials
|
||||
if path in ("/api/auth/login", "/api/auth/setup") and request.method.upper() == "POST":
|
||||
if (
|
||||
path in ("/api/auth/login", "/api/auth/setup")
|
||||
and request.method.upper() == "POST"
|
||||
):
|
||||
client_host = self._get_client_ip(request)
|
||||
rec = self._rate.setdefault(client_host, {"count": 0, "window_start": time.time()})
|
||||
rate_limit_record = self._rate.setdefault(
|
||||
client_host,
|
||||
{"count": 0, "window_start": time.time()},
|
||||
)
|
||||
now = time.time()
|
||||
if now - rec["window_start"] > self.window_seconds:
|
||||
# reset window
|
||||
rec["window_start"] = now
|
||||
rec["count"] = 0
|
||||
# The limiter uses a fixed window; once the window expires, we
|
||||
# reset the counter for that client and start measuring again.
|
||||
if now - rate_limit_record["window_start"] > self.window_seconds:
|
||||
rate_limit_record["window_start"] = now
|
||||
rate_limit_record["count"] = 0
|
||||
|
||||
rec["count"] += 1
|
||||
if rec["count"] > self.rate_limit_per_minute:
|
||||
rate_limit_record["count"] += 1
|
||||
if rate_limit_record["count"] > self.rate_limit_per_minute:
|
||||
# Too many requests in window — return a JSON 429 response
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
content={"detail": "Too many authentication attempts, try again later"},
|
||||
content={
|
||||
"detail": (
|
||||
"Too many authentication attempts, "
|
||||
"try again later"
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
# If Authorization header present try to decode token and attach session
|
||||
|
||||
Reference in New Issue
Block a user