feat: 对接 UAC 登录并支持 iCenter 扫码
This commit is contained in:
+217
-84
@@ -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 ""),
|
||||
|
||||
Reference in New Issue
Block a user