1. 新增xq0031_xq0032插件:包含前后端源码、打包脚本、配置文件与插件元数据 2. 新增内网文件服务器组件:exe、启停脚本、打包脚本与配置 3. 新增敏感凭证RSA加密下发能力与存储结构 4. 新增大文件源管理表与相关API 5. 优化登录流程与会话管理,新增Chrome自动化安装工具链 6. 清理废弃插件与示例代码 7. 更新版本号至1.1.3,完善安装包与.gitignore配置
166 lines
6.8 KiB
Python
166 lines
6.8 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""webhost 宿主「管理台基础」路由:统一账户登录 / 当前账号 / 登出 / 改密 / 概览 / 头像代理。"""
|
||
from __future__ import annotations
|
||
|
||
import time
|
||
import uuid
|
||
from urllib.parse import quote
|
||
|
||
from fastapi import APIRouter, File, HTTPException, Request, Response, UploadFile
|
||
from pydantic import BaseModel
|
||
|
||
from webhost.backend import config
|
||
from webhost.backend.core.cpapi import _cp_call, _cp_headers, _sync_licensing
|
||
from webhost.backend.core.session import (SESSION_COOKIE, _SESS, _SESS_LOCK,
|
||
_sess_account, _sess_persist, _ACCT_CLOUD_TOKEN)
|
||
|
||
router = APIRouter()
|
||
|
||
|
||
class _LoginIn(BaseModel):
|
||
account: str
|
||
password: str
|
||
|
||
|
||
class _PwdIn(BaseModel):
|
||
account: str
|
||
old_password: str
|
||
new_password: str
|
||
|
||
|
||
@router.get("/api/admin/me")
|
||
def admin_me(request: Request) -> dict:
|
||
"""当前登录账号是否管理员(会话 cookie)。
|
||
|
||
账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐,
|
||
云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False,
|
||
不影响员工正常进入插件页(前端以 account 非空判登录)。
|
||
"""
|
||
account = _sess_account(request)
|
||
if not account:
|
||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||
try:
|
||
r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
|
||
if r.get("account") == account:
|
||
return r
|
||
except HTTPException:
|
||
pass
|
||
return {"account": account, "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||
|
||
|
||
@router.post("/api/admin/login")
|
||
def admin_login(b: _LoginIn, response: Response) -> dict:
|
||
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
|
||
try:
|
||
r = _cp_call("POST", "/api/admin/auth",
|
||
headers={"X-Admin-User": b.account.strip(),
|
||
**({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||
"Content-Type": "application/json"},
|
||
json={"account": b.account, "password": b.password})
|
||
except HTTPException as e:
|
||
raise e
|
||
if not r.get("ok"):
|
||
return r
|
||
token = uuid.uuid4().hex
|
||
with _SESS_LOCK:
|
||
_SESS[token] = (b.account.strip(), time.time())
|
||
_sess_persist()
|
||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||
# 沿用中心机登录时签发的用户云令牌,后续 /api/admin/me 等调用凭它定位账号(无需机器 TOKEN)
|
||
_cloud_tok = (r or {}).get("cloud_token") or ""
|
||
if _cloud_tok:
|
||
_ACCT_CLOUD_TOKEN[b.account.strip()] = _cloud_tok
|
||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||
if config.CONTROLPLANE_URL:
|
||
try:
|
||
_sync_licensing(b.account.strip())
|
||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||
import logging
|
||
logging.getLogger(__name__).warning("登录后同步离线授权票据失败:%s", _exc)
|
||
# 登录成功即按账号权限自下载/更新插件并重载(离线/失败不影响登录)
|
||
try:
|
||
from webhost.backend.core.plugin_sync import sync_plugins
|
||
from webhost.backend.plugins import load_plugins
|
||
sync_plugins(b.account.strip())
|
||
load_plugins(None, reload=True)
|
||
except Exception as _exc: # noqa: BLE001
|
||
import logging
|
||
logging.getLogger(__name__).warning("登录后插件同步失败:%s", _exc)
|
||
# 登录后刷新该账号敏感凭证(管理员可拉到;员工被服务端 403 拒绝 → 走本地缓存,无害)
|
||
try:
|
||
from webhost.backend.core import creds_sync
|
||
_creds = creds_sync.load(b.account.strip())
|
||
if _creds:
|
||
config.apply_creds(_creds)
|
||
except Exception as _exc: # noqa: BLE001
|
||
import logging
|
||
logging.getLogger(__name__).warning("登录后敏感凭证刷新失败:%s", _exc)
|
||
return {**r, "account": b.account.strip()}
|
||
|
||
|
||
@router.post("/api/admin/logout")
|
||
def admin_logout(request: Request, response: Response) -> dict:
|
||
"""登出:清除会话 cookie 与内存会话。"""
|
||
token = request.cookies.get(SESSION_COOKIE, "")
|
||
with _SESS_LOCK:
|
||
_SESS.pop(token, None)
|
||
_sess_persist()
|
||
response.delete_cookie(SESSION_COOKIE)
|
||
return {"ok": True}
|
||
|
||
|
||
@router.post("/api/admin/password")
|
||
def admin_password(b: _PwdIn, request: Request) -> dict:
|
||
return _cp_call("POST", "/api/admin/password",
|
||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||
json=b.model_dump())
|
||
|
||
|
||
@router.get("/api/admin/overview")
|
||
def admin_overview(request: Request) -> dict:
|
||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||
return {"plugins": [], "accounts": [], "admins": []}
|
||
|
||
|
||
@router.get("/api/avatar/{account}")
|
||
def avatar_get(account: str) -> Response:
|
||
"""代理中心机头像读取(webhost 前端 img 直接引用;未设置头像返回 404)。"""
|
||
if not config.CONTROLPLANE_URL:
|
||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||
import requests
|
||
|
||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/avatar/{quote(account)}", timeout=10)
|
||
if r.status_code != 200:
|
||
raise HTTPException(r.status_code, "头像不存在")
|
||
return Response(content=r.content,
|
||
media_type=r.headers.get("content-type", "application/octet-stream"))
|
||
|
||
|
||
@router.post("/api/avatar")
|
||
def avatar_upload(file: UploadFile = File(...), request: Request = None) -> dict:
|
||
"""上传当前登录账号的头像(自服务,账号取本机会话),代理到中心机。"""
|
||
if request is None:
|
||
raise HTTPException(500, "missing request")
|
||
account = _sess_account(request)
|
||
if not account:
|
||
raise HTTPException(401, "未登录")
|
||
if not config.CONTROLPLANE_URL:
|
||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||
import requests as _rq
|
||
|
||
data = file.file.read()
|
||
if not data:
|
||
raise HTTPException(400, "头像文件为空")
|
||
resp = _rq.post(
|
||
f"{config.CONTROLPLANE_URL}/api/admin/avatar?account={quote(account)}",
|
||
headers=_cp_headers(request),
|
||
files={"file": (file.filename or f"{account}.png", data,
|
||
file.content_type or "application/octet-stream")},
|
||
timeout=30)
|
||
try:
|
||
body = resp.json()
|
||
except ValueError:
|
||
body = {"detail": resp.text[:300]}
|
||
if resp.status_code >= 400:
|
||
raise HTTPException(resp.status_code, body.get("detail", f"中心机 {resp.status_code}"))
|
||
return body |