114 lines
5.0 KiB
Python
114 lines
5.0 KiB
Python
"""按当前配置放行跨域请求的中间件:改了跨域来源不用重启。
|
||
|
||
Starlette 自带的 ``CORSMiddleware`` 在装上去的那一刻就把允许的来源列表定死了,
|
||
而本项目要求「所有运行配置都存在库里、界面上保存即生效」。这里换一个现读现判的
|
||
轻量实现:
|
||
|
||
* 每个请求现场问一次 :func:`app.dbconfig.value`,界面上刚加的域名马上就能用;
|
||
* 本机 ``localhost`` / ``127.0.0.1`` 的任意端口始终放行,前端起在哪个端口都行;
|
||
* 预检请求(``OPTIONS`` + ``Access-Control-Request-Method``)直接在本中间件里答掉,
|
||
不进路由 —— SPA 的兜底路由只收 GET/HEAD,不放行的话预检会撞上 405;
|
||
* 带 cookie 的跨域(``credentials``)照旧允许,``Content-Disposition`` 仍然暴露给
|
||
前端,下载文件名不会被吃掉。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
|
||
from starlette.datastructures import Headers, MutableHeaders
|
||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||
|
||
#: 本机的任意端口始终允许,省得开发时来回配
|
||
LOCAL_ORIGIN = re.compile(r"^http://(localhost|127\.0\.0\.1)(:\d{1,5})?$")
|
||
|
||
#: 预检结果缓存多久(秒):浏览器在这段时间内不用再问一次
|
||
PREFLIGHT_MAX_AGE = "600"
|
||
|
||
|
||
class LiveCORSMiddleware:
|
||
"""每次请求都按当前生效的 ``cors_origins`` 判断,改完配置立刻生效。"""
|
||
|
||
def __init__(
|
||
self,
|
||
app: ASGIApp,
|
||
allow_credentials: bool = True,
|
||
allow_methods: tuple[str, ...] = ("*",),
|
||
allow_headers: tuple[str, ...] = ("*",),
|
||
expose_headers: tuple[str, ...] = ("Content-Disposition",),
|
||
) -> None:
|
||
self.app = app
|
||
self.allow_credentials = allow_credentials
|
||
self.allow_methods = allow_methods
|
||
self.allow_headers = allow_headers
|
||
self.expose_headers = expose_headers
|
||
|
||
# -- 判定 --------------------------------------------------------------
|
||
def allowed(self, origin: str) -> bool:
|
||
from . import dbconfig
|
||
|
||
configured = dbconfig.value("cors_origins") or ()
|
||
if any(str(item).strip() == "*" for item in configured):
|
||
return True
|
||
if origin in {str(item).strip().rstrip("/") for item in configured}:
|
||
return True
|
||
return bool(LOCAL_ORIGIN.match(origin))
|
||
|
||
def _base_headers(self, origin: str) -> dict[str, str]:
|
||
headers = {"access-control-allow-origin": origin, "vary": "Origin"}
|
||
if self.allow_credentials:
|
||
headers["access-control-allow-credentials"] = "true"
|
||
return headers
|
||
|
||
# -- ASGI --------------------------------------------------------------
|
||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||
if scope["type"] != "http":
|
||
await self.app(scope, receive, send)
|
||
return
|
||
headers = Headers(scope=scope)
|
||
origin = headers.get("origin", "").strip()
|
||
if not origin or not self.allowed(origin):
|
||
await self.app(scope, receive, send)
|
||
return
|
||
|
||
if str(scope.get("method", "")).upper() == "OPTIONS" and "access-control-request-method" in headers:
|
||
await self._preflight(origin, headers, send)
|
||
return
|
||
|
||
async def send_wrapper(message: Message) -> None:
|
||
if message["type"] == "http.response.start":
|
||
out = MutableHeaders(scope=message)
|
||
for name, value in self._base_headers(origin).items():
|
||
if name == "vary":
|
||
existing = out.get("vary", "")
|
||
out["vary"] = existing if "Origin" in existing else f"{existing}, Origin".strip(", ")
|
||
else:
|
||
out[name] = value
|
||
if self.expose_headers:
|
||
out.append("access-control-expose-headers", ", ".join(self.expose_headers))
|
||
await send(message)
|
||
|
||
await self.app(scope, receive, send_wrapper)
|
||
|
||
async def _preflight(self, origin: str, headers: Headers, send: Send) -> None:
|
||
requested = headers.get("access-control-request-method", "*")
|
||
requested_headers = headers.get("access-control-request-headers", "")
|
||
out = self._base_headers(origin)
|
||
out["access-control-allow-methods"] = "*".join(self.allow_methods) if "*" in self.allow_methods else requested
|
||
if "*" in self.allow_headers:
|
||
out["access-control-allow-headers"] = "*"
|
||
else:
|
||
out["access-control-allow-headers"] = requested_headers or ",".join(self.allow_headers)
|
||
out["access-control-max-age"] = PREFLIGHT_MAX_AGE
|
||
body = b""
|
||
raw = b"".join(f"{name}: {value}\r\n".encode("latin-1") for name, value in out.items())
|
||
await send(
|
||
{
|
||
"type": "http.response.start",
|
||
"status": 204,
|
||
"headers": [(name.lower().encode("latin-1"), value.encode("latin-1")) for name, value in out.items()],
|
||
}
|
||
)
|
||
await send({"type": "http.response.body", "body": body})
|
||
del raw # 仅为说明这里不需要额外 body
|