diff --git a/PRODUCT.md b/PRODUCT.md index 65279f8..aa490d0 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -32,7 +32,7 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和 - 管理功能:首页运行面板查看大数据账号池指标(总数、新增、有效、失效、未退出)。选择登录方式,管理用户,管理大数据账号池,设置凭证刷新间隔和并行数量,手动添加账号。大数据账号池里的账号只有用户级别,不能设为管理员。并行数量范围是 1 到 32,采集和导出共用。调大后马上多领任务。调小后不中断正在运行的任务,等它们结束后再降到新的数量。用户管理可为用户角色改密;管理员账号只能由本人修改。 - 登录先看账号名。账号名与本系统管理员一致时,只校验本系统密码,不处理图形验证码,也不交给大数据平台。密码不正确就停在这里。 - 其余账号只启用一种登录方式。大数据平台登录时,登录页直接显示图形验证码,登录失败后更换验证码;登录成功后该账号进入账号池。自有账号由管理员添加,不能自行注册,登录不显示验证码,也不发送手机验证码。 -- 托管到 Metrix 时不使用本地密码登录。管理员是 Metrix 里有本应用管理员角色的账号,从「管理员登录」进入平台登录页后再进管理端。直接打开本系统登录页时显示用户登录,不自动使用当前平台身份。登录方式为自有账号时,自有账号就是有本应用用户角色的 Metrix 账号,由平台维护,管理导航没有「用户」;没登录平台先去平台登录页,登录了但没有角色显示「无权使用」。登录方式为大数据平台时,普通用户仍走原有 NQI 登录流程,账号进入账号池,不写入 Metrix。托管页面支持 `/apps/decomeval/` 子路径,侧栏底部有「返回平台」。退出账号回到本系统用户登录页。 +- 托管到 Metrix 时,用户入口只用本系统账号。登录方式为自有账号时,用户用本系统用户账号登录,管理员可以维护这些账号。登录方式为大数据平台时,普通用户仍走验证码和短信,账号进入账号池,不写入 Metrix。管理入口只认 Metrix 应用管理员,从应用托管进入,用户登录页没有管理员登录。管理页可以返回应用托管。退出用户账号回到本系统登录页。 - Metrix 应用包内含接口与排队进程使用的容器镜像,并声明持久数据目录。数据库连接由应用自己的环境变量配置。接口与排队进程可同时启动,应用会等待数据库并自动完成安装,不显示安装页。 - 操作结果用 toast 提示。最短显示 2.5 秒;超过 6 个字后,每多一个字加 0.3 秒;最长 8 秒。每条可以单独关闭。 - 平台登录使用 JWT。账号池另行保存大数据平台凭证。退出只清除平台登录,不删除账号池中的账号。退出后再次登录需要重新发送手机验证码,成功后账号池改用新凭证。 diff --git a/README.md b/README.md index c7ed1c2..f93aad1 100644 --- a/README.md +++ b/README.md @@ -67,9 +67,8 @@ backend\.venv\Scripts\python.exe scripts\package_metrix.py --npm-registry https: 登录: -- 管理员:在 Metrix 里给账号分配本应用的管理员角色,从平台登录后直接进入管理后台。托管时没有本地管理员密码。 -- 自有账号登录时:自有账号就是 Metrix 里有本应用用户角色的账号,由平台维护,管理后台不再有「用户」页。没有登录平台时先跳到平台登录页;登录了但没有角色时显示「无权使用」。 -- 大数据平台账号登录时:登录页照常使用大数据平台账号,成功后进入账号池,不写入 Metrix。登录卡片下方的「管理员登录」跳到平台登录页。 -- 侧栏底部的「返回平台」回到 Metrix 首页。退出账号回到 DecomEval 用户登录页。 +- 用户入口 `/apps/decomeval/` 使用本系统自己的账号。登录方式为自有账号时,管理员在管理页维护这些用户;登录方式为大数据平台时,登录页使用验证码和短信,成功后进入账号池。 +- 管理入口只认 Metrix 的应用管理员,从应用托管的「管理」进入 `/apps/decomeval/admin/`。用户登录页没有管理员登录。 +- 管理页侧栏是「返回应用托管」。用户页不显示返回平台。退出用户账号回到本系统登录页。 -应用用 `public` 访问方式,大数据平台用户不需要 Metrix 账号。 +应用清单里用户账号来源是 `app`,管理账号来源是 `metrix`。大数据平台用户不需要 Metrix 账号。 diff --git a/backend/app/api/deps.py b/backend/app/api/deps.py index ad574aa..f135529 100644 --- a/backend/app/api/deps.py +++ b/backend/app/api/deps.py @@ -31,16 +31,8 @@ def current_actor(request: Request, authorization: str | None = Header(default=N 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: + if identity is None or identity.user_id != actor.id or identity.role != actor.role or actor.role != "admin": 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: diff --git a/backend/app/api/http.py b/backend/app/api/http.py index 61cb5ee..642a0c2 100644 --- a/backend/app/api/http.py +++ b/backend/app/api/http.py @@ -103,18 +103,19 @@ def platform_login(request: Request, session: Session = db_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) + if identity.role != "admin": + 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 - if _setting(session).login_mode == "local" or user.role == "admin": + mode = _setting(session).login_mode + if hosted(): + return user if mode == "local" and user.role == "user" else None + if mode == "local" or user.role == "admin": return user return None @@ -133,7 +134,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("请从平台登录" if hosted() else "账号或密码不正确") + raise _bad("账号或密码不正确") if str(body.get("sessionId") or ""): return await nqi_finish(body) started = await nqi_start({"username": username, "purpose": "login"}) @@ -144,14 +145,12 @@ async def login(body: dict) -> dict: @router.post("/auth/local") def local_login(body: dict, session: Session = db_session) -> dict: - if hosted(): - raise _bad("请从平台登录") if _setting(session).login_mode != "local": raise _bad("当前使用大数据平台账号登录") username = str(body.get("username") or "").strip() password = str(body.get("password") or "") user = session.scalar(select(User).where(User.username == username)) - if user is None or not verify_password(password, user.password_hash): + if user is None or not verify_password(password, user.password_hash) or (hosted() and user.role != "user"): raise _bad("账号或密码不正确") return _token_for("local", str(user.id), user.role, user.username) @@ -373,15 +372,15 @@ def update_settings(body: dict, actor: Actor = Depends(current_actor), session: } -def _require_local_users() -> None: - if hosted(): - raise _bad("自有账号由平台管理", 404) +def _require_local_users(session: Session) -> None: + if _setting(session).login_mode != "local": + raise _bad("当前使用大数据平台账号登录", 404) @router.get("/admin/users") def list_users(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: require_admin(actor) - _require_local_users() + _require_local_users(session) 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]} @@ -389,10 +388,10 @@ def list_users(actor: Actor = Depends(current_actor), session: Session = db_sess @router.post("/admin/users") def create_user(body: dict, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: require_admin(actor) - _require_local_users() + _require_local_users(session) username = str(body.get("username") or "").strip() password = str(body.get("password") or "") - role = "admin" if body.get("role") == "admin" else "user" + role = "user" if hosted() else ("admin" if body.get("role") == "admin" else "user") if not username or not password: raise _bad("请填写账号和密码") if session.scalar(select(User).where(User.username == username)) is not None: @@ -404,7 +403,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 = db_session) -> dict: require_admin(actor) - _require_local_users() + _require_local_users(session) user = session.get(User, user_id) if user is None: raise _bad("账号不存在", 404) @@ -417,7 +416,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 = db_session) -> dict: require_admin(actor) - _require_local_users() + _require_local_users(session) user = session.get(User, user_id) if user is None: raise _bad("账号不存在", 404) diff --git a/backend/tests/test_hosting.py b/backend/tests/test_hosting.py index 0684a6d..d690b10 100644 --- a/backend/tests/test_hosting.py +++ b/backend/tests/test_hosting.py @@ -11,6 +11,8 @@ from fastapi.testclient import TestClient TEST_DATA = Path(os.environ["DECOM_DATA_DIR"]) +from sqlalchemy import select # noqa: E402 + from app.auth.platform import base_href, platform_identity # noqa: E402 from app.db import reset_engine, session_scope # noqa: E402 from app.main import create_app # noqa: E402 @@ -163,8 +165,8 @@ def test_platform_login_three_cases(hosted: TestClient): assert admin.json()["user"] == {"kind": "platform", "id": "a-1", "role": "admin", "name": "管理员甲"} user = hosted.post("/api/auth/platform", headers=identity("user")) - assert user.status_code == 200 - assert user.json()["user"] == {"kind": "platform", "id": "u-1", "role": "user", "name": "张三"} + assert user.status_code == 403 + assert user.json()["detail"] == "请从应用托管进入管理" saved = hosted.put( "/api/admin/settings", @@ -174,7 +176,7 @@ def test_platform_login_three_cases(hosted: TestClient): assert saved.status_code == 200 refused = hosted.post("/api/auth/platform", headers=identity("user")) assert refused.status_code == 403 - assert refused.json()["detail"] == "当前使用大数据平台账号登录" + assert refused.json()["detail"] == "请从应用托管进入管理" still_admin = hosted.post("/api/auth/platform", headers=identity("admin", user_id="a-1")) assert still_admin.status_code == 200 @@ -208,20 +210,23 @@ def test_local_password_login_closed_when_hosted(hosted: TestClient): with session_scope() as session: session.add(User(username="admin", password_hash=hash_password("admin-pass"), role="admin")) session.add(User(username="worker", password_hash=hash_password("worker-pass"), role="user")) - for username, password in (("admin", "admin-pass"), ("worker", "worker-pass")): - local = hosted.post("/api/auth/local", json={"username": username, "password": password}) - assert local.status_code == 400 - assert local.json()["detail"] == "请从平台登录" - combined = hosted.post("/api/auth/login", json={"username": username, "password": password}) - assert combined.status_code == 400 - assert combined.json()["detail"] == "请从平台登录" + for path in ("/api/auth/local", "/api/auth/login"): + blocked = hosted.post(path, json={"username": "admin", "password": "admin-pass"}) + assert blocked.status_code == 400 + assert blocked.json()["detail"] == "账号或密码不正确" + allowed = hosted.post("/api/auth/login", json={"username": "worker", "password": "worker-pass"}) + assert allowed.status_code == 200 + assert allowed.json()["user"]["role"] == "user" admin_headers = identity("admin", user_id="a-1", username="boss", display="管理员甲") headers = bearer(admin_token(hosted), admin_headers) - assert hosted.get("/api/admin/users", headers=headers).status_code == 404 - assert hosted.post("/api/admin/users", json={"username": "x", "password": "y"}, headers=headers).status_code == 404 - assert hosted.put("/api/admin/users/1/password", json={"password": "z"}, headers=headers).status_code == 404 - assert hosted.delete("/api/admin/users/1", headers=headers).status_code == 404 + listed = hosted.get("/api/admin/users", headers=headers) + assert listed.status_code == 200 + created = hosted.post("/api/admin/users", json={"username": "new", "password": "new-pass", "role": "admin"}, headers=headers) + assert created.status_code == 200 + with session_scope() as session: + created_user = session.scalar(select(User).where(User.username == "new")) + assert created_user is not None and created_user.role == "user" def test_nqi_admin_name_goes_to_platform_when_hosted(hosted: TestClient, monkeypatch): @@ -272,15 +277,19 @@ def test_switch_to_local_needs_no_local_admin_when_hosted(hosted: TestClient): assert back.json()["loginMode"] == "local" -def test_platform_user_runs_export(hosted: TestClient): - from app.models import ExportTask +def test_local_user_runs_export(hosted: TestClient): + from app.models import ExportTask, User + from app.security import hash_password - user_headers = identity("user") - login = hosted.post("/api/auth/platform", headers=user_headers) - headers = bearer(login.json()["token"], user_headers) + with session_scope() as session: + session.add(User(username="worker", password_hash=hash_password("worker-pass"), role="user")) + session.add(User(username="other", password_hash=hash_password("other-pass"), role="user")) + login = hosted.post("/api/auth/login", json={"username": "worker", "password": "worker-pass"}) + headers = bearer(login.json()["token"]) created = hosted.post("/api/tasks", json={"format": "csv", "cellKey": ""}, headers=headers) assert created.status_code == 200 task_id = created.json()["task"]["id"] + listing = [] for _ in range(30): listing = hosted.get("/api/tasks", headers=headers).json()["tasks"] if listing[0]["status"] == "done": @@ -289,12 +298,12 @@ def test_platform_user_runs_export(hosted: TestClient): assert listing[0]["status"] == "done" with session_scope() as session: task = session.get(ExportTask, task_id) - assert (task.owner_kind, task.owner_id) == ("platform", "u-1") + owner = session.scalar(select(User).where(User.username == "worker")) + assert (task.owner_kind, task.owner_id) == ("local", str(owner.id)) downloaded = hosted.get(f"/api/tasks/{task_id}/file", headers=headers) assert downloaded.status_code == 200 - other = identity("user", user_id="u-2") - other_login = hosted.post("/api/auth/platform", headers=other) - assert hosted.get(f"/api/tasks/{task_id}/file", headers=bearer(other_login.json()["token"], other)).status_code == 404 + other_login = hosted.post("/api/auth/login", json={"username": "other", "password": "other-pass"}) + assert hosted.get(f"/api/tasks/{task_id}/file", headers=bearer(other_login.json()["token"])).status_code == 404 admin_headers = identity("admin", user_id="a-1") assert hosted.get("/api/tasks", headers=bearer(admin_token(hosted), admin_headers)).status_code == 403 diff --git a/scripts/package_metrix.py b/scripts/package_metrix.py index e550eb2..71af094 100644 --- a/scripts/package_metrix.py +++ b/scripts/package_metrix.py @@ -44,26 +44,25 @@ def version() -> str: return f"{base}-{commit}-dirty" if dirty else f"{base}-{commit}" -def manifest(image: str) -> dict: +def manifest(image: str, release: str) -> dict: return { - "schema": 1, + "schema": 2, "slug": SLUG, "name": NAME, - "type": "container", - "image": image, - "image_file": "image.tar", + "version": release, + "user_auth": "app", + "admin_auth": "metrix", + "admin_path": "/admin", "services": [ - {"name": "web", "command": "", "port": WEB_PORT}, - {"name": "worker", "command": "python -m worker.main"}, + {"name": "web", "image": image, "image_file": "image.tar", "command": "", "port": WEB_PORT}, + {"name": "worker", "image": image, "image_file": "image.tar", "command": "python -m worker.main"}, ], - "postgres": {"enabled": False, "image": "postgres:16"}, "data_dir": DATA_DIR, "env": { "DECOM_DATA_DIR": DATA_DIR, "DECOM_INLINE_WORKER": "0", "DECOM_DB_WAIT_SECONDS": "180", }, - "access": "public", } @@ -86,14 +85,14 @@ def build_image(image: str, args: argparse.Namespace) -> None: _run(command) -def write_bundle(image: str, target: Path) -> None: +def write_bundle(image: str, release: str, target: Path) -> None: target.parent.mkdir(parents=True, exist_ok=True) partial = target.with_name(target.name + ".partial") with tempfile.TemporaryDirectory(prefix="decomeval-pack-", dir=target.parent) as work: tar = Path(work) / "image.tar" _run(["docker", "save", "-o", str(tar), image]) with zipfile.ZipFile(partial, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as bundle: - bundle.writestr("metrix-app.json", json.dumps(manifest(image), ensure_ascii=False, indent=2) + "\n") + bundle.writestr("metrix-app.json", json.dumps(manifest(image, release), ensure_ascii=False, indent=2) + "\n") bundle.write(tar, "image.tar") os.replace(partial, target) @@ -116,7 +115,7 @@ def main() -> int: if not args.skip_build: build_image(image, args) target = Path(args.output).resolve() / f"{SLUG}-{current}.zip" - write_bundle(image, target) + write_bundle(image, current, target) size = target.stat().st_size print(f"应用包:{target}") print(f"大小:{size / 1024 / 1024:.1f} MB({size} 字节)") diff --git a/web/src/features/admin/SettingsView.vue b/web/src/features/admin/SettingsView.vue index 52e74f4..d327b0b 100644 --- a/web/src/features/admin/SettingsView.vue +++ b/web/src/features/admin/SettingsView.vue @@ -15,7 +15,7 @@ const concurrency = ref(4); const saving = ref(false); const loaded = ref(false); const modeHint = hosted - ? "自有账号由平台管理,用户用平台账号直接进入。大数据平台登录会显示图形验证码,失败后换一张。管理员始终从平台进入。" + ? "自有账号由本系统管理。大数据平台登录会显示图形验证码,失败后换一张。管理页面从应用托管进入。" : "自有账号登录不显示验证码。大数据平台登录会显示图形验证码,失败后换一张。管理员始终只校验本系统密码。"; function askMode(next: string) { @@ -23,8 +23,8 @@ function askMode(next: string) { const toPlatform = next === "nqi"; const content = hosted ? toPlatform - ? "换成大数据平台账号后,用户在登录页用大数据平台账号登录,会显示图形验证码。管理员仍从平台进入。" - : "换成自有账号后,用户用平台账号直接进入,账号由平台管理。" + ? "换成大数据平台账号后,用户在登录页用大数据平台账号登录,会显示图形验证码。" + : "换成自有账号后,用户用本系统账号登录。管理员可以在这里维护这些账号。" : toPlatform ? "换成大数据平台账号后,登录页会显示图形验证码,登录失败会换一张。管理员仍只校验本系统密码。" : "换成自有账号后,登录页不再显示验证码。"; diff --git a/web/src/features/admin/UsersView.vue b/web/src/features/admin/UsersView.vue index cdcffd7..5651912 100644 --- a/web/src/features/admin/UsersView.vue +++ b/web/src/features/admin/UsersView.vue @@ -5,6 +5,7 @@ import type { DropdownOption } from "naive-ui"; import { EllipsisVerticalOutline } from "@vicons/ionicons5"; import Shell from "../../shell/Shell.vue"; import { api, sessionInfo } from "../../shared/http"; +import { hosted } from "../../shared/installState"; import { useToast } from "../../shared/toast"; interface User { id: number; username: string; role: string } @@ -149,7 +150,7 @@ onMounted(load);
-
+
diff --git a/web/src/features/auth/DeniedView.vue b/web/src/features/auth/DeniedView.vue index 8b6acad..d99626e 100644 --- a/web/src/features/auth/DeniedView.vue +++ b/web/src/features/auth/DeniedView.vue @@ -1,7 +1,5 @@ @@ -13,11 +11,10 @@ import ThemeButton from "../../shell/ThemeButton.vue";

DecomEval

-

无权使用

-

当前平台账号没有使用 DecomEval 的权限。请联系平台管理员开通,或换一个有权限的账号登录。

+

请从应用托管进入管理

+

管理页面不在这里登录。请回到应用托管,使用「管理」进入。

- 重新登录 - 返回平台 + 返回应用托管
diff --git a/web/src/features/auth/LoginView.vue b/web/src/features/auth/LoginView.vue index 266d63c..769316d 100644 --- a/web/src/features/auth/LoginView.vue +++ b/web/src/features/auth/LoginView.vue @@ -2,9 +2,7 @@ import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue"; import { useRoute, useRouter } from "vue-router"; import { NButton, NInput, NModal, NSpin } from "naive-ui"; -import { basePath, platformLoginUrl } from "../../shared/base"; import { api, saveSession } from "../../shared/http"; -import { hosted } from "../../shared/installState"; import { useToast } from "../../shared/toast"; import ThemeButton from "../../shell/ThemeButton.vue"; import "./login-gate.css"; @@ -15,7 +13,6 @@ const emit = defineEmits<{ done: [] }>(); const route = useRoute(); const router = useRouter(); const toast = useToast(); -const adminLoginUrl = platformLoginUrl(basePath, true); const mode = ref("local"); const username = ref(""); const password = ref(""); @@ -375,7 +372,6 @@ async function finishNqi() { - 管理员登录