From 6aaa46e5a02c6a9400e89e0d7fe6ac1ca526933b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?dni=20=E2=9A=A1?= Date: Mon, 3 Jul 2023 11:25:00 +0200 Subject: [PATCH] Fix ip blocker 2nd try (#1796) * fix ipblock v2 fix ipblock 2nd try * remove sleep inside ip block dont ignore other exceptions typo * remove asyncio * Update lnbits/middleware.py --------- Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com> --- lnbits/middleware.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lnbits/middleware.py b/lnbits/middleware.py index 87dcc998..d6d4206d 100644 --- a/lnbits/middleware.py +++ b/lnbits/middleware.py @@ -2,7 +2,7 @@ from http import HTTPStatus from typing import Any, List, Tuple, Union from urllib.parse import parse_qs -from fastapi import FastAPI, Request +from fastapi import FastAPI, Request, Response from fastapi.responses import HTMLResponse, JSONResponse from slowapi import _rate_limit_exceeded_handler from slowapi.errors import RateLimitExceeded @@ -218,6 +218,14 @@ def add_ip_block_middleware(app: FastAPI): status_code=403, # Forbidden content={"detail": "IP is blocked"}, ) - return await call_next(request) + # this try: except: block is not needed on latest FastAPI (await call_next(request) is enough) + # https://stackoverflow.com/questions/71222144/runtimeerror-no-response-returned-in-fastapi-when-refresh-request + # TODO: remove after https://github.com/lnbits/lnbits/pull/1609 is merged + try: + return await call_next(request) + except RuntimeError as exc: + if str(exc) == "No response returned." and await request.is_disconnected(): + return Response(status_code=HTTPStatus.NO_CONTENT) + raise # bubble up different exceptions app.middleware("http")(block_allow_ip_middleware)