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
+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: