65 lines
2.2 KiB
Python
65 lines
2.2 KiB
Python
"""校验 e 学登录。本地只保存工号、加密密码和加密后的登录凭证。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
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:
|
|
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="", credential_cipher="")
|
|
db.add(account)
|
|
account.password_cipher = encrypt_secret(password)
|
|
account.credential_cipher = encrypt_secret(_dump(credential))
|
|
db.commit()
|
|
db.refresh(account)
|
|
return account
|
|
|
|
|
|
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:
|
|
return decrypt_secret(account.password_cipher)
|