From e3d7a05e0e511798e7dd2c53fcce732df749338d Mon Sep 17 00:00:00 2001 From: Nixevol Date: Tue, 10 Nov 2026 09:01:20 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=8D=B3=E5=B8=AD=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E4=BB=8E=E7=99=BB=E8=AE=B0=E8=BF=87=E7=9A=84=E5=85=A5=E5=8F=A3?= =?UTF-8?q?=E7=BB=AD=E7=A5=A8=E6=8D=AE=EF=BC=8C=E6=9C=89=E6=95=88=E5=BF=85?= =?UTF-8?q?=E9=A1=BB=E8=83=BD=E8=BF=9B=E5=85=A5=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/http.py | 41 ++++++++++++++++------------- backend/app/nqi/adhoc.py | 13 ++++++--- backend/app/nqi/client.py | 6 +++++ backend/app/tasks/runner.py | 7 ++--- backend/tests/test_adhoc_entry.py | 26 ++++++++++++++++++ web/src/features/admin/PoolView.vue | 10 +++++-- 6 files changed, 75 insertions(+), 28 deletions(-) create mode 100644 backend/tests/test_adhoc_entry.py diff --git a/backend/app/api/http.py b/backend/app/api/http.py index 4e90f7e..bd4e1c9 100644 --- a/backend/app/api/http.py +++ b/backend/app/api/http.py @@ -177,13 +177,13 @@ async def nqi_start(body: dict) -> dict: if purpose == "login" and resume_cookies: resumed = await _resume(resume_cookies) if resumed is not None: - user, cookies = resumed + user, cookies, adhoc_ready = resumed with session_scope() as session: account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == username)) if account is not None: account.cookies = cookies account.user_name = user.get("userName") or account.user_name - account.credential_valid = True + account.credential_valid = adhoc_ready account.saved_at = utcnow() account.role = "user" resume_name = account.user_name or account.login_id @@ -260,7 +260,7 @@ async def nqi_finish(body: dict) -> dict: pass return {**_captcha_body(session_id, challenge), "status": "need_captcha", "message": message} challenge.password = "" - await client.renew_ticket() + adhoc_ready = await client.renew_ticket() cookies = client.export_cookies() await client.aclose() drop(session_id) @@ -268,6 +268,7 @@ async def nqi_finish(body: dict) -> dict: if purpose != "pool" and _setting(session).login_mode != "nqi": raise _bad("当前使用自有账号登录") account = _save_pool(session, user, cookies) + account.credential_valid = adhoc_ready login_id = account.login_id name = account.user_name or account.login_id if purpose == "pool": @@ -462,8 +463,8 @@ def check_pool_account(account_id: int, actor: Actor = Depends(current_actor), s account = session.get(NqiAccount, account_id) if account is None: raise _bad("账号不存在", 404) - _check_account(account) - return {"account": _public_account(account)} + reason = _check_account(account) + return {"account": _public_account(account), "reason": reason} def _public_account(row: NqiAccount) -> dict: @@ -478,33 +479,35 @@ def _public_account(row: NqiAccount) -> dict: } -def _check_account(account: NqiAccount) -> None: +def _check_account(account: NqiAccount) -> str: cookies = list(account.cookies or []) if not cookies: account.credential_valid = False account.saved_at = utcnow() - return + return "invalid" - async def run() -> tuple[bool, list]: + async def run() -> tuple[str, list]: client = NqiClient() try: client.import_cookies(cookies) - await client.current_user() - await client.renew_ticket() - return True, client.export_cookies() - except NqiAuthError: - return False, cookies + try: + await client.current_user() + except NqiAuthError: + return "invalid", cookies + if not await client.renew_ticket(): + return "adhoc", client.export_cookies() + return "ok", client.export_cookies() finally: await client.aclose() try: - valid, refreshed = asyncio.run(run()) + reason, refreshed = asyncio.run(run()) except NqiError as exc: raise _bad(str(exc)) from exc - account.credential_valid = valid + account.credential_valid = reason == "ok" + account.cookies = refreshed account.saved_at = utcnow() - if valid: - account.cookies = refreshed + return reason @router.delete("/admin/pool/{account_id}") @@ -728,8 +731,8 @@ async def _resume(cookies: list): try: client.import_cookies(cookies) user = await client.current_user() - await client.renew_ticket() - return user, client.export_cookies() + ready = await client.renew_ticket() + return user, client.export_cookies(), ready except NqiAuthError: return None except NqiError: diff --git a/backend/app/nqi/adhoc.py b/backend/app/nqi/adhoc.py index bef99b4..4c1cb45 100644 --- a/backend/app/nqi/adhoc.py +++ b/backend/app/nqi/adhoc.py @@ -15,6 +15,7 @@ from app.nqi.constants import ORIGIN ADHOC = f"{ORIGIN}/pro-adhoc" PAGE = f"{ADHOC}/adhocquery" +ENTRY = f"{ADHOC}/index" PAGE_SIZE = 200 MAX_PAGES = 2000 TIME_MODES = {"prev_month", "prev_week", "prev_day", "prev_weeks", "prev_months", "prev_days"} @@ -55,14 +56,18 @@ def _end(day: date) -> datetime: async def ensure_session(client: NqiClient) -> None: - """门户凭证有效时,还要先打开即席查询,才会拿到这个应用自己的会话。""" + """单点入口是 /pro-adhoc/index。票据有效时,这里会换成即席查询自己的会话。""" response = await client._request( "GET", - PAGE, - headers={"Referer": f"{ORIGIN}/pro-portal/"}, + ENTRY, + headers={ + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Referer": f"{ORIGIN}/pro-portal/", + "Upgrade-Insecure-Requests": "1", + }, check_auth=False, ) - if _landed_on_login(response): + if response.status_code >= 400 or _landed_on_login(response): raise NqiAuthError("登录已失效,请重新登录") diff --git a/backend/app/nqi/client.py b/backend/app/nqi/client.py index 63ebe92..cb9a88c 100644 --- a/backend/app/nqi/client.py +++ b/backend/app/nqi/client.py @@ -164,6 +164,10 @@ class NqiClient: ) return exported + def replace_cookies(self, cookies: list[dict]) -> None: + self.client.cookies.clear() + self.import_cookies(cookies) + def import_cookies(self, cookies: list[dict]) -> None: for cookie in cookies: if not cookie.get("name"): @@ -319,9 +323,11 @@ class NqiClient: """用单点票据进入即席查询。票据还有效时,这一步会把它续上。""" from app.nqi.adhoc import ensure_session + saved = self.export_cookies() try: await ensure_session(self) except NqiAuthError: + self.replace_cookies(saved) return False return True diff --git a/backend/app/tasks/runner.py b/backend/app/tasks/runner.py index 2fd6425..f44e91a 100644 --- a/backend/app/tasks/runner.py +++ b/backend/app/tasks/runner.py @@ -313,7 +313,7 @@ async def refresh_accounts() -> None: continue valid, user, refreshed = outcome account.credential_valid = valid - if valid and user is not None: + if user is not None: account.user_name = user.get("userName") or account.user_name account.city_name = user.get("cityName") or account.city_name account.org_name = user.get("orgName") or account.org_name @@ -326,9 +326,10 @@ async def _touch(cookies: list): try: client.import_cookies(cookies) user = await client.touch_session() - if not await client.renew_ticket(): + renewed = await client.renew_ticket() + if not renewed: logger.info("门户登录仍有效,单点票据没有续上") - return True, user, client.export_cookies() + return renewed, user, client.export_cookies() except NqiAuthError: return False, None, cookies except (NqiError, OSError): diff --git a/backend/tests/test_adhoc_entry.py b/backend/tests/test_adhoc_entry.py new file mode 100644 index 0000000..c0b4ed5 --- /dev/null +++ b/backend/tests/test_adhoc_entry.py @@ -0,0 +1,26 @@ +import asyncio + +from app.nqi.adhoc import ENTRY, ensure_session + + +def test_adhoc_session_uses_the_registered_service(): + assert ENTRY.endswith("/pro-adhoc/index") + seen = {} + + class Response: + status_code = 200 + + class url: + path = "/pro-adhoc/index" + + class Client: + async def _request(self, method, url, **kwargs): + seen["method"] = method + seen["url"] = url + seen["accept"] = kwargs["headers"]["Accept"] + return Response() + + asyncio.run(ensure_session(Client())) + assert seen["method"] == "GET" + assert seen["url"] == ENTRY + assert seen["accept"].startswith("text/html") diff --git a/web/src/features/admin/PoolView.vue b/web/src/features/admin/PoolView.vue index bd0682b..e27a0c2 100644 --- a/web/src/features/admin/PoolView.vue +++ b/web/src/features/admin/PoolView.vue @@ -46,9 +46,15 @@ async function load() { async function check(account: Account) { checkingId.value = account.id; try { - const result = await api<{ account: Account }>(`/api/admin/pool/${account.id}/check`, { method: "POST" }); + const result = await api<{ account: Account; reason: string }>(`/api/admin/pool/${account.id}/check`, { method: "POST" }); accounts.value = accounts.value.map((item) => item.id === result.account.id ? result.account : item); - toast.success(result.account.credentialValid ? "凭证有效" : "凭证已失效"); + if (result.reason === "adhoc") { + toast.warning("门户登录还在,但进入即席查询没有接上,请用这个大数据账号重新登录一次"); + } else if (result.account.credentialValid) { + toast.success("凭证有效"); + } else { + toast.warning("凭证已失效"); + } } catch (error) { toast.error(error instanceof Error ? error.message : "检查失败"); } finally {