|
5 | 5 | from starlette.middleware.base import BaseHTTPMiddleware |
6 | 6 | from starlette.requests import Request |
7 | 7 | from starlette.responses import JSONResponse, Response |
| 8 | +from starlette.types import ASGIApp, Scope, Receive, Send |
8 | 9 |
|
9 | 10 | from backend.constants import DATABASE_URL, DOCS_PASSWORD, MONGO_DATABASE |
10 | 11 |
|
11 | 12 |
|
12 | | -class DatabaseMiddleware(BaseHTTPMiddleware): |
13 | | - async def dispatch(self, request: Request, call_next: t.Callable) -> Response: |
| 13 | +class DatabaseMiddleware: |
| 14 | + |
| 15 | + def __init__(self, app: ASGIApp) -> None: |
| 16 | + self._app = app |
| 17 | + |
| 18 | + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
14 | 19 | client: AsyncIOMotorClient = AsyncIOMotorClient( |
15 | 20 | DATABASE_URL, |
16 | 21 | ssl_cert_reqs=ssl.CERT_NONE |
17 | 22 | ) |
18 | 23 | db = client[MONGO_DATABASE] |
19 | | - request.state.db = db |
20 | | - response = await call_next(request) |
21 | | - return response |
| 24 | + scope["state"].db = db |
| 25 | + await self._app(scope, send, receive) |
| 26 | + |
22 | 27 |
|
| 28 | +class ProtectedDocsMiddleware: |
23 | 29 |
|
24 | | -class ProtectedDocsMiddleware(BaseHTTPMiddleware): |
25 | | - async def dispatch(self, request: Request, call_next: t.Callable) -> Response: |
| 30 | + def __init__(self, app: ASGIApp) -> None: |
| 31 | + self._app = app |
| 32 | + |
| 33 | + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
| 34 | + request = Request(scope) |
26 | 35 | if DOCS_PASSWORD and request.url.path.startswith("/docs"): |
27 | 36 | if request.cookies.get("docs_password") != DOCS_PASSWORD: |
28 | | - return JSONResponse({"status": "unauthorized"}, status_code=403) |
29 | | - |
30 | | - resp = await call_next(request) |
31 | | - return resp |
| 37 | + await JSONResponse({"status": "unauthorized"}, status_code=403)(scope, receive, send) |
| 38 | + return |
| 39 | + await self._app(scope, receive, send) |
0 commit comments