feat: 用户入口改用自有账号,管理入口只从应用托管进入
This commit is contained in:
+1
-1
@@ -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。账号池另行保存大数据平台凭证。退出只清除平台登录,不删除账号池中的账号。退出后再次登录需要重新发送手机验证码,成功后账号池改用新凭证。
|
||||
|
||||
@@ -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 账号。
|
||||
|
||||
@@ -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:
|
||||
|
||||
+16
-17
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+11
-12
@@ -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} 字节)")
|
||||
|
||||
@@ -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
|
||||
? "换成大数据平台账号后,登录页会显示图形验证码,登录失败会换一张。管理员仍只校验本系统密码。"
|
||||
: "换成自有账号后,登录页不再显示验证码。";
|
||||
|
||||
@@ -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);
|
||||
<n-modal v-model:show="show" class="app-dialog" preset="dialog" :show-icon="false" title="添加用户" positive-text="保存" negative-text="取消" @positive-click="create">
|
||||
<div class="form-row"><label>账号</label><n-input v-model:value="username" /></div>
|
||||
<div class="form-row"><label>密码</label><n-input v-model:value="password" type="password" /></div>
|
||||
<div class="form-row"><label>角色</label><n-select v-model:value="role" :options="[{ label: '用户', value: 'user' }, { label: '管理员', value: 'admin' }]" /></div>
|
||||
<div v-if="!hosted" class="form-row"><label>角色</label><n-select v-model:value="role" :options="[{ label: '用户', value: 'user' }, { label: '管理员', value: 'admin' }]" /></div>
|
||||
</n-modal>
|
||||
<n-modal v-model:show="pwdShow" class="app-dialog" preset="dialog" :show-icon="false" :title="pwdUser ? `修改密码 · ${pwdUser.username}` : '修改密码'" positive-text="保存" negative-text="取消" @positive-click="savePassword">
|
||||
<div class="form-row"><label>新密码</label><n-input v-model:value="pwdNext" type="password" /></div>
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { NButton } from "naive-ui";
|
||||
import { basePath, platformHome } from "../../shared/base";
|
||||
import { goPlatformLogin } from "../../shared/platform";
|
||||
import ThemeButton from "../../shell/ThemeButton.vue";
|
||||
</script>
|
||||
|
||||
@@ -13,11 +11,10 @@ import ThemeButton from "../../shell/ThemeButton.vue";
|
||||
<div class="brand-mark" aria-hidden="true">D</div>
|
||||
<h1>DecomEval</h1>
|
||||
</div>
|
||||
<h2 id="denied-title" class="gate-title">无权使用</h2>
|
||||
<p class="gate-text">当前平台账号没有使用 DecomEval 的权限。请联系平台管理员开通,或换一个有权限的账号登录。</p>
|
||||
<h2 id="denied-title" class="gate-title">请从应用托管进入管理</h2>
|
||||
<p class="gate-text">管理页面不在这里登录。请回到应用托管,使用「管理」进入。</p>
|
||||
<div class="gate-actions">
|
||||
<n-button @click="goPlatformLogin(basePath, true)">重新登录</n-button>
|
||||
<n-button type="primary" tag="a" :href="platformHome">返回平台</n-button>
|
||||
<n-button type="primary" tag="a" href="/hosting">返回应用托管</n-button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -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() {
|
||||
</template>
|
||||
<button class="lv-go" type="submit" :disabled="busy">{{ busy ? "登录中" : "登录" }}</button>
|
||||
</form>
|
||||
<a v-if="hosted && mode === 'nqi'" class="lv-admin" :href="adminLoginUrl">管理员登录</a>
|
||||
</section>
|
||||
<n-modal v-model:show="smsRequired" :mask-closable="false" :auto-focus="false">
|
||||
<div class="lv-sms-sheet" role="dialog" aria-modal="true" aria-labelledby="sms-title">
|
||||
|
||||
+26
-32
@@ -4,7 +4,6 @@ window.addEventListener("error", (event) => {
|
||||
if (event.message?.includes("ResizeObserver loop")) event.stopImmediatePropagation();
|
||||
});
|
||||
import { createRouter, createWebHistory } from "vue-router";
|
||||
import type { RouteLocationNormalized, RouteLocationRaw } from "vue-router";
|
||||
import App from "./App.vue";
|
||||
import InstallView from "./features/install/InstallView.vue";
|
||||
import LoginView from "./features/auth/LoginView.vue";
|
||||
@@ -15,10 +14,10 @@ import SettingsView from "./features/admin/SettingsView.vue";
|
||||
import UsersView from "./features/admin/UsersView.vue";
|
||||
import PoolView from "./features/admin/PoolView.vue";
|
||||
import SourcesView from "./features/admin/SourcesView.vue";
|
||||
import { appUrl, basePath } from "./shared/base";
|
||||
import { onUnauthorized, sessionInfo, token } from "./shared/http";
|
||||
import { basePath } from "./shared/base";
|
||||
import { clearSession, onUnauthorized, sessionInfo, token, useSurface } from "./shared/http";
|
||||
import { hosted, installed, refreshInstalled } from "./shared/installState";
|
||||
import { goPlatformLogin, justBounced, loginMode, platformLogin } from "./shared/platform";
|
||||
import { loginMode, platformLogin } from "./shared/platform";
|
||||
import "./styles.css";
|
||||
|
||||
const router = createRouter({
|
||||
@@ -26,8 +25,8 @@ const router = createRouter({
|
||||
routes: [
|
||||
{ path: "/install", component: InstallView },
|
||||
{ path: "/login", component: LoginView },
|
||||
{ path: "/denied", component: DeniedView },
|
||||
{ path: "/", redirect: () => sessionInfo().role === "admin" ? "/admin" : "/tasks" },
|
||||
{ path: "/entry-denied", component: DeniedView },
|
||||
{ path: "/", redirect: () => (!hosted && sessionInfo("user").role === "admin" ? "/admin" : "/tasks") },
|
||||
{ path: "/tasks", component: TasksView, meta: { role: "user" } },
|
||||
{ path: "/admin", component: DashboardView, meta: { role: "admin" } },
|
||||
{ path: "/admin/users", component: UsersView, meta: { role: "admin", localUsers: true } },
|
||||
@@ -38,39 +37,28 @@ const router = createRouter({
|
||||
],
|
||||
});
|
||||
|
||||
function landing(to: RouteLocationNormalized): RouteLocationRaw | true {
|
||||
const role = sessionInfo().role;
|
||||
if (to.meta.role && to.meta.role === role && !(hosted && to.meta.localUsers)) return true;
|
||||
return role === "admin" ? "/admin" : "/tasks";
|
||||
}
|
||||
|
||||
async function enterFromPlatform(to: RouteLocationNormalized): Promise<RouteLocationRaw | boolean> {
|
||||
const outcome = await platformLogin();
|
||||
if (outcome === "ok") return landing(to);
|
||||
if (outcome === "none" && (await loginMode()) === "local") {
|
||||
if (justBounced()) return to.path === "/denied" ? true : "/denied";
|
||||
goPlatformLogin(to.meta.role && !to.redirectedFrom ? appUrl(to.fullPath) : basePath);
|
||||
return false;
|
||||
}
|
||||
return to.path === "/login" ? true : "/login";
|
||||
function isAdminRoute(path: string) {
|
||||
return path === "/admin" || path.startsWith("/admin/");
|
||||
}
|
||||
|
||||
router.beforeEach(async (to) => {
|
||||
if (installed === null) await refreshInstalled();
|
||||
if (!installed && to.path !== "/install") return "/install";
|
||||
if (installed && to.path === "/install") return "/login";
|
||||
if (to.path === "/install") return true;
|
||||
if (hosted && !token()) {
|
||||
if (to.path === "/login") return true;
|
||||
return enterFromPlatform(to);
|
||||
if (to.path === "/install" || to.path === "/entry-denied") return true;
|
||||
const adminRoute = isAdminRoute(to.path);
|
||||
useSurface(adminRoute ? "admin" : "user");
|
||||
if (to.path === "/login") return token("user") ? "/" : true;
|
||||
if (adminRoute) {
|
||||
if (!token("admin")) {
|
||||
if (!hosted) return "/login";
|
||||
if ((await platformLogin()) !== "ok") return "/entry-denied";
|
||||
}
|
||||
if (hosted && to.meta.localUsers && (await loginMode()) !== "local") return "/admin";
|
||||
return true;
|
||||
}
|
||||
if (to.path === "/denied") return token() ? "/" : "/login";
|
||||
if (to.path === "/login") return token() ? "/" : true;
|
||||
if (!token()) return "/login";
|
||||
const role = sessionInfo().role;
|
||||
if (to.meta.role === "admin" && role !== "admin") return "/tasks";
|
||||
if (to.meta.role === "user" && role === "admin") return "/admin";
|
||||
if (hosted && to.meta.localUsers) return "/admin";
|
||||
if (!token("user")) return "/login";
|
||||
if (!hosted && sessionInfo("user").role === "admin") return "/admin";
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -78,6 +66,12 @@ let reentries = 0;
|
||||
onUnauthorized(() => {
|
||||
reentries += 1;
|
||||
if (reentries > 3) return;
|
||||
if (hosted && isAdminRoute(router.currentRoute.value.path)) {
|
||||
clearSession("admin");
|
||||
void router.replace("/entry-denied");
|
||||
return;
|
||||
}
|
||||
clearSession("user");
|
||||
void router.replace("/login");
|
||||
});
|
||||
|
||||
|
||||
@@ -9,11 +9,3 @@ export const basePath = computeBase();
|
||||
export function appUrl(path: string) {
|
||||
return basePath + path.replace(/^\/+/, "");
|
||||
}
|
||||
|
||||
export const platformHome = "/";
|
||||
|
||||
/** switchAccount 让平台先退出当前账号再显示登录表单,否则已登录的平台账号会被直接送回来。 */
|
||||
export function platformLoginUrl(target = basePath, switchAccount = false) {
|
||||
const url = `/login?redirect=${encodeURIComponent(target)}`;
|
||||
return switchAccount ? `${url}&switch=1` : url;
|
||||
}
|
||||
|
||||
+49
-27
@@ -1,4 +1,5 @@
|
||||
import { appUrl } from "./base";
|
||||
import { hosted } from "./installState";
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
@@ -9,50 +10,71 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
const KEYS = {
|
||||
token: "decomeval.token",
|
||||
role: "decomeval.role",
|
||||
name: "decomeval.name",
|
||||
id: "decomeval.id",
|
||||
kind: "decomeval.kind",
|
||||
} as const;
|
||||
export type Surface = "user" | "admin";
|
||||
|
||||
const KEYS: Record<Surface, { token: string; role: string; name: string; id: string; kind: string }> = {
|
||||
user: {
|
||||
token: "decomeval.token",
|
||||
role: "decomeval.role",
|
||||
name: "decomeval.name",
|
||||
id: "decomeval.id",
|
||||
kind: "decomeval.kind",
|
||||
},
|
||||
admin: {
|
||||
token: "decomeval.admin.token",
|
||||
role: "decomeval.admin.role",
|
||||
name: "decomeval.admin.name",
|
||||
id: "decomeval.admin.id",
|
||||
kind: "decomeval.admin.kind",
|
||||
},
|
||||
};
|
||||
|
||||
let surface: Surface = "user";
|
||||
let unauthorized: (() => void) | null = null;
|
||||
|
||||
export function useSurface(value: Surface) {
|
||||
surface = value;
|
||||
}
|
||||
|
||||
export function onUnauthorized(handler: () => void) {
|
||||
unauthorized = handler;
|
||||
}
|
||||
|
||||
export function token() {
|
||||
return sessionStorage.getItem(KEYS.token) || "";
|
||||
function actual(target: Surface): Surface {
|
||||
return !hosted && target === "admin" ? "user" : target;
|
||||
}
|
||||
|
||||
export function setToken(value: string) {
|
||||
if (value) sessionStorage.setItem(KEYS.token, value);
|
||||
else sessionStorage.removeItem(KEYS.token);
|
||||
export function token(target: Surface = surface) {
|
||||
return sessionStorage.getItem(KEYS[actual(target)].token) || "";
|
||||
}
|
||||
|
||||
export function sessionInfo() {
|
||||
export function sessionInfo(target: Surface = surface) {
|
||||
const keys = KEYS[actual(target)];
|
||||
return {
|
||||
role: sessionStorage.getItem(KEYS.role) || "",
|
||||
name: sessionStorage.getItem(KEYS.name) || "",
|
||||
id: sessionStorage.getItem(KEYS.id) || "",
|
||||
kind: sessionStorage.getItem(KEYS.kind) || "",
|
||||
role: sessionStorage.getItem(keys.role) || "",
|
||||
name: sessionStorage.getItem(keys.name) || "",
|
||||
id: sessionStorage.getItem(keys.id) || "",
|
||||
kind: sessionStorage.getItem(keys.kind) || "",
|
||||
};
|
||||
}
|
||||
|
||||
export function saveSession(tokenValue: string, user: { role: string; name: string; id?: string; kind?: string }) {
|
||||
setToken(tokenValue);
|
||||
sessionStorage.setItem(KEYS.role, user.role);
|
||||
sessionStorage.setItem(KEYS.name, user.name);
|
||||
if (user.id) sessionStorage.setItem(KEYS.id, user.id);
|
||||
else sessionStorage.removeItem(KEYS.id);
|
||||
if (user.kind) sessionStorage.setItem(KEYS.kind, user.kind);
|
||||
else sessionStorage.removeItem(KEYS.kind);
|
||||
export function saveSession(
|
||||
tokenValue: string,
|
||||
user: { role: string; name: string; id?: string; kind?: string },
|
||||
target: Surface = surface,
|
||||
) {
|
||||
const keys = KEYS[target];
|
||||
sessionStorage.setItem(keys.token, tokenValue);
|
||||
sessionStorage.setItem(keys.role, user.role);
|
||||
sessionStorage.setItem(keys.name, user.name);
|
||||
if (user.id) sessionStorage.setItem(keys.id, user.id);
|
||||
else sessionStorage.removeItem(keys.id);
|
||||
if (user.kind) sessionStorage.setItem(keys.kind, user.kind);
|
||||
else sessionStorage.removeItem(keys.kind);
|
||||
}
|
||||
|
||||
export function clearSession() {
|
||||
for (const key of Object.values(KEYS)) sessionStorage.removeItem(key);
|
||||
export function clearSession(target: Surface = surface) {
|
||||
for (const key of Object.values(KEYS[actual(target)])) sessionStorage.removeItem(key);
|
||||
}
|
||||
|
||||
export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import { appUrl, basePath, platformLoginUrl } from "./base";
|
||||
import { appUrl } from "./base";
|
||||
import { api, saveSession } from "./http";
|
||||
|
||||
const BOUNCE_KEY = "decomeval.platform-bounce";
|
||||
const BOUNCE_MS = 3 * 60 * 1000;
|
||||
|
||||
export type PlatformOutcome = "ok" | "refused" | "none";
|
||||
|
||||
/** 用平台登录身份换取本系统登录。refused 表示平台用户此时应走大数据平台登录。 */
|
||||
/** 用平台管理员身份换取管理会话。普通平台用户会被拒绝。 */
|
||||
export async function platformLogin(): Promise<PlatformOutcome> {
|
||||
try {
|
||||
const response = await fetch(appUrl("/api/auth/platform"), { method: "POST", cache: "no-store" });
|
||||
if (response.ok) {
|
||||
const body = (await response.json()) as { token: string; user: { role: string; name: string; id?: string; kind?: string } };
|
||||
saveSession(body.token, body.user);
|
||||
sessionStorage.removeItem(BOUNCE_KEY);
|
||||
saveSession(body.token, body.user, "admin");
|
||||
return "ok";
|
||||
}
|
||||
return response.status === 403 ? "refused" : "none";
|
||||
@@ -30,13 +26,3 @@ export async function loginMode() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 刚从平台登录页回来仍没有身份,说明当前平台账号没有使用权限。 */
|
||||
export function justBounced() {
|
||||
const at = Number(sessionStorage.getItem(BOUNCE_KEY) || 0);
|
||||
return at > 0 && Date.now() - at < BOUNCE_MS;
|
||||
}
|
||||
|
||||
export function goPlatformLogin(target = basePath, switchAccount = false) {
|
||||
sessionStorage.setItem(BOUNCE_KEY, String(Date.now()));
|
||||
window.location.assign(platformLoginUrl(target, switchAccount));
|
||||
}
|
||||
|
||||
+19
-9
@@ -1,10 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { h, onMounted, onUnmounted, ref } from "vue";
|
||||
import { computed, h, onMounted, onUnmounted, ref } from "vue";
|
||||
import type { Component } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { NButton, NIcon, NLayout, NLayoutSider, NMenu } from "naive-ui";
|
||||
import { AppsOutline, CloudDownloadOutline, HomeOutline, KeyOutline, ListOutline, LogOutOutline, PeopleOutline, PersonOutline, SettingsOutline } from "@vicons/ionicons5";
|
||||
import { appUrl, platformHome } from "../shared/base";
|
||||
import { appUrl } from "../shared/base";
|
||||
import { api, clearSession, sessionInfo, token } from "../shared/http";
|
||||
import { hosted } from "../shared/installState";
|
||||
import ThemeButton from "./ThemeButton.vue";
|
||||
@@ -17,21 +17,30 @@ const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { role, name } = sessionInfo();
|
||||
const collapsed = ref(window.innerWidth < 800);
|
||||
const items = role === "admin"
|
||||
const loginMode = ref("local");
|
||||
const items = computed(() => role === "admin"
|
||||
? [
|
||||
{ label: "首页", key: "/admin", icon: renderIcon(HomeOutline) },
|
||||
...(hosted ? [] : [{ label: "用户", key: "/admin/users", icon: renderIcon(PeopleOutline) }]),
|
||||
...(!hosted || loginMode.value === "local" ? [{ label: "用户", key: "/admin/users", icon: renderIcon(PeopleOutline) }] : []),
|
||||
{ label: "大数据账号池", key: "/admin/pool", icon: renderIcon(KeyOutline) },
|
||||
{ label: "采集", key: "/admin/sources", icon: renderIcon(CloudDownloadOutline) },
|
||||
{ label: "设置", key: "/admin/settings", icon: renderIcon(SettingsOutline) },
|
||||
]
|
||||
: [{ label: "任务", key: "/tasks", icon: renderIcon(ListOutline) }];
|
||||
: [{ label: "任务", key: "/tasks", icon: renderIcon(ListOutline) }]);
|
||||
|
||||
function onResize() {
|
||||
if (window.innerWidth < 800) collapsed.value = true;
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener("resize", onResize));
|
||||
onMounted(async () => {
|
||||
window.addEventListener("resize", onResize);
|
||||
if (role !== "admin") return;
|
||||
try {
|
||||
loginMode.value = (await api<{ mode: string }>("/api/auth/mode")).mode;
|
||||
} catch {
|
||||
loginMode.value = "local";
|
||||
}
|
||||
});
|
||||
onUnmounted(() => window.removeEventListener("resize", onResize));
|
||||
|
||||
async function logout() {
|
||||
@@ -42,8 +51,9 @@ async function logout() {
|
||||
/* 本地会话仍会清掉 */
|
||||
}
|
||||
}
|
||||
const admin = role === "admin";
|
||||
clearSession();
|
||||
window.location.assign(appUrl("login"));
|
||||
window.location.assign(hosted && admin ? "/hosting" : appUrl("login"));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -74,9 +84,9 @@ async function logout() {
|
||||
:options="items"
|
||||
@update:value="(key) => router.push(String(key))"
|
||||
/>
|
||||
<a v-if="hosted" class="sider-back" :class="{ compact: collapsed }" :href="platformHome" :title="collapsed ? '返回平台' : undefined">
|
||||
<a v-if="hosted && role === 'admin'" class="sider-back" :class="{ compact: collapsed }" href="/hosting" :title="collapsed ? '返回应用托管' : undefined" @click="clearSession()">
|
||||
<n-icon :size="collapsed ? 22 : 18"><AppsOutline /></n-icon>
|
||||
<span v-if="!collapsed">返回平台</span>
|
||||
<span v-if="!collapsed">返回应用托管</span>
|
||||
</a>
|
||||
<div class="sider-user" :class="{ compact: collapsed }">
|
||||
<n-icon :size="18"><PersonOutline /></n-icon>
|
||||
|
||||
Reference in New Issue
Block a user