feat: 登录后进入实时首页,并加密保存可刷新的登录凭证

This commit is contained in:
2026-10-26 18:12:00 +08:00
parent eaad01d5a8
commit 91707f959f
14 changed files with 748 additions and 136 deletions
@@ -0,0 +1,19 @@
"""保存加密后的登录凭证。"""
from alembic import op
import sqlalchemy as sa
revision = "0003_credentials"
down_revision = "0002_accounts_only"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.add_column(sa.Column("credential_cipher", sa.Text(), nullable=False, server_default=""))
def downgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.drop_column("credential_cipher")
+8 -5
View File
@@ -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"
+121
View File
@@ -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)
+2 -1
View File
@@ -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="")
+38 -9
View File
@@ -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:
+71 -5
View File
@@ -1,3 +1,5 @@
import json
from fastapi.testclient import TestClient
from sqlalchemy import text
@@ -10,12 +12,61 @@ class FakeClient:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name
self.password = password
self._token = "yxt-1"
self._profile = {
"token": "ucs-1",
"accountId": login_name,
"userId": "u1",
"ssoinfo": "sso",
"unionId": "",
}
def close(self) -> None:
return None
def login(self) -> dict:
return {"accountId": self.login_name}
return dict(self._profile)
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": self._profile["ssoinfo"],
"ucs_union_id": self._profile["unionId"],
"yxt_token": self._token,
}
def restore(self, credential: dict) -> None:
self._token = credential["yxt_token"]
self._profile = {
"token": credential["ucs_token"],
"accountId": credential["ucs_account_id"],
"userId": credential["ucs_user_id"],
"ssoinfo": credential["ucs_ssoinfo"],
"unionId": credential["ucs_union_id"],
}
def home_snapshot(self) -> dict:
if self._token == "yxt-1":
self._token = "yxt-2"
return {
"name": "测试用户",
"avatar": "https://example.test/a.jpg",
"department": "测试部门",
"level": "Scientist",
"year_score": "1.00",
"month_score": "0.20",
"total_hours": "10",
"total_score": "3.00",
"today_hours": "1",
"today_score": "0.10",
"pending_exam_count": 1,
"pending_exams": [{"name": "安全考试", "deadline": ""}],
}
def setup_function() -> None:
@@ -26,21 +77,36 @@ def setup_function() -> None:
init_db()
def test_login_stores_only_employee_id_and_password() -> None:
def test_login_stores_password_and_credential_only() -> None:
import euniv.api as api_module
import euniv.service as service_module
api_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store(
db, employee_id, password, FakeClient
)
api_module.fetch_home = lambda db, employee_id: service_module.fetch_home(db, employee_id, FakeClient)
client = TestClient(api_module.app)
response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert response.status_code == 200
assert response.json() == {"employee_id": "6650000146"}
listed = client.get("/api/accounts").json()
assert listed == [{"employee_id": "6650000146"}]
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
assert decrypt_secret(account.password_cipher) == "secret-pass"
assert set(account.__table__.columns.keys()) == {"employee_id", "password_cipher"}
stored = json.loads(decrypt_secret(account.credential_cipher))
assert stored["yxt_token"] == "yxt-1"
assert stored["ucs_token"] == "ucs-1"
assert set(account.__table__.columns.keys()) == {"employee_id", "password_cipher", "credential_cipher"}
home = client.get("/api/home", params={"employee_id": "6650000146"})
assert home.status_code == 200
body = home.json()
assert body["name"] == "测试用户"
assert body["pending_exams"] == [{"name": "安全考试", "deadline": ""}]
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
updated = json.loads(decrypt_secret(account.credential_cipher))
assert updated["yxt_token"] == "yxt-2"
assert "测试用户" not in decrypt_secret(account.credential_cipher)
assert "测试用户" not in decrypt_secret(account.password_cipher)