feat: 支持托管到Metrix应用包并移除授权与平台模式
- 新增 scripts/package_metrix.py 打包应用包(user_auth=metrix、admin_auth=none、数据目录 /data) - 托管模式只认平台代理身份,停用应用登录与改密码,新增 /api/session - 后端按 X-Forwarded-Prefix 注入 <base href>,前端改为相对路径构建并按 basePath 请求 - 托管时隐藏登录页、退出按钮和修改密码页,顶栏显示 Metrix 用户名 - 移除授权到期校验、激活码和连点品牌图标打开的授权延期窗口 - 移除 Metrix 平台数据源/仓库模式及相关配置、接口、设置页和 requests 依赖 - 新增托管鉴权与 base href 注入测试,更新使用与开发文档
This commit is contained in:
+55
-19
@@ -1,12 +1,13 @@
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
|
||||
from app import state
|
||||
from app.api.routers import (
|
||||
@@ -18,13 +19,12 @@ from app.api.routers import (
|
||||
database,
|
||||
health,
|
||||
history,
|
||||
license,
|
||||
remote,
|
||||
script,
|
||||
tasks,
|
||||
upload,
|
||||
)
|
||||
from app.auth import resolve_access_context, resolve_login_context
|
||||
from app.auth import is_hosted, resolve_access_context, resolve_login_context, resolve_platform_context
|
||||
from app.config import BASE_DIR
|
||||
from app.services.auto_scheduler import AutoScheduler
|
||||
|
||||
@@ -34,11 +34,15 @@ APP_HOST = "0.0.0.0"
|
||||
APP_PORT = 9081
|
||||
# Code/frontend live in the image (/app); runtime state lives on the data volume (BASE_DIR=/data).
|
||||
FRONTEND_DIST_DIR = Path(os.environ.get("CAPAREPORT_FRONTEND_DIR") or (BASE_DIR / "frontend" / "dist"))
|
||||
OPEN_API_PATHS = {"/api/login", "/api/session"}
|
||||
LOGIN_ONLY_API_PREFIXES = (
|
||||
"/api/config",
|
||||
"/api/change-password",
|
||||
"/api/license",
|
||||
)
|
||||
# 托管后账号由 Metrix 管理,应用自己的登录与改密码接口停用。
|
||||
HOSTED_DISABLED_API_PATHS = {"/api/login", "/api/change-password"}
|
||||
FORWARDED_PREFIX_PATTERN = re.compile(r"^/apps/[a-z0-9-]+$")
|
||||
BASE_TAG_PATTERN = re.compile(r"<base\b[^>]*>", re.IGNORECASE)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -88,7 +92,13 @@ async def auth_middleware(request: Request, call_next):
|
||||
return await call_next(request)
|
||||
|
||||
path = request.url.path
|
||||
if path == "/api/login":
|
||||
if not path.startswith("/api/"):
|
||||
return await call_next(request)
|
||||
|
||||
if is_hosted():
|
||||
return await _hosted_auth(request, call_next, path)
|
||||
|
||||
if path in OPEN_API_PATHS:
|
||||
return await call_next(request)
|
||||
|
||||
if _is_login_only_api(path):
|
||||
@@ -96,13 +106,25 @@ async def auth_middleware(request: Request, call_next):
|
||||
return JSONResponse(status_code=401, content={"detail": "未登录或登录已过期"})
|
||||
return await call_next(request)
|
||||
|
||||
if path.startswith("/api/"):
|
||||
access_context = resolve_access_context(request)
|
||||
if access_context is None:
|
||||
return JSONResponse(status_code=401, content={"detail": "未授权,请提供有效的 Token"})
|
||||
access_context = resolve_access_context(request)
|
||||
if access_context is None:
|
||||
return JSONResponse(status_code=401, content={"detail": "未授权,请提供有效的 Token"})
|
||||
|
||||
request.state.auth_context = access_context
|
||||
request.state.auth_context = access_context
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
async def _hosted_auth(request: Request, call_next, path: str):
|
||||
if path in HOSTED_DISABLED_API_PATHS:
|
||||
return JSONResponse(status_code=404, content={"detail": "接口不存在"})
|
||||
if path == "/api/session":
|
||||
return await call_next(request)
|
||||
|
||||
platform_context = resolve_platform_context(request)
|
||||
if platform_context is None:
|
||||
return JSONResponse(status_code=401, content={"detail": "未授权,请从 Metrix 平台访问"})
|
||||
|
||||
request.state.auth_context = platform_context
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
@@ -114,7 +136,6 @@ def register_routes(app: FastAPI) -> None:
|
||||
remote.router,
|
||||
tasks.router,
|
||||
history.router,
|
||||
license.router,
|
||||
database.router,
|
||||
config.router,
|
||||
cache.router,
|
||||
@@ -129,30 +150,45 @@ def register_routes(app: FastAPI) -> None:
|
||||
def register_frontend(app: FastAPI) -> None:
|
||||
@app.get("/", include_in_schema=False)
|
||||
@app.get("/{path:path}", include_in_schema=False)
|
||||
async def serve_frontend(path: str = ""):
|
||||
async def serve_frontend(request: Request, path: str = ""):
|
||||
if path.startswith("api/"):
|
||||
raise HTTPException(status_code=404, detail="接口不存在")
|
||||
return _serve_frontend_path(path)
|
||||
return _serve_frontend_path(path, request.headers.get("x-forwarded-prefix", ""))
|
||||
|
||||
|
||||
def _serve_frontend_path(path: str):
|
||||
def _serve_frontend_path(path: str, forwarded_prefix: str = ""):
|
||||
if not FRONTEND_DIST_DIR.exists():
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={"detail": "前端构建产物不存在,请先执行 cd frontend && npm install && npm run build"},
|
||||
)
|
||||
|
||||
requested_file = _safe_file(FRONTEND_DIST_DIR, path)
|
||||
if requested_file and requested_file.exists() and requested_file.is_file():
|
||||
return FileResponse(str(requested_file))
|
||||
|
||||
index_file = FRONTEND_DIST_DIR / "index.html"
|
||||
requested_file = _safe_file(FRONTEND_DIST_DIR, path)
|
||||
if requested_file and requested_file.is_file() and requested_file != index_file.resolve():
|
||||
return FileResponse(str(requested_file))
|
||||
# 缺失的静态资源直接 404,不能回落成 index.html,否则浏览器会把 HTML 当脚本执行。
|
||||
if path.startswith("assets/"):
|
||||
raise HTTPException(status_code=404, detail="资源不存在")
|
||||
|
||||
if index_file.exists():
|
||||
return FileResponse(str(index_file))
|
||||
return _render_index(index_file, forwarded_prefix)
|
||||
|
||||
return JSONResponse(status_code=503, content={"detail": "前端入口文件不存在"})
|
||||
|
||||
|
||||
def _render_index(index_file: Path, forwarded_prefix: str) -> HTMLResponse:
|
||||
prefix = forwarded_prefix.strip()
|
||||
href = f"{prefix}/" if FORWARDED_PREFIX_PATTERN.match(prefix) else "/"
|
||||
tag = f'<base href="{href}" />'
|
||||
html = index_file.read_text(encoding="utf-8")
|
||||
if BASE_TAG_PATTERN.search(html):
|
||||
html = BASE_TAG_PATTERN.sub(tag, html, count=1)
|
||||
else:
|
||||
html = html.replace("<head>", f"<head>\n {tag}", 1)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-store", "Vary": "X-Forwarded-Prefix"})
|
||||
|
||||
|
||||
def _safe_file(root: Path, path: str) -> Path | None:
|
||||
if not path:
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user