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 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 21 additions & 15 deletions backend/middleware.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
import typing as t

import ssl
from motor.motor_asyncio import AsyncIOMotorClient
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.responses import JSONResponse
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(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: t.Callable) -> Response:
class ProtectedDocsMiddleware:

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
resp = JSONResponse({"status": "unauthorized"}, status_code=403)
await resp(scope, receive, send)
return
await self._app(scope, receive, send)