feat: 后端支持托管到 Metrix,启动自动安装并接入平台登录
This commit is contained in:
+22
-3
@@ -2,8 +2,9 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
from fastapi import Header, HTTPException, Request
|
||||
|
||||
from app.auth.platform import platform_identity
|
||||
from app.security import read_token
|
||||
|
||||
|
||||
@@ -15,13 +16,31 @@ class Actor:
|
||||
name: str
|
||||
|
||||
|
||||
def current_actor(authorization: str | None = Header(default=None)) -> Actor:
|
||||
def current_actor(request: Request, authorization: str | None = Header(default=None)) -> Actor:
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise HTTPException(status_code=401, detail="请先登录")
|
||||
body = read_token(authorization.split(" ", 1)[1].strip())
|
||||
if body is None:
|
||||
raise HTTPException(status_code=401, detail="登录已失效")
|
||||
return Actor(str(body.get("kind") or ""), str(body.get("id") or ""), str(body.get("role") or "user"), str(body.get("name") or ""))
|
||||
actor = Actor(str(body.get("kind") or ""), str(body.get("id") or ""), str(body.get("role") or "user"), str(body.get("name") or ""))
|
||||
if actor.kind == "platform":
|
||||
_check_platform(request, actor)
|
||||
return actor
|
||||
|
||||
|
||||
def _check_platform(request: Request, actor: Actor) -> None:
|
||||
"""平台账号的令牌跟随平台登录:换人、退出或角色变化后即失效。"""
|
||||
identity = platform_identity(request.headers)
|
||||
if identity is None or identity.user_id != actor.id or identity.role != actor.role:
|
||||
raise HTTPException(status_code=401, detail="平台登录已变化,请重新进入")
|
||||
if actor.role == "user":
|
||||
from app.db import session_scope
|
||||
from app.models import AppSetting
|
||||
|
||||
with session_scope() as session:
|
||||
setting = session.get(AppSetting, 1)
|
||||
if setting is not None and setting.login_mode != "local":
|
||||
raise HTTPException(status_code=401, detail="当前使用大数据平台账号登录")
|
||||
|
||||
|
||||
def require_admin(actor: Actor) -> None:
|
||||
|
||||
+35
-10
@@ -1,16 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import Actor, current_actor, require_admin
|
||||
from app.config import installed, result_dir
|
||||
from app.auth.platform import platform_identity
|
||||
from app.config import env_database, hosted, installed, result_dir
|
||||
from app.install import InstallError, perform_install
|
||||
from app.db import get_session, session_scope
|
||||
from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow
|
||||
@@ -24,13 +24,15 @@ router = APIRouter(prefix="/api")
|
||||
|
||||
@router.get("/install/status")
|
||||
def install_status() -> dict:
|
||||
db = env_database()
|
||||
return {
|
||||
"installed": installed(),
|
||||
"hosted": hosted(),
|
||||
"defaults": {
|
||||
"host": os.environ.get("DECOM_DB_HOST", "127.0.0.1"),
|
||||
"port": int(os.environ.get("DECOM_DB_PORT", "5432")),
|
||||
"database": os.environ.get("DECOM_DB_NAME", "decom"),
|
||||
"username": os.environ.get("DECOM_DB_USER", "postgres"),
|
||||
"host": db["host"] or "127.0.0.1",
|
||||
"port": db["port"] or 5432,
|
||||
"database": db["database"] or "decom",
|
||||
"username": db["username"] or "postgres",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -91,10 +93,22 @@ def _public_source(source: CollectionSource) -> dict:
|
||||
|
||||
@router.get("/auth/mode")
|
||||
def auth_mode(session: Session = Depends(get_session)) -> dict:
|
||||
return {"mode": _setting(session).login_mode}
|
||||
return {"mode": _setting(session).login_mode, "hosted": hosted()}
|
||||
|
||||
|
||||
@router.post("/auth/platform")
|
||||
def platform_login(request: Request, session: Session = Depends(get_session)) -> dict:
|
||||
identity = platform_identity(request.headers)
|
||||
if identity is None:
|
||||
raise _bad("没有平台登录", 401)
|
||||
if identity.role == "user" and _setting(session).login_mode != "local":
|
||||
raise _bad("当前使用大数据平台账号登录", 403)
|
||||
return _token_for("platform", identity.user_id, identity.role, identity.name)
|
||||
|
||||
|
||||
def _matched_local_user(session: Session, username: str) -> User | None:
|
||||
if hosted():
|
||||
return None
|
||||
user = session.scalar(select(User).where(User.username == username))
|
||||
if user is None:
|
||||
return None
|
||||
@@ -117,7 +131,7 @@ async def login(body: dict) -> dict:
|
||||
return _token_for("local", str(user.id), user.role, user.username)
|
||||
mode = _setting(session).login_mode
|
||||
if mode != "nqi":
|
||||
raise _bad("账号或密码不正确")
|
||||
raise _bad("请从平台登录" if hosted() else "账号或密码不正确")
|
||||
if str(body.get("sessionId") or ""):
|
||||
return await nqi_finish(body)
|
||||
started = await nqi_start({"username": username, "purpose": "login"})
|
||||
@@ -128,6 +142,8 @@ async def login(body: dict) -> dict:
|
||||
|
||||
@router.post("/auth/local")
|
||||
def local_login(body: dict, session: Session = Depends(get_session)) -> dict:
|
||||
if hosted():
|
||||
raise _bad("请从平台登录")
|
||||
if _setting(session).login_mode != "local":
|
||||
raise _bad("当前使用大数据平台账号登录")
|
||||
username = str(body.get("username") or "").strip()
|
||||
@@ -335,7 +351,7 @@ def update_settings(body: dict, actor: Actor = Depends(current_actor), session:
|
||||
mode = str(body.get("loginMode") or setting.login_mode)
|
||||
if mode not in {"local", "nqi"}:
|
||||
raise _bad("登录方式不正确")
|
||||
if mode == "local" and session.scalar(select(User).where(User.role == "admin")) is None:
|
||||
if mode == "local" and not hosted() and session.scalar(select(User).where(User.role == "admin")) is None:
|
||||
raise _bad("还没有自有账号管理员,不能切换")
|
||||
if "credentialRefreshSeconds" in body:
|
||||
try:
|
||||
@@ -355,9 +371,15 @@ def update_settings(body: dict, actor: Actor = Depends(current_actor), session:
|
||||
}
|
||||
|
||||
|
||||
def _require_local_users() -> None:
|
||||
if hosted():
|
||||
raise _bad("自有账号由平台管理", 404)
|
||||
|
||||
|
||||
@router.get("/admin/users")
|
||||
def list_users(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
_require_local_users()
|
||||
rows = session.scalars(select(User).order_by(User.id)).all()
|
||||
return {"users": [{"id": row.id, "username": row.username, "role": row.role} for row in rows]}
|
||||
|
||||
@@ -365,6 +387,7 @@ def list_users(actor: Actor = Depends(current_actor), session: Session = Depends
|
||||
@router.post("/admin/users")
|
||||
def create_user(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
_require_local_users()
|
||||
username = str(body.get("username") or "").strip()
|
||||
password = str(body.get("password") or "")
|
||||
role = "admin" if body.get("role") == "admin" else "user"
|
||||
@@ -379,6 +402,7 @@ def create_user(body: dict, actor: Actor = Depends(current_actor), session: Sess
|
||||
@router.delete("/admin/users/{user_id}")
|
||||
def delete_user(user_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
_require_local_users()
|
||||
user = session.get(User, user_id)
|
||||
if user is None:
|
||||
raise _bad("账号不存在", 404)
|
||||
@@ -391,6 +415,7 @@ def delete_user(user_id: int, actor: Actor = Depends(current_actor), session: Se
|
||||
@router.put("/admin/users/{user_id}/password")
|
||||
def update_user_password(user_id: int, body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
_require_local_users()
|
||||
user = session.get(User, user_id)
|
||||
if user is None:
|
||||
raise _bad("账号不存在", 404)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""托管到 Metrix 时,由平台代理带来的登录身份。
|
||||
|
||||
只有请求带的代理令牌与 METRIX_APP_PROXY_TOKEN 一致时,才相信 X-Metrix-* 身份头。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Mapping
|
||||
from urllib.parse import unquote
|
||||
|
||||
from app.config import proxy_token
|
||||
|
||||
PREFIX_PATTERN = re.compile(r"^/apps/[a-z0-9-]+$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PlatformIdentity:
|
||||
user_id: str
|
||||
username: str
|
||||
display_name: str
|
||||
role: str
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self.display_name or self.username or self.user_id
|
||||
|
||||
|
||||
def from_proxy(headers: Mapping[str, str]) -> bool:
|
||||
expected = proxy_token()
|
||||
if not expected:
|
||||
return False
|
||||
given = headers.get("x-metrix-proxy-token") or ""
|
||||
return hmac.compare_digest(given.encode("utf-8"), expected.encode("utf-8"))
|
||||
|
||||
|
||||
def platform_identity(headers: Mapping[str, str]) -> PlatformIdentity | None:
|
||||
if not from_proxy(headers):
|
||||
return None
|
||||
user_id = (headers.get("x-metrix-user-id") or "").strip()
|
||||
role = (headers.get("x-metrix-app-role") or "").strip().lower()
|
||||
if not user_id or role not in {"admin", "user"}:
|
||||
return None
|
||||
username = (headers.get("x-metrix-username") or "").strip()
|
||||
display_name = unquote(headers.get("x-metrix-display-name") or "", encoding="utf-8", errors="replace").strip()
|
||||
return PlatformIdentity(user_id=user_id, username=username, display_name=display_name, role=role)
|
||||
|
||||
|
||||
def base_href(headers: Mapping[str, str]) -> str:
|
||||
prefix = (headers.get("x-forwarded-prefix") or "").strip()
|
||||
if PREFIX_PATTERN.match(prefix):
|
||||
return prefix + "/"
|
||||
return "/"
|
||||
@@ -1,26 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from sqlalchemy import create_engine, pool, text
|
||||
|
||||
from app.config import BACKEND_ROOT, data_dir, installed
|
||||
from app.config import BACKEND_ROOT, data_dir, database_url, installed
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
INSTALL_LOCK = 7_316_501_842
|
||||
|
||||
|
||||
def migrate() -> None:
|
||||
@contextmanager
|
||||
def _install_lock() -> Iterator[None]:
|
||||
"""接口和排队进程可能同时启动,建表和初始化依次进行。"""
|
||||
url = database_url()
|
||||
if not url.startswith("postgresql"):
|
||||
yield
|
||||
return
|
||||
engine = create_engine(url, poolclass=pool.NullPool, isolation_level="AUTOCOMMIT")
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT pg_advisory_lock(:key)"), {"key": INSTALL_LOCK})
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
connection.execute(text("SELECT pg_advisory_unlock(:key)"), {"key": INSTALL_LOCK})
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _ensure_queue_schema() -> None:
|
||||
from app.config import postgres_conninfo
|
||||
|
||||
conninfo = postgres_conninfo()
|
||||
if not conninfo:
|
||||
return
|
||||
import psycopg
|
||||
from procrastinate.schema import SchemaManager
|
||||
|
||||
with psycopg.connect(conninfo) as connection:
|
||||
exists = connection.execute("SELECT to_regclass('procrastinate_jobs')").fetchone()
|
||||
if exists and exists[0]:
|
||||
return
|
||||
connection.execute(SchemaManager.get_schema())
|
||||
logger.info("已建立排队表")
|
||||
|
||||
|
||||
def migrate(then: Callable[[], None] | None = None) -> None:
|
||||
data_dir().mkdir(parents=True, exist_ok=True)
|
||||
config = Config(str(Path(BACKEND_ROOT) / "alembic.ini"))
|
||||
config.set_main_option("script_location", str(Path(BACKEND_ROOT) / "alembic"))
|
||||
config.attributes["configure_logger"] = False
|
||||
command.upgrade(config, "head")
|
||||
with _install_lock():
|
||||
command.upgrade(config, "head")
|
||||
_ensure_queue_schema()
|
||||
if then is not None:
|
||||
then()
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
def init_db() -> bool:
|
||||
"""准备数据库。返回数据库是否已可用。"""
|
||||
from app.install import auto_install
|
||||
|
||||
if auto_install():
|
||||
return True
|
||||
if not installed():
|
||||
logger.info("尚未安装,等待安装页")
|
||||
return
|
||||
return False
|
||||
migrate()
|
||||
return True
|
||||
|
||||
+67
-2
@@ -1,4 +1,7 @@
|
||||
"""运行配置。连接信息在安装后写入 data/install.json,其余配置保存在数据库。"""
|
||||
"""运行配置。连接信息在安装后写入 data/install.json,其余配置保存在数据库。
|
||||
|
||||
托管到 Metrix 时,平台注入的 METRIX_* 变量作为 DECOM_* 缺省时的回退。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -9,8 +12,24 @@ from pathlib import Path
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _env(*names: str) -> str:
|
||||
for name in names:
|
||||
value = os.environ.get(name, "").strip()
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def hosted() -> bool:
|
||||
return bool(proxy_token())
|
||||
|
||||
|
||||
def proxy_token() -> str:
|
||||
return os.environ.get("METRIX_APP_PROXY_TOKEN", "").strip()
|
||||
|
||||
|
||||
def data_dir() -> Path:
|
||||
override = os.environ.get("DECOM_DATA_DIR", "").strip()
|
||||
override = _env("DECOM_DATA_DIR", "METRIX_APP_DATA_DIR")
|
||||
if override:
|
||||
return Path(override)
|
||||
return BACKEND_ROOT / "data"
|
||||
@@ -44,3 +63,49 @@ def postgres_conninfo() -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def env_database() -> dict:
|
||||
"""环境变量里的数据库连接。缺的项为空,端口缺省 5432。"""
|
||||
url_parts: dict = {}
|
||||
raw_url = _env("METRIX_PG_URL")
|
||||
if raw_url:
|
||||
try:
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
parsed = make_url(raw_url)
|
||||
url_parts = {
|
||||
"host": parsed.host or "",
|
||||
"port": parsed.port or 0,
|
||||
"database": parsed.database or "",
|
||||
"username": parsed.username or "",
|
||||
"password": parsed.password or "",
|
||||
}
|
||||
except Exception:
|
||||
url_parts = {}
|
||||
port_text = _env("DECOM_DB_PORT", "METRIX_PG_PORT")
|
||||
try:
|
||||
port = int(port_text) if port_text else int(url_parts.get("port") or 5432)
|
||||
except ValueError:
|
||||
port = 5432
|
||||
return {
|
||||
"host": _env("DECOM_DB_HOST", "METRIX_PG_HOST") or url_parts.get("host", ""),
|
||||
"port": port,
|
||||
"database": _env("DECOM_DB_NAME", "METRIX_PG_DATABASE") or url_parts.get("database", ""),
|
||||
"username": _env("DECOM_DB_USER", "METRIX_PG_USER") or url_parts.get("username", ""),
|
||||
"password": _env("DECOM_DB_PASSWORD", "METRIX_PG_PASSWORD") or url_parts.get("password", ""),
|
||||
}
|
||||
|
||||
|
||||
def env_database_complete() -> bool:
|
||||
db = env_database()
|
||||
return all(db[key] for key in ("host", "database", "username", "password"))
|
||||
|
||||
|
||||
def database_wait_seconds() -> int:
|
||||
try:
|
||||
return max(1, int(_env("DECOM_DB_WAIT_SECONDS") or "120"))
|
||||
except ValueError:
|
||||
return 120
|
||||
|
||||
|
||||
def inline_worker_allowed() -> bool:
|
||||
return _env("DECOM_INLINE_WORKER") != "0"
|
||||
|
||||
+107
-6
@@ -1,21 +1,27 @@
|
||||
"""首次安装:连接数据库、建表、创建管理员,并把配置写入数据库。"""
|
||||
"""首次安装:连接数据库、建表、创建管理员,并把配置写入数据库。
|
||||
|
||||
托管到 Metrix 且平台提供了数据库时,启动即自动安装,不经过安装页。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from sqlalchemy import create_engine, select, text
|
||||
from sqlalchemy.engine import URL
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.config import data_dir, install_file, installed
|
||||
from app.config import data_dir, database_wait_seconds, env_database, env_database_complete, hosted, install_file, installed
|
||||
from app.db import reset_engine, session_scope
|
||||
from app.models import AppSetting, User
|
||||
from app.security import hash_password
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")
|
||||
|
||||
|
||||
@@ -40,10 +46,24 @@ def build_postgres_url(host: str, port: int, database: str, username: str, passw
|
||||
).render_as_string(hide_password=False)
|
||||
|
||||
|
||||
def _can_connect(url: str) -> bool:
|
||||
engine = create_engine(url, connect_args={"connect_timeout": 5})
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def ensure_database(host: str, port: int, database: str, username: str, password: str) -> None:
|
||||
if _can_connect(build_postgres_url(host, port, database, username, password)):
|
||||
return
|
||||
maintenance = build_postgres_url(host, port, "postgres", username, password)
|
||||
try:
|
||||
checker = create_engine(maintenance, isolation_level="AUTOCOMMIT")
|
||||
checker = create_engine(maintenance, isolation_level="AUTOCOMMIT", connect_args={"connect_timeout": 5})
|
||||
with checker.connect() as connection:
|
||||
exists = connection.execute(
|
||||
text("SELECT 1 FROM pg_database WHERE datname = :name"),
|
||||
@@ -56,12 +76,93 @@ def ensure_database(host: str, port: int, database: str, username: str, password
|
||||
raise InstallError("无法连接数据库,请检查主机、端口、账号和密码") from exc
|
||||
|
||||
|
||||
def wait_for_database(host: str, port: int, database: str, username: str, password: str, timeout: int) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
attempt = 0
|
||||
while True:
|
||||
attempt += 1
|
||||
try:
|
||||
ensure_database(host, port, database, username, password)
|
||||
if attempt > 1:
|
||||
logger.info("数据库已就绪")
|
||||
return
|
||||
except InstallError as exc:
|
||||
if time.monotonic() >= deadline:
|
||||
raise InstallError(f"等待数据库 {host}:{port}/{database} 超过 {timeout} 秒") from exc
|
||||
if attempt == 1 or attempt % 10 == 0:
|
||||
logger.info("等待数据库 %s:%s/%s 就绪", host, port, database)
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def _write_install(url: str) -> None:
|
||||
content = json.dumps({"databaseUrl": url}, ensure_ascii=False)
|
||||
target = install_file()
|
||||
if target.is_file() and target.read_text(encoding="utf-8") == content:
|
||||
return
|
||||
staging = target.with_name(f"{target.name}.{os.getpid()}.tmp")
|
||||
staging.write_text(content, encoding="utf-8")
|
||||
os.replace(staging, target)
|
||||
|
||||
|
||||
def hosted_database_url() -> str | None:
|
||||
if not env_database_complete():
|
||||
return None
|
||||
db = env_database()
|
||||
return build_postgres_url(db["host"], db["port"], db["database"], db["username"], db["password"])
|
||||
|
||||
|
||||
def _ensure_setting(host: str, port: int, database: str, username: str, password: str) -> bool:
|
||||
with session_scope() as session:
|
||||
setting = session.get(AppSetting, 1)
|
||||
if setting is not None:
|
||||
if not setting.jwt_secret:
|
||||
setting.jwt_secret = secrets.token_hex(32)
|
||||
return True
|
||||
session.add(
|
||||
AppSetting(
|
||||
id=1,
|
||||
login_mode="local",
|
||||
credential_refresh_seconds=300,
|
||||
worker_concurrency=4,
|
||||
db_host=host,
|
||||
db_port=port,
|
||||
db_name=database,
|
||||
db_user=username,
|
||||
db_password=password,
|
||||
jwt_secret=secrets.token_hex(32),
|
||||
)
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def auto_install() -> bool:
|
||||
"""托管模式下按平台提供的数据库完成安装。API 和排队进程同时启动也只会装一次。"""
|
||||
if not hosted():
|
||||
return False
|
||||
url = hosted_database_url()
|
||||
if url is None:
|
||||
return False
|
||||
db = env_database()
|
||||
if url.startswith("postgresql"):
|
||||
wait_for_database(db["host"], db["port"], db["database"], db["username"], db["password"], database_wait_seconds())
|
||||
data_dir().mkdir(parents=True, exist_ok=True)
|
||||
_write_install(url)
|
||||
reset_engine()
|
||||
from app.bootstrap import migrate
|
||||
|
||||
already: list[bool] = []
|
||||
migrate(then=lambda: already.append(_ensure_setting(db["host"], db["port"], db["database"], db["username"], db["password"])))
|
||||
logger.info("托管安装已就绪" if already and already[0] else "托管安装已完成")
|
||||
return True
|
||||
|
||||
|
||||
def perform_install(body: dict) -> bool:
|
||||
if installed():
|
||||
raise InstallError("已经安装")
|
||||
admin_username = str(body.get("adminUsername") or "").strip()
|
||||
admin_password = str(body.get("adminPassword") or "")
|
||||
if not admin_username or not admin_password:
|
||||
with_admin = not hosted()
|
||||
if with_admin and (not admin_username or not admin_password):
|
||||
raise InstallError("请填写管理员账号和密码")
|
||||
use_sqlite = bool(body.get("sqlite"))
|
||||
data_dir().mkdir(parents=True, exist_ok=True)
|
||||
@@ -83,7 +184,7 @@ def perform_install(body: dict) -> bool:
|
||||
raise InstallError("请填写完整的数据库连接")
|
||||
ensure_database(host, port, database, username, password)
|
||||
url = build_postgres_url(host, port, database, username, password)
|
||||
install_file().write_text(json.dumps({"databaseUrl": url}, ensure_ascii=False), encoding="utf-8")
|
||||
_write_install(url)
|
||||
reset_engine()
|
||||
try:
|
||||
from app.bootstrap import migrate
|
||||
@@ -106,7 +207,7 @@ def perform_install(body: dict) -> bool:
|
||||
jwt_secret=secrets.token_hex(32),
|
||||
)
|
||||
)
|
||||
if session.scalar(select(User).where(User.username == admin_username)) is None:
|
||||
if with_admin and session.scalar(select(User).where(User.username == admin_username)) is None:
|
||||
session.add(User(username=admin_username, password_hash=hash_password(admin_password), role="admin"))
|
||||
return already
|
||||
except IntegrityError as exc:
|
||||
|
||||
+31
-11
@@ -1,15 +1,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.api.http import router
|
||||
from app.auth.platform import base_href
|
||||
from app.bootstrap import init_db
|
||||
from app.config import installed
|
||||
|
||||
@@ -25,6 +27,7 @@ WEB_DIST = next(
|
||||
),
|
||||
Path(__file__).resolve().parents[2] / "web" / "dist",
|
||||
)
|
||||
BASE_TAG = re.compile(r"<base\b[^>]*>", re.IGNORECASE)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -33,10 +36,18 @@ async def lifespan(_application: FastAPI):
|
||||
yield
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
def render_index(html: str, href: str) -> str:
|
||||
tag = f'<base href="{href}" />'
|
||||
if BASE_TAG.search(html):
|
||||
return BASE_TAG.sub(tag, html, count=1)
|
||||
return html.replace("<head>", f"<head>\n {tag}", 1)
|
||||
|
||||
|
||||
def create_app(web_dist: Path | None = None) -> FastAPI:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
application = FastAPI(title="DecomEval", lifespan=lifespan)
|
||||
application.include_router(router)
|
||||
dist = (web_dist or WEB_DIST).resolve()
|
||||
|
||||
@application.middleware("http")
|
||||
async def require_install(request, call_next):
|
||||
@@ -45,17 +56,26 @@ def create_app() -> FastAPI:
|
||||
return JSONResponse({"detail": "尚未安装"}, status_code=503)
|
||||
return await call_next(request)
|
||||
|
||||
if (WEB_DIST / "index.html").is_file():
|
||||
application.mount("/assets", StaticFiles(directory=WEB_DIST / "assets"), name="assets")
|
||||
if (dist / "index.html").is_file():
|
||||
if (dist / "assets").is_dir():
|
||||
application.mount("/assets", StaticFiles(directory=dist / "assets"), name="assets")
|
||||
|
||||
@application.get("/{path:path}")
|
||||
def pages(path: str) -> FileResponse:
|
||||
def index(request: Request) -> HTMLResponse:
|
||||
html = (dist / "index.html").read_text(encoding="utf-8")
|
||||
return HTMLResponse(
|
||||
render_index(html, base_href(request.headers)),
|
||||
headers={"Cache-Control": "no-store", "Vary": "X-Forwarded-Prefix"},
|
||||
)
|
||||
|
||||
@application.get("/{path:path}", response_model=None)
|
||||
def pages(path: str, request: Request) -> FileResponse | HTMLResponse:
|
||||
if path == "api" or path.startswith("api/"):
|
||||
raise HTTPException(status_code=404, detail="接口不存在")
|
||||
target = WEB_DIST / path
|
||||
if path and target.is_file():
|
||||
return FileResponse(target)
|
||||
return FileResponse(WEB_DIST / "index.html")
|
||||
if path and path != "index.html":
|
||||
target = (dist / path).resolve()
|
||||
if target.is_file() and target.is_relative_to(dist):
|
||||
return FileResponse(target)
|
||||
return index(request)
|
||||
|
||||
return application
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ from sqlalchemy import select
|
||||
|
||||
from app.collect.io import parse_upload, write_table
|
||||
from app.collect.remote import fetch_ftp, fetch_nqi
|
||||
from app.config import postgres_conninfo, result_dir
|
||||
from app.config import inline_worker_allowed, postgres_conninfo, result_dir
|
||||
from app.db import session_scope
|
||||
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
@@ -204,13 +204,20 @@ def _fetch_nqi_sync(cookies: list, config: dict) -> tuple[str, bytes]:
|
||||
def enqueue_export(task_id: int) -> None:
|
||||
if _defer("decom_export", task_id=task_id):
|
||||
return
|
||||
threading.Thread(target=execute_export, args=(task_id,), daemon=True).start()
|
||||
_run_inline(execute_export, task_id)
|
||||
|
||||
|
||||
def enqueue_collection(source_id: int) -> None:
|
||||
if _defer("decom_collect", source_id=source_id):
|
||||
return
|
||||
threading.Thread(target=execute_collection, args=(source_id,), daemon=True).start()
|
||||
_run_inline(execute_collection, source_id)
|
||||
|
||||
|
||||
def _run_inline(target, item_id: int) -> None:
|
||||
if not inline_worker_allowed():
|
||||
logger.info("没有排队数据库,任务 %s 留在排队中", item_id)
|
||||
return
|
||||
threading.Thread(target=target, args=(item_id,), daemon=True).start()
|
||||
|
||||
|
||||
def _defer(name: str, **kwargs) -> bool:
|
||||
|
||||
Reference in New Issue
Block a user