fix: 即席查询从登记过的入口续票据,有效必须能进入查询

This commit is contained in:
2026-11-10 09:01:20 +08:00
parent 6140ca3d39
commit e3d7a05e0e
6 changed files with 75 additions and 28 deletions
+20 -17
View File
@@ -177,13 +177,13 @@ async def nqi_start(body: dict) -> dict:
if purpose == "login" and resume_cookies: if purpose == "login" and resume_cookies:
resumed = await _resume(resume_cookies) resumed = await _resume(resume_cookies)
if resumed is not None: if resumed is not None:
user, cookies = resumed user, cookies, adhoc_ready = resumed
with session_scope() as session: with session_scope() as session:
account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == username)) account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == username))
if account is not None: if account is not None:
account.cookies = cookies account.cookies = cookies
account.user_name = user.get("userName") or account.user_name account.user_name = user.get("userName") or account.user_name
account.credential_valid = True account.credential_valid = adhoc_ready
account.saved_at = utcnow() account.saved_at = utcnow()
account.role = "user" account.role = "user"
resume_name = account.user_name or account.login_id resume_name = account.user_name or account.login_id
@@ -260,7 +260,7 @@ async def nqi_finish(body: dict) -> dict:
pass pass
return {**_captcha_body(session_id, challenge), "status": "need_captcha", "message": message} return {**_captcha_body(session_id, challenge), "status": "need_captcha", "message": message}
challenge.password = "" challenge.password = ""
await client.renew_ticket() adhoc_ready = await client.renew_ticket()
cookies = client.export_cookies() cookies = client.export_cookies()
await client.aclose() await client.aclose()
drop(session_id) drop(session_id)
@@ -268,6 +268,7 @@ async def nqi_finish(body: dict) -> dict:
if purpose != "pool" and _setting(session).login_mode != "nqi": if purpose != "pool" and _setting(session).login_mode != "nqi":
raise _bad("当前使用自有账号登录") raise _bad("当前使用自有账号登录")
account = _save_pool(session, user, cookies) account = _save_pool(session, user, cookies)
account.credential_valid = adhoc_ready
login_id = account.login_id login_id = account.login_id
name = account.user_name or account.login_id name = account.user_name or account.login_id
if purpose == "pool": 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) account = session.get(NqiAccount, account_id)
if account is None: if account is None:
raise _bad("账号不存在", 404) raise _bad("账号不存在", 404)
_check_account(account) reason = _check_account(account)
return {"account": _public_account(account)} return {"account": _public_account(account), "reason": reason}
def _public_account(row: NqiAccount) -> dict: 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 []) cookies = list(account.cookies or [])
if not cookies: if not cookies:
account.credential_valid = False account.credential_valid = False
account.saved_at = utcnow() account.saved_at = utcnow()
return return "invalid"
async def run() -> tuple[bool, list]: async def run() -> tuple[str, list]:
client = NqiClient() client = NqiClient()
try: try:
client.import_cookies(cookies) client.import_cookies(cookies)
try:
await client.current_user() await client.current_user()
await client.renew_ticket()
return True, client.export_cookies()
except NqiAuthError: except NqiAuthError:
return False, cookies return "invalid", cookies
if not await client.renew_ticket():
return "adhoc", client.export_cookies()
return "ok", client.export_cookies()
finally: finally:
await client.aclose() await client.aclose()
try: try:
valid, refreshed = asyncio.run(run()) reason, refreshed = asyncio.run(run())
except NqiError as exc: except NqiError as exc:
raise _bad(str(exc)) from exc raise _bad(str(exc)) from exc
account.credential_valid = valid account.credential_valid = reason == "ok"
account.saved_at = utcnow()
if valid:
account.cookies = refreshed account.cookies = refreshed
account.saved_at = utcnow()
return reason
@router.delete("/admin/pool/{account_id}") @router.delete("/admin/pool/{account_id}")
@@ -728,8 +731,8 @@ async def _resume(cookies: list):
try: try:
client.import_cookies(cookies) client.import_cookies(cookies)
user = await client.current_user() user = await client.current_user()
await client.renew_ticket() ready = await client.renew_ticket()
return user, client.export_cookies() return user, client.export_cookies(), ready
except NqiAuthError: except NqiAuthError:
return None return None
except NqiError: except NqiError:
+9 -4
View File
@@ -15,6 +15,7 @@ from app.nqi.constants import ORIGIN
ADHOC = f"{ORIGIN}/pro-adhoc" ADHOC = f"{ORIGIN}/pro-adhoc"
PAGE = f"{ADHOC}/adhocquery" PAGE = f"{ADHOC}/adhocquery"
ENTRY = f"{ADHOC}/index"
PAGE_SIZE = 200 PAGE_SIZE = 200
MAX_PAGES = 2000 MAX_PAGES = 2000
TIME_MODES = {"prev_month", "prev_week", "prev_day", "prev_weeks", "prev_months", "prev_days"} 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: async def ensure_session(client: NqiClient) -> None:
"""门户凭证有效时,还要先打开即席查询,才会拿到这个应用自己的会话。""" """单点入口是 /pro-adhoc/index。票据有效时,这里会换成即席查询自己的会话。"""
response = await client._request( response = await client._request(
"GET", "GET",
PAGE, ENTRY,
headers={"Referer": f"{ORIGIN}/pro-portal/"}, 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, check_auth=False,
) )
if _landed_on_login(response): if response.status_code >= 400 or _landed_on_login(response):
raise NqiAuthError("登录已失效,请重新登录") raise NqiAuthError("登录已失效,请重新登录")
+6
View File
@@ -164,6 +164,10 @@ class NqiClient:
) )
return exported 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: def import_cookies(self, cookies: list[dict]) -> None:
for cookie in cookies: for cookie in cookies:
if not cookie.get("name"): if not cookie.get("name"):
@@ -319,9 +323,11 @@ class NqiClient:
"""用单点票据进入即席查询。票据还有效时,这一步会把它续上。""" """用单点票据进入即席查询。票据还有效时,这一步会把它续上。"""
from app.nqi.adhoc import ensure_session from app.nqi.adhoc import ensure_session
saved = self.export_cookies()
try: try:
await ensure_session(self) await ensure_session(self)
except NqiAuthError: except NqiAuthError:
self.replace_cookies(saved)
return False return False
return True return True
+4 -3
View File
@@ -313,7 +313,7 @@ async def refresh_accounts() -> None:
continue continue
valid, user, refreshed = outcome valid, user, refreshed = outcome
account.credential_valid = valid 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.user_name = user.get("userName") or account.user_name
account.city_name = user.get("cityName") or account.city_name account.city_name = user.get("cityName") or account.city_name
account.org_name = user.get("orgName") or account.org_name account.org_name = user.get("orgName") or account.org_name
@@ -326,9 +326,10 @@ async def _touch(cookies: list):
try: try:
client.import_cookies(cookies) client.import_cookies(cookies)
user = await client.touch_session() user = await client.touch_session()
if not await client.renew_ticket(): renewed = await client.renew_ticket()
if not renewed:
logger.info("门户登录仍有效,单点票据没有续上") logger.info("门户登录仍有效,单点票据没有续上")
return True, user, client.export_cookies() return renewed, user, client.export_cookies()
except NqiAuthError: except NqiAuthError:
return False, None, cookies return False, None, cookies
except (NqiError, OSError): except (NqiError, OSError):
+26
View File
@@ -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")
+8 -2
View File
@@ -46,9 +46,15 @@ async function load() {
async function check(account: Account) { async function check(account: Account) {
checkingId.value = account.id; checkingId.value = account.id;
try { 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); 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) { } catch (error) {
toast.error(error instanceof Error ? error.message : "检查失败"); toast.error(error instanceof Error ? error.message : "检查失败");
} finally { } finally {