Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace BaseHTTPMiddleware with pure ASGI middleware #173

Merged
merged 5 commits into from
Jun 18, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions backend/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,35 @@
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.types import ASGIApp, Scope, Receive, Send

from backend.constants import DATABASE_URL, DOCS_PASSWORD, MONGO_DATABASE


class DatabaseMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: t.Callable) -> Response:
class DatabaseMiddleware:

def __init__(self, app: ASGIApp) -> None:
self._app = app

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
client: AsyncIOMotorClient = AsyncIOMotorClient(
DATABASE_URL,
ssl_cert_reqs=ssl.CERT_NONE
)
db = client[MONGO_DATABASE]
request.state.db = db
response = await call_next(request)
return response
scope["state"].db = db
HassanAbouelela marked this conversation as resolved.
Show resolved Hide resolved
await self._app(scope, send, receive)
adriangb marked this conversation as resolved.
Show resolved Hide resolved


class ProtectedDocsMiddleware:

class ProtectedDocsMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: t.Callable) -> Response:
def __init__(self, app: ASGIApp) -> None:
self._app = app

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope)
if DOCS_PASSWORD and request.url.path.startswith("/docs"):
if request.cookies.get("docs_password") != DOCS_PASSWORD:
return JSONResponse({"status": "unauthorized"}, status_code=403)

resp = await call_next(request)
return resp
await JSONResponse({"status": "unauthorized"}, status_code=403)(scope, receive, send)
return
await self._app(scope, receive, send)