diff --git a/backend/euniv/api.py b/backend/euniv/api.py index ecbd7d7..16d4dbe 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -26,8 +26,10 @@ from euniv.service import ( fetch_study_history, fetch_training_detail, login_and_store, + poll_qr_login, revoke_credential, start_credential_refresh, + start_qr_login, submit_jigsaw, ) from euniv.session import clear_session, read_employee_id, write_session @@ -102,6 +104,10 @@ class JigsawBody(BaseModel): offset: int = Field(ge=0, le=2000) +class QrPollBody(BaseModel): + attempt_id: str = Field(min_length=8, max_length=64) + + @app.get("/api/health") def health() -> dict: return {"ok": True} @@ -162,6 +168,25 @@ def login_jigsaw(body: JigsawBody, response: Response, db: Session = Depends(get return _open_session(response, payload) +@app.post("/api/login/qr") +def login_qr() -> dict: + try: + return start_qr_login() + except RuntimeError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + +@app.post("/api/login/qr/poll") +def login_qr_poll(body: QrPollBody, response: Response, db: Session = Depends(get_db)) -> dict: + try: + payload = poll_qr_login(db, body.attempt_id) + except RuntimeError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + if payload.get("employee_id"): + return _open_session(response, payload) + return payload + + @app.post("/api/logout") def logout(response: Response) -> dict: clear_session(response) diff --git a/backend/euniv/client.py b/backend/euniv/client.py index f7a051c..290b964 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -3,6 +3,7 @@ from __future__ import annotations import base64 +import hashlib import io import json import random @@ -19,19 +20,33 @@ from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from PIL import Image -PORTAL = "https://bmtucportal.zte.com.cn" +PORTAL = "https://uac.zte.com.cn" +PORTAL_BFF = f"{PORTAL}/zte-sec-uac-iportalbff" +PORTAL_PAGE = f"{PORTAL}/zte-sec-uac-iportal/iportal/" EUNIV = "https://euniv.zte.com.cn" YXT_API = "https://api-qidacustomc1.yunxuetang.cn" STUDY_API = "https://api-qidac1.yunxuetang.cn" CLASS_API = "https://sdcs-api-ztec1.yunxuetang.cn" REDIRECT_URI = f"{YXT_API}/v1/ztctech/sso" -CLIENT_ID = "30051" +CLIENT_ID = "183681933766" TENANT_ID = "10001" -APP_ID = "10051" +APP_ID = CLIENT_ID +INNER_APP_ID = "10001" USER_AGENT = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:158.0) " "Gecko/20100101 Firefox/158.0" ) +PUBLIC_KEY_B64 = ( + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApeLemQaHD72LD0L6Jyc8OiDZhGla2SeHkpQWHfUR" + "MGxV6zHCc0M8dvYZ5RTDWO53CVAEPCNFPG5oUIay+XH/UwxmOuO1aYxyNISSwyrovP341Qsy2uvZAnHo4cyY" + "5xTAYqCP5Yv/e2pkUeQRu+KQ+Y4JiQzEGia+ASmI5tF4tYqArllaWFlDBR7rtAV4/O/9zn5WA2kISRwgjW1i" + "rrQDG7OKe8AMjZx1RPw6gLRA18AE4Jf66U6GWi2nuI0mmeQ1kudBkH/ucVQ6wbReXcRJHpyxQGCQX871acHq" + "ZTGGHv4l6SM0U5jegvmJqHRNsTgWN0WQVAmTFXUGoGornnf+6wIDAQAB" +) +QR_PASSWORD_MARK = "扫码登陆" +QR_PREFIX = "TwoDIMAuth" +UAC_OK = "0000" +UAC_QR_WAIT = "4002" def now_ms() -> int: @@ -48,6 +63,59 @@ def encrypt_password(public_key_b64: str, password: str) -> str: return base64.b64encode(cipher).decode("ascii") +def encrypt_field(value: str) -> str: + return encrypt_password(PUBLIC_KEY_B64, value) + + +def is_qr_password(password: str) -> bool: + return password == QR_PASSWORD_MARK + + +def parse_uac(payload: object) -> tuple[str, str, object, str]: + """解析 UAC 两种响应:code 为对象(嵌套 bo/other.data)或顶层字符串(data)。""" + if not isinstance(payload, dict): + return "", "", None, "" + code = payload.get("code") + reason = payload.get("reason") if isinstance(payload.get("reason"), dict) else {} + if isinstance(code, dict): + top = str(code.get("code") or "") + bo = payload.get("bo") if isinstance(payload.get("bo"), dict) else {} + inner = str(bo.get("code") or top) + other = payload.get("other") if isinstance(payload.get("other"), dict) else {} + data = other.get("data") + if data is None: + data = payload.get("data") + message = str(bo.get("msg") or code.get("msg") or reason.get("zh_CN") or "") + return top, inner, data, message + top = str(code or "") + message = str(payload.get("message") or reason.get("zh_CN") or "") + return top, top, payload.get("data"), message + + +def make_qr_payload(prefix: str = QR_PREFIX) -> str: + def digest(text: str) -> str: + return hashlib.md5(text.encode("utf-8")).hexdigest() + + def digits(count: int) -> str: + return "".join(random.choice("0123456789") for _ in range(count)) + + key = digest(prefix + str(now_ms()) + digits(10)) + value = digest(key + digits(10)) + return f"{prefix}:{key}:{value}" + + +def qr_data_uri(text: str) -> str: + import qrcode + + qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=6, border=2) + qr.add_data(text) + qr.make(fit=True) + image = qr.make_image(fill_color="black", back_color="white") + buf = io.BytesIO() + image.save(buf, format="PNG") + return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii") + + def decode_data_uri(value: str) -> bytes: payload = value.split(",", 1)[1] if "," in value else value return base64.b64decode(payload) @@ -532,6 +600,10 @@ class ManualJigsaw(Exception): self.puzzle = puzzle +class QrWaiting(Exception): + """二维码尚未扫过或还在等待确认。""" + + class EunivClient: def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: from euniv.proxy import parse_proxy @@ -548,71 +620,113 @@ class EunivClient: self._profile: dict = {} self._yxt_token = "" self._cipher = "" + self._cipher_name = "" self._kid = "" self._puzzle: dict = {} + self._qr_str = "" def close(self) -> None: self.client.close() - def portal_headers(self) -> dict[str, str]: - referer = ( - f"{PORTAL}/uc/{TENANT_ID}/oauthLogin?client_id={CLIENT_ID}" - f"&scope=profile&redirect_uri={quote(REDIRECT_URI, safe='')}" - "&response_type=code" - ) - return { + def portal_headers(self, app_id: str | None = None, json_body: bool = True) -> dict[str, str]: + request_id = str(uuid.uuid4()) + headers = { "Accept": "application/json, text/plain, */*", - "Content-Type": "application/json;charset=UTF-8", "Origin": PORTAL, - "Referer": referer, - "X-App-Id": APP_ID, + "Referer": PORTAL_PAGE, + "X-App-Id": app_id or APP_ID, "X-Device-Type": "pc", - "X-Itp-Value": "from=ucs-portal;client=pc;platform=portal", + "X-Itp-Value": "client=pc;platform=iportal;deviceType=web", "X-Lang-Id": "zh_CN", "X-Tenant-Id": TENANT_ID, - "x_uuid": str(uuid.uuid4()), + "x_uuid": request_id, + "x-uuid": request_id, } + if json_body: + headers["Content-Type"] = "application/json;charset=UTF-8" + return headers def code_of(self, payload: dict) -> tuple[str, str, object]: - block = payload.get("code") or {} - return block.get("code") or "", block.get("msg") or "", payload.get("bo") + top, _inner, data, message = parse_uac(payload) + return top, message, data + + def _uac_post(self, path: str, *, app_id: str | None = None, json_body: object = None, extra: dict | None = None) -> httpx.Response: + headers = self.portal_headers(app_id) + if extra: + headers.update(extra) + url = path if path.startswith("http") else PORTAL_BFF + path + if json_body is None: + return self.client.post(url, headers=headers, content=b"null") + return self.client.post(url, headers=headers, json=json_body) + + def _begin_uac(self) -> None: + self.client.get(EUNIV + "/") + self.client.get( + f"{PORTAL_BFF}/auth/external/login/oauth/authorize.serv", + params={ + "client_id": CLIENT_ID, + "scope": "openid", + "redirect_uri": REDIRECT_URI, + "response_type": "code", + }, + headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}, + ) + self._uac_post(f"/auth/external/oauth/source/{CLIENT_ID}", app_id=INNER_APP_ID) + top, _inner, _data, message = parse_uac( + self._uac_post( + "/auth/external/oauth/validate.serv", + json_body={ + "redirectUri": REDIRECT_URI, + "clientId": CLIENT_ID, + "responseType": "code", + "state": "null", + "scope": "openid", + }, + ).json() + ) + if top != UAC_OK: + raise RuntimeError(f"登录页校验失败:{message or top}") def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: - self.client.get(EUNIV + "/") - self.client.post( - f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate", - headers=self.portal_headers(), - json={ - "clientId": CLIENT_ID, - "redirectUri": REDIRECT_URI, - "responseType": "code", - "scope": "profile", - "_t": now_ms(), - }, + if is_qr_password(self.password): + raise RuntimeError("扫码登录已失效,请重新扫码登录") + self._begin_uac() + check_resp = self._uac_post( + "/authentication/pas/securitycode/check.serv", + json_body={"accountId": self.login_name, "callerId": CLIENT_ID}, ) - key_resp = self.client.post( - f"{PORTAL}/zte-bmt-ucs-portalbff/srv/password/publicKey/{TENANT_ID}", - headers=self.portal_headers(), - json={"_t": now_ms()}, - ) - key_code, key_message, public_key = self.code_of(key_resp.json()) - if key_code != "0000" or not isinstance(public_key, str): - raise RuntimeError(f"获取密码公钥失败:{key_message or key_resp.status_code}") - - check_resp = self.client.post( - f"{PORTAL}/zte-bmt-ucs-portalbff/srv/pas/securitycode/check", - headers=self.portal_headers(), - json={"accountId": self.login_name, "callerId": APP_ID, "_t": now_ms()}, - ) - check_code, check_message, needs_security_code = self.code_of(check_resp.json()) - if check_code == "0000" and needs_security_code is True: + top, _inner, needs_security_code, message = parse_uac(check_resp.json()) + if top == UAC_OK and needs_security_code is True: raise RuntimeError("这个账号开启了动态安全码,当前登录流程还不能提交安全码") - if check_code not in ("", "0000"): - raise RuntimeError(f"安全码检查失败:{check_message}") - - self._cipher = encrypt_password(public_key, self.password) + if top not in ("", UAC_OK): + raise RuntimeError(f"安全码检查失败:{message}") + self._cipher_name = encrypt_field(self.login_name) + self._cipher = encrypt_field(self.password) return self._login_with_jigsaw(manual, auto_attempts) + def start_qr(self) -> tuple[str, str]: + self._begin_uac() + self._qr_str = make_qr_payload() + return self._qr_str, qr_data_uri(self._qr_str) + + def poll_qr(self) -> dict: + if not self._qr_str or ":" not in self._qr_str: + raise RuntimeError("请重新扫码") + parts = self._qr_str.split(":") + if len(parts) < 3: + raise RuntimeError("请重新扫码") + payload = self._uac_post( + "/authentication/qrscan.serv", + json_body={"qrCodeKey": parts[1], "qrCodeValue": parts[2]}, + ).json() + top, inner, data, message = parse_uac(payload) + if top == UAC_OK and inner == UAC_QR_WAIT: + raise QrWaiting() + if top == UAC_OK and inner == UAC_OK and isinstance(data, dict) and data.get("token"): + self.login_name = str(data.get("accountId") or data.get("userName") or self.login_name) + return data + raise RuntimeError(message or "扫码登录失败") + def _login_with_jigsaw(self, manual: bool, auto_attempts: int) -> dict: """次数由调用方传入。只把拼图被拒绝计入自动次数,密码错误或网络失败不重试。""" if manual: @@ -630,31 +744,31 @@ class EunivClient: def _load_jigsaw(self) -> tuple[bytes, bytes, int]: kid = make_kid("t") image_resp = self.client.get( - f"{PORTAL}/zte-bmt-ucs-portalbff/srv/kaptcha/jigsaw", - params={"kid": kid, "_t": now_ms()}, - headers=self.portal_headers(), + f"{PORTAL_BFF}/common/captcha/create.serv", + params={"kid": kid}, + headers=self.portal_headers(json_body=False), ) - image_code, image_message, image = self.code_of(image_resp.json()) - if image_code != "0000": - raise RuntimeError(f"获取拼图失败:{image_message}") + top, _inner, image, message = parse_uac(image_resp.json()) + if top != UAC_OK: + raise RuntimeError(f"获取拼图失败:{message}") if not isinstance(image, dict): raise RuntimeError("拼图返回无法识别") big = decode_data_uri(image["bigImg"]) small = decode_data_uri(image["smallImg"]) big_size = Image.open(io.BytesIO(big)).size small_size = Image.open(io.BytesIO(small)).size - top = int(image["yHeight"]) + offset_y = int(image["yHeight"]) self._kid = kid self._puzzle = { "big_img": data_uri(image["bigImg"]), "small_img": data_uri(image["smallImg"]), - "y": top, + "y": offset_y, "width": big_size[0], "height": big_size[1], "piece_width": small_size[0], "piece_height": small_size[1], } - return big, small, top + return big, small, offset_y def next_jigsaw(self) -> dict: self._load_jigsaw() @@ -664,32 +778,34 @@ class EunivClient: return dict(self._puzzle) def submit_jigsaw(self, offset: int) -> dict: - headers = self.portal_headers() - headers.update({"kcode": "", "kid": make_kid(""), "kskip": "true", "source": APP_ID}) - login_resp = self.client.post( - f"{PORTAL}/zte-bmt-ucs-portalbff/srv/login", - headers=headers, - json={ - "loginName": self.login_name, + login_resp = self._uac_post( + "/authentication/login.serv", + extra={"kskip": "true"}, + json_body={ + "loginName": self._cipher_name or encrypt_field(self.login_name), "password": self._cipher, "kid": self._kid, "jigsawCode": int(offset), - "_t": now_ms(), }, ) - login_code, message, profile = self.code_of(login_resp.json()) - if login_code == "0000" and isinstance(profile, dict): + top, _inner, profile, message = parse_uac(login_resp.json()) + if top == UAC_OK and isinstance(profile, dict) and profile.get("token"): return profile if any(word in message for word in ("验证码", "拼图", "滑块")): raise JigsawRejected(message or "拼图未通过") raise RuntimeError(f"登录失败:{message}") def authorize(self, profile: dict) -> None: - account_id = str(profile["accountId"]) - user_id = str(profile["userId"]) - token = str(profile["token"]) + account_id = str(profile.get("accountId") or profile.get("userName") or "") + user_id = str(profile.get("userId") or account_id) + token = str(profile.get("token") or "") + if not account_id or not token: + raise RuntimeError("登录结果缺少账号或令牌") domain = "zte.com.cn" jar = { + "PORTALSSOLanguage": "zh_CN", + "PORTALSSOUser": account_id, + "PORTALSSOCookie": token, "UCSLoginName": account_id, "UCSSSOAccount": account_id, "UCSSSOUser": user_id, @@ -702,29 +818,46 @@ class EunivClient: "iAuthUid_prod": account_id, "iAuthTid_prod": token, "iAuthLanguage_prod": "zh_CN", + "iAuthLoginName_prod": account_id, } if profile.get("unionId"): jar["iuacUnionId"] = str(profile["unionId"]) for name, value in jar.items(): self.client.cookies.set(name, value, domain=domain, path="/") - response = self.client.post( - f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/authorize", - params={ - "redirect_uri": REDIRECT_URI, - "client_id": CLIENT_ID, - "response_type": "code", - "scope": "profile", - }, - headers=self.portal_headers(), - json={"accountId": account_id, "token": token, "userId": user_id, "_t": now_ms()}, + self._uac_post( + "/authentication/token/verify.serv", + app_id=INNER_APP_ID, + json_body={"accountId": account_id, "token": token}, ) - code, message, redirect_url = self.code_of(response.json()) - if code != "0000" or not isinstance(redirect_url, str): + try: + self._uac_post( + "/external/account/lasttenant/query.serv", + app_id=INNER_APP_ID, + json_body={"accountId": account_id}, + ) + self._uac_post( + "/external/account/lasttenant/update.serv", + app_id=INNER_APP_ID, + json_body={"tenantId": TENANT_ID}, + ) + except Exception: + pass + + response = self._uac_post( + "/auth/external/oauth/authorize.serv" + f"?redirect_uri={quote(REDIRECT_URI, safe='')}" + f"&response_type=code&client_id={CLIENT_ID}&state=null&scope=openid", + app_id=INNER_APP_ID, + json_body={"accountId": account_id, "token": token, "redirectUri": REDIRECT_URI}, + ) + top, _inner, data, message = parse_uac(response.json()) + callback = data.get("callbackUrl") if isinstance(data, dict) else None + if top != UAC_OK or not isinstance(callback, str) or not callback: raise RuntimeError(f"申请学习平台授权码失败:{message}") - self.client.get(redirect_url, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT}) + self.client.get(callback, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT}) self._profile = { - "token": str(profile.get("token") or ""), + "token": token, "accountId": account_id, "userId": user_id, "ssoinfo": str(profile.get("ssoinfo") or ""), diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 594631a..aff295c 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -11,12 +11,22 @@ from dataclasses import dataclass from sqlalchemy import select from sqlalchemy.orm import Session -from euniv.client import EunivClient, JigsawRejected, ManualJigsaw, SessionExpired +from euniv.client import ( + QR_PASSWORD_MARK, + EunivClient, + JigsawRejected, + ManualJigsaw, + QrWaiting, + SessionExpired, + is_qr_password, +) from euniv.crypto import decrypt_secret, encrypt_secret from euniv.models import Account _PENDING_SECONDS = 180 +_QR_SECONDS = 70 _pending: dict[str, "PendingLogin"] = {} +_pending_qr: dict[str, "PendingQr"] = {} _credential_guard = threading.Lock() _credential_locks: dict[str, threading.Lock] = {} @@ -38,6 +48,12 @@ class PendingLogin: created: float +@dataclass +class PendingQr: + client: EunivClient + created: float + + def _dump(credential: dict) -> str: return json.dumps(credential, ensure_ascii=False, sort_keys=True) @@ -48,6 +64,16 @@ def _purge_pending() -> None: if now - pending.created > _PENDING_SECONDS: pending.client.close() _pending.pop(attempt_id, None) + for attempt_id, pending in list(_pending_qr.items()): + if now - pending.created > _QR_SECONDS: + pending.client.close() + _pending_qr.pop(attempt_id, None) + + +def _drop_qr(attempt_id: str) -> None: + pending = _pending_qr.pop(attempt_id, None) + if pending is not None: + pending.client.close() def _drop_employee(employee_id: str) -> None: @@ -180,6 +206,46 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict: pending.client.close() +def start_qr_login(client_factory=EunivClient) -> dict: + _purge_pending() + client = None + try: + client = client_factory("", "") + _unused_qr, image = client.start_qr() + except Exception: + if client is not None: + client.close() + raise + attempt_id = secrets.token_urlsafe(18) + _pending_qr[attempt_id] = PendingQr(client, time.time()) + return {"attempt_id": attempt_id, "qr_image": image, "ttl": 60} + + +def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> dict: + _purge_pending() + pending = _pending_qr.get(attempt_id) + if pending is None: + raise RuntimeError("请重新扫码") + try: + profile = pending.client.poll_qr() + except QrWaiting: + return {"status": "waiting"} + except Exception: + _drop_qr(attempt_id) + raise + _pending_qr.pop(attempt_id, None) + employee_id = str(profile.get("accountId") or profile.get("userName") or "").strip() + if not employee_id: + pending.client.close() + raise RuntimeError("扫码登录没有返回工号") + try: + _persist(db, employee_id, QR_PASSWORD_MARK, pending.client, profile) + _request_course_sync(employee_id) + return {"employee_id": employee_id} + finally: + pending.client.close() + + def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict: """向 e 学现查首页信息。个人信息只出现在返回值里,不写入数据库。凭证变化时更新密文。""" return _live(db, employee_id, client_factory, lambda client: client.home_snapshot()) @@ -233,6 +299,8 @@ def _live(db: Session, employee_id: str, client_factory, read): try: if credential.get("yxt_token"): client.restore(credential) + elif is_qr_password(password): + raise RuntimeError("扫码登录已失效,请重新扫码登录") else: try: client.authorize(client.login(manual=False, auto_attempts=attempts)) @@ -241,6 +309,8 @@ def _live(db: Session, employee_id: str, client_factory, read): try: data = read(client) except SessionExpired: + if is_qr_password(password): + raise RuntimeError("扫码登录已失效,请重新扫码登录") from None try: client.authorize(client.login(manual=False, auto_attempts=attempts)) except ManualJigsaw: @@ -316,6 +386,8 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None: account.credential_cipher = encrypt_secret(_dump(updated)) valid = True checked_alive = True + elif is_qr_password(password): + valid = False else: profile = client.login(manual=False, auto_attempts=attempts) _persist(db, employee_id, password, client, profile) diff --git a/backend/requirements.txt b/backend/requirements.txt index 18b6776..73af6f9 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -2,6 +2,7 @@ httpx==0.28.1 socksio==1.0.0 cryptography==50.0.2 pillow==13.0.0 +qrcode==8.2 fastapi==0.162.0 uvicorn==0.54.0 sqlalchemy==2.1.6 diff --git a/backend/tests/test_uac.py b/backend/tests/test_uac.py new file mode 100644 index 0000000..c1c9f24 --- /dev/null +++ b/backend/tests/test_uac.py @@ -0,0 +1,152 @@ +import json + +import pytest +from fastapi.testclient import TestClient + +from euniv.client import ( + QR_PASSWORD_MARK, + EunivClient, + QrWaiting, + encrypt_field, + is_qr_password, + make_qr_payload, + parse_uac, + qr_data_uri, +) +from euniv.crypto import decrypt_secret +from euniv.db import SessionLocal +from euniv.models import Account + + +def test_parse_uac_nested_and_flat() -> None: + top, inner, data, message = parse_uac( + { + "code": {"code": "0000", "msg": "操作成功"}, + "bo": {"code": "4002", "msg": "二维码状态轮询失败"}, + "other": None, + } + ) + assert top == "0000" + assert inner == "4002" + assert data is None + assert "二维码" in message + + top, inner, data, message = parse_uac( + { + "code": {"code": "0000", "msg": "操作成功"}, + "bo": {"code": "0000", "msg": "成功"}, + "other": {"data": {"callbackUrl": "https://example.test/sso?code=1"}}, + } + ) + assert top == inner == "0000" + assert data == {"callbackUrl": "https://example.test/sso?code=1"} + + top, inner, data, message = parse_uac( + { + "code": "0000", + "reason": {"zh_CN": "成功"}, + "data": {"accountId": "6650000146", "token": "abc"}, + } + ) + assert top == inner == "0000" + assert data["token"] == "abc" + assert message == "成功" + + +def test_qr_payload_and_rsa_cipher_shape() -> None: + text = make_qr_payload() + prefix, key, value = text.split(":") + assert prefix == "TwoDIMAuth" + assert len(key) == 32 + assert len(value) == 32 + assert int(key, 16) >= 0 + cipher = encrypt_field("6650000146") + assert len(cipher) == 344 + assert is_qr_password(QR_PASSWORD_MARK) + assert not is_qr_password("secret-pass") + uri = qr_data_uri(text) + assert uri.startswith("data:image/png;base64,") + + +def test_qr_password_cannot_use_password_login() -> None: + client = EunivClient("6650000146", QR_PASSWORD_MARK) + try: + with pytest.raises(RuntimeError, match="扫码登录已失效"): + client.login() + finally: + client.close() + + +def test_qr_login_stores_scan_mark(monkeypatch) -> None: + import euniv.api as api_module + import euniv.service as service_module + + service_module._pending.clear() + service_module._pending_qr.clear() + + class QrClient: + def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: + self.login_name = login_name + self.password = password + self.proxy = proxy + self._profile: dict = {} + self._token = "yxt-qr" + self._polls = 0 + + def close(self) -> None: + return None + + def start_qr(self) -> tuple[str, str]: + return "TwoDIMAuth:aa:bb", "data:image/png;base64,QQ==" + + def poll_qr(self) -> dict: + self._polls += 1 + if self._polls == 1: + raise QrWaiting() + return { + "accountId": "6650000146", + "userId": "6650000146", + "token": "ucs-qr", + "unionId": "un-1", + } + + def authorize(self, profile: dict) -> None: + self._profile = dict(profile) + + def export_credential(self) -> dict: + return { + "ucs_token": self._profile["token"], + "ucs_account_id": self._profile["accountId"], + "ucs_user_id": self._profile["userId"], + "ucs_ssoinfo": "", + "ucs_union_id": self._profile.get("unionId") or "", + "yxt_token": self._token, + } + + monkeypatch.setattr(api_module, "start_qr_login", lambda: service_module.start_qr_login(QrClient)) + monkeypatch.setattr(api_module, "poll_qr_login", service_module.poll_qr_login) + monkeypatch.setattr(service_module, "_request_course_sync", lambda employee_id: None) + + client = TestClient(api_module.app) + started = client.post("/api/login/qr") + assert started.status_code == 200 + body = started.json() + assert body["qr_image"].startswith("data:image/png;base64,") + attempt_id = body["attempt_id"] + + waiting = client.post("/api/login/qr/poll", json={"attempt_id": attempt_id}) + assert waiting.status_code == 200 + assert waiting.json() == {"status": "waiting"} + + done = client.post("/api/login/qr/poll", json={"attempt_id": attempt_id}) + assert done.status_code == 200 + assert done.json() == {"role": "user", "employee_id": "6650000146"} + + with SessionLocal() as db: + account = db.get(Account, "6650000146") + assert account is not None + assert decrypt_secret(account.password_cipher) == QR_PASSWORD_MARK + stored = json.loads(decrypt_secret(account.credential_cipher)) + assert stored["ucs_token"] == "ucs-qr" + assert stored["yxt_token"] == "yxt-qr" + assert "secret" not in decrypt_secret(account.password_cipher) diff --git a/web/src/features/auth/LoginView.vue b/web/src/features/auth/LoginView.vue index fc81b5e..42ef426 100644 --- a/web/src/features/auth/LoginView.vue +++ b/web/src/features/auth/LoginView.vue @@ -1,5 +1,5 @@