voice-changer/server/restapi/mods/trustedorigin.py

44 lines
1.4 KiB
Python
Raw Normal View History

2024-03-18 23:52:22 +03:00
from typing import Optional, Sequence, Literal
2024-03-17 01:11:16 +03:00
2024-03-18 23:52:22 +03:00
from mods.origins import compute_local_origins, normalize_origins
2024-03-17 01:11:16 +03:00
from starlette.datastructures import Headers
from starlette.responses import PlainTextResponse
from starlette.types import ASGIApp, Receive, Scope, Send
class TrustedOriginMiddleware:
def __init__(
self,
app: ASGIApp,
2024-03-18 23:52:22 +03:00
allowed_origins: Optional[Sequence[str]] = None,
port: Optional[int] = None,
2024-03-17 01:11:16 +03:00
) -> None:
self.allowed_origins: set[str] = set()
2024-03-18 23:52:22 +03:00
local_origins = compute_local_origins(port)
self.allowed_origins.update(local_origins)
2024-03-18 23:52:22 +03:00
if allowed_origins is not None:
normalized_origins = normalize_origins(allowed_origins)
self.allowed_origins.update(normalized_origins)
2024-03-17 01:11:16 +03:00
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in (
"http",
"websocket",
): # pragma: no cover
await self.app(scope, receive, send)
return
headers = Headers(scope=scope)
origin = headers.get("origin", "")
# Origin header is not present for same origin
if not origin or origin in self.allowed_origins:
await self.app(scope, receive, send)
return
response = PlainTextResponse("Invalid origin header", status_code=400)
await response(scope, receive, send)