feat: 登录后进入实时首页,并加密保存可刷新的登录凭证
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
"""登录接口。本地只保存工号和加密密码。"""
|
||||
"""登录接口。本地保存工号、加密密码和加密后的登录凭证。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -11,7 +11,7 @@ from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.db import get_db, init_db
|
||||
from euniv.service import list_accounts, login_and_store
|
||||
from euniv.service import fetch_home, login_and_store
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -43,9 +43,12 @@ def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
|
||||
return {"employee_id": employee_id}
|
||||
|
||||
|
||||
@app.get("/api/accounts")
|
||||
def accounts(db: Session = Depends(get_db)) -> list[dict]:
|
||||
return [{"employee_id": item.employee_id} for item in list_accounts(db)]
|
||||
@app.get("/api/home")
|
||||
def home(employee_id: str, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return fetch_home(db, employee_id.strip())
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
_dist = Path(__file__).resolve().parents[2] / "web" / "dist"
|
||||
|
||||
@@ -76,11 +76,17 @@ def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
|
||||
return best_x
|
||||
|
||||
|
||||
class SessionExpired(RuntimeError):
|
||||
"""学习平台凭证失效,需要重新登录。"""
|
||||
|
||||
|
||||
class EunivClient:
|
||||
def __init__(self, login_name: str, password: str) -> None:
|
||||
self.login_name = login_name.strip()
|
||||
self.password = password
|
||||
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
|
||||
self._profile: dict = {}
|
||||
self._yxt_token = ""
|
||||
|
||||
def close(self) -> None:
|
||||
self.client.close()
|
||||
@@ -220,14 +226,72 @@ class EunivClient:
|
||||
if code != "0000" or not isinstance(redirect_url, str):
|
||||
raise RuntimeError(f"申请学习平台授权码失败:{message}")
|
||||
self.client.get(redirect_url, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT})
|
||||
self._profile = {
|
||||
"token": str(profile.get("token") or ""),
|
||||
"accountId": account_id,
|
||||
"userId": user_id,
|
||||
"ssoinfo": str(profile.get("ssoinfo") or ""),
|
||||
"unionId": str(profile.get("unionId") or ""),
|
||||
}
|
||||
self._yxt_token = ""
|
||||
self.session_token()
|
||||
|
||||
def export_credential(self) -> dict:
|
||||
profile = self._profile
|
||||
return {
|
||||
"ucs_token": str(profile.get("token") or ""),
|
||||
"ucs_account_id": str(profile.get("accountId") or ""),
|
||||
"ucs_user_id": str(profile.get("userId") or ""),
|
||||
"ucs_ssoinfo": str(profile.get("ssoinfo") or ""),
|
||||
"ucs_union_id": str(profile.get("unionId") or ""),
|
||||
"yxt_token": self.session_token(),
|
||||
}
|
||||
|
||||
def restore(self, credential: dict) -> None:
|
||||
self._profile = {
|
||||
"token": str(credential.get("ucs_token") or ""),
|
||||
"accountId": str(credential.get("ucs_account_id") or ""),
|
||||
"userId": str(credential.get("ucs_user_id") or ""),
|
||||
"ssoinfo": str(credential.get("ucs_ssoinfo") or ""),
|
||||
"unionId": str(credential.get("ucs_union_id") or ""),
|
||||
}
|
||||
token = str(credential.get("yxt_token") or "")
|
||||
self._yxt_token = token
|
||||
if token:
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/")
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain=".yunxuetang.cn", path="/")
|
||||
|
||||
def session_token(self) -> str:
|
||||
for cookie in self.client.cookies.jar:
|
||||
if cookie.name == "ELEARNING_00024" and cookie.value:
|
||||
self._yxt_token = cookie.value
|
||||
return cookie.value
|
||||
if self._yxt_token:
|
||||
return self._yxt_token
|
||||
names = sorted({cookie.name for cookie in self.client.cookies.jar})
|
||||
raise RuntimeError("学习平台没有返回登录会话,现有 Cookie 名称:" + ", ".join(names))
|
||||
|
||||
def _request(self, method: str, url: str, **kwargs) -> httpx.Response:
|
||||
headers = self.api_headers()
|
||||
extra = kwargs.pop("headers", None)
|
||||
if extra:
|
||||
headers.update(extra)
|
||||
response = self.client.request(method, url, headers=headers, **kwargs)
|
||||
refreshed = response.headers.get("token") or response.headers.get("Token")
|
||||
if refreshed:
|
||||
self._yxt_token = refreshed
|
||||
self.client.cookies.set("ELEARNING_00024", refreshed, domain="euniv.zte.com.cn", path="/")
|
||||
for cookie in self.client.cookies.jar:
|
||||
if cookie.name == "ELEARNING_00024" and cookie.value:
|
||||
self._yxt_token = cookie.value
|
||||
if response.status_code in (401, 403):
|
||||
raise SessionExpired("学习平台登录已失效")
|
||||
if response.headers.get("content-type", "").startswith("application/json"):
|
||||
payload = response.json()
|
||||
if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}:
|
||||
raise SessionExpired("学习平台登录已失效")
|
||||
return response
|
||||
|
||||
def user_info(self) -> dict:
|
||||
response = self.client.post(
|
||||
f"{YXT_API}/v1/customdiy/user/getuserinfobyid",
|
||||
@@ -292,6 +356,63 @@ class EunivClient:
|
||||
"class_count": class_count,
|
||||
}
|
||||
|
||||
def home_snapshot(self) -> dict:
|
||||
"""实时读取首页要展示的个人信息,调用方不得把结果写入数据库。"""
|
||||
info_resp = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
|
||||
info = info_resp.json()
|
||||
if not isinstance(info, dict) or "cnName" not in info:
|
||||
raise RuntimeError("用户信息返回无法识别")
|
||||
|
||||
period_resp = self._request("GET", f"{STUDY_API}/v1/frw/user/info")
|
||||
period = period_resp.json()
|
||||
if not isinstance(period, dict) or "yearScores" not in period:
|
||||
raise RuntimeError("本年和本月学分返回无法识别")
|
||||
|
||||
score_resp = self._request("POST", f"{YXT_API}/v1/customapiforweb/getscoreorpointorhour", json={})
|
||||
score_payload = score_resp.json()
|
||||
score = score_payload.get("data") or {}
|
||||
if score_payload.get("code") not in (None, "0", 0):
|
||||
raise RuntimeError(score_payload.get("message") or "学时学分查询失败")
|
||||
|
||||
today_resp = self._request("GET", f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours")
|
||||
today = today_resp.json()
|
||||
|
||||
exam_resp = self._request("POST", f"{YXT_API}/v1/user/getmyexamcountnew", content=b"")
|
||||
exam_payload = exam_resp.json()
|
||||
exam = exam_payload.get("data") or {}
|
||||
pending_count = int(exam.get("preExamCount") or 0)
|
||||
return {
|
||||
"name": info.get("cnName") or "",
|
||||
"avatar": info.get("headPictureUrl") or "",
|
||||
"department": info.get("departmentName") or "",
|
||||
"level": period.get("levelName") or info.get("userClassLevelName") or "",
|
||||
"year_score": period.get("yearScores") or "0.00",
|
||||
"month_score": period.get("monthScores") or "0.00",
|
||||
"total_hours": score.get("actualStudyHour") or "",
|
||||
"total_score": score.get("actualStudyScore") or period.get("totalScores") or "",
|
||||
"today_hours": today.get("studyHours"),
|
||||
"today_score": today.get("studyScore"),
|
||||
"pending_exam_count": pending_count,
|
||||
"pending_exams": self._pending_exams(pending_count),
|
||||
}
|
||||
|
||||
def _pending_exams(self, count: int) -> list[dict]:
|
||||
if count <= 0:
|
||||
return []
|
||||
response = self._request(
|
||||
"GET",
|
||||
f"{EUNIV}/exam/userallexam.htm",
|
||||
headers={"Accept": "text/html,application/xhtml+xml"},
|
||||
)
|
||||
names = []
|
||||
for match in response.text.split("lblExamName"):
|
||||
if ">" not in match:
|
||||
continue
|
||||
text = match.split(">", 1)[1].split("<", 1)[0].strip()
|
||||
if text:
|
||||
names.append(text)
|
||||
return [{"name": name, "deadline": ""} for name in names]
|
||||
|
||||
def open_session(self) -> dict:
|
||||
profile = self.login()
|
||||
self.authorize(profile)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""本地只保存工号和加密后的密码。"""
|
||||
"""本地保存工号、加密密码和加密后的登录凭证。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,3 +15,4 @@ class Account(Base):
|
||||
|
||||
employee_id: Mapped[str] = mapped_column(String(32), primary_key=True)
|
||||
password_cipher: Mapped[str] = mapped_column(Text)
|
||||
credential_cipher: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
@@ -1,34 +1,63 @@
|
||||
"""校验 e 学登录,并只把工号和加密密码写入本地库。"""
|
||||
"""校验 e 学登录。本地只保存工号、加密密码和加密后的登录凭证。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import select
|
||||
import json
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.client import EunivClient
|
||||
from euniv.client import EunivClient, SessionExpired
|
||||
from euniv.crypto import decrypt_secret, encrypt_secret
|
||||
from euniv.models import Account
|
||||
|
||||
|
||||
def _dump(credential: dict) -> str:
|
||||
return json.dumps(credential, ensure_ascii=False, sort_keys=True)
|
||||
|
||||
|
||||
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> Account:
|
||||
client = client_factory(employee_id, password)
|
||||
try:
|
||||
client.login()
|
||||
profile = client.login()
|
||||
client.authorize(profile)
|
||||
credential = client.export_credential()
|
||||
finally:
|
||||
client.close()
|
||||
account = db.get(Account, employee_id)
|
||||
if account is None:
|
||||
account = Account(employee_id=employee_id, password_cipher=encrypt_secret(password))
|
||||
account = Account(employee_id=employee_id, password_cipher="", credential_cipher="")
|
||||
db.add(account)
|
||||
else:
|
||||
account.password_cipher = encrypt_secret(password)
|
||||
account.password_cipher = encrypt_secret(password)
|
||||
account.credential_cipher = encrypt_secret(_dump(credential))
|
||||
db.commit()
|
||||
db.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
def list_accounts(db: Session) -> list[Account]:
|
||||
return list(db.scalars(select(Account).order_by(Account.employee_id)))
|
||||
def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
|
||||
"""向 e 学现查首页信息。个人信息只出现在返回值里,不写入数据库。凭证变化时更新密文。"""
|
||||
account = db.get(Account, employee_id)
|
||||
if account is None:
|
||||
raise RuntimeError("请先登录")
|
||||
credential = json.loads(decrypt_secret(account.credential_cipher)) if account.credential_cipher else {}
|
||||
client = client_factory(employee_id, decrypt_secret(account.password_cipher))
|
||||
try:
|
||||
if credential.get("yxt_token"):
|
||||
client.restore(credential)
|
||||
else:
|
||||
client.authorize(client.login())
|
||||
try:
|
||||
data = client.home_snapshot()
|
||||
except SessionExpired:
|
||||
client.authorize(client.login())
|
||||
data = client.home_snapshot()
|
||||
updated = client.export_credential()
|
||||
if _dump(updated) != _dump(credential):
|
||||
account.credential_cipher = encrypt_secret(_dump(updated))
|
||||
db.commit()
|
||||
return data
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
def stored_password(account: Account) -> str:
|
||||
|
||||
Reference in New Issue
Block a user