feat: 保持浏览器登录,并显示我的学时里的本月学时

This commit is contained in:
2026-10-27 04:52:39 +08:00
parent afda5a883f
commit 7bbb80ee9c
10 changed files with 318 additions and 35 deletions
+52 -9
View File
@@ -2,22 +2,29 @@
from __future__ import annotations
import os
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import Depends, FastAPI, HTTPException
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from euniv.db import get_db, init_db
from euniv.service import fetch_home, login_and_store, submit_jigsaw
from euniv.service import fetch_home, login_and_store, revoke_credential, start_credential_refresh, submit_jigsaw
from euniv.session import clear_session, read_employee_id, write_session
@asynccontextmanager
async def lifespan(_app: FastAPI):
init_db()
stop = None
if os.environ.get("EUNIV_DISABLE_REFRESH") != "1":
stop = start_credential_refresh()
yield
if stop is not None:
stop.set()
app = FastAPI(title="EunivTools", lifespan=lifespan)
@@ -26,6 +33,7 @@ app = FastAPI(title="EunivTools", lifespan=lifespan)
class LoginBody(BaseModel):
employee_id: str = Field(min_length=1, max_length=32)
password: str = Field(min_length=1, max_length=128)
manual_jigsaw: bool = False
class JigsawBody(BaseModel):
@@ -38,27 +46,62 @@ def health() -> dict:
return {"ok": True}
def _open_session(response: Response, payload: dict) -> dict:
employee_id = payload.get("employee_id")
if employee_id:
write_session(response, employee_id)
return payload
@app.get("/api/session")
def session(request: Request) -> dict:
employee_id = read_employee_id(request.cookies)
if not employee_id:
raise HTTPException(status_code=401, detail="未登录")
return {"employee_id": employee_id}
@app.post("/api/login")
def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
employee_id = body.employee_id.strip()
def login(body: LoginBody, response: Response, db: Session = Depends(get_db)) -> dict:
try:
return login_and_store(db, employee_id, body.password)
payload = login_and_store(db, body.employee_id.strip(), body.password, manual=body.manual_jigsaw)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return _open_session(response, payload)
@app.post("/api/login/jigsaw")
def login_jigsaw(body: JigsawBody, db: Session = Depends(get_db)) -> dict:
def login_jigsaw(body: JigsawBody, response: Response, db: Session = Depends(get_db)) -> dict:
try:
return submit_jigsaw(db, body.attempt_id, body.offset)
payload = submit_jigsaw(db, body.attempt_id, body.offset)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return _open_session(response, payload)
@app.post("/api/logout")
def logout(response: Response) -> dict:
clear_session(response)
return {"ok": True}
@app.post("/api/revoke")
def revoke(request: Request, response: Response, db: Session = Depends(get_db)) -> dict:
employee_id = read_employee_id(request.cookies)
if not employee_id:
raise HTTPException(status_code=401, detail="未登录")
revoke_credential(db, employee_id)
clear_session(response)
return {"ok": True}
@app.get("/api/home")
def home(employee_id: str, db: Session = Depends(get_db)) -> dict:
def home(request: Request, db: Session = Depends(get_db)) -> dict:
employee_id = read_employee_id(request.cookies)
if not employee_id:
raise HTTPException(status_code=401, detail="未登录")
try:
return fetch_home(db, employee_id.strip())
return fetch_home(db, employee_id)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+34 -1
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import base64
import io
import random
import re
import time
import uuid
from urllib.parse import quote
@@ -134,7 +135,7 @@ class EunivClient:
block = payload.get("code") or {}
return block.get("code") or "", block.get("msg") or "", payload.get("bo")
def login(self) -> dict:
def login(self, manual: bool = False) -> dict:
self.client.get(EUNIV + "/")
self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate",
@@ -168,6 +169,9 @@ class EunivClient:
raise RuntimeError(f"安全码检查失败:{check_message}")
self._cipher = encrypt_password(public_key, self.password)
if manual:
self._load_jigsaw()
raise ManualJigsaw(self.current_puzzle())
for _ in range(3):
big, small, top = self._load_jigsaw()
try:
@@ -441,8 +445,37 @@ class EunivClient:
"today_score": today.get("studyScore"),
"pending_exam_count": pending_count,
"pending_exams": self._pending_exams(pending_count),
"month_hours": self._month_study_hours(),
}
def _month_study_hours(self) -> str:
text = self._study_period_page()
match = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', text)
return match.group(1) if match else ""
def _study_period_page(self) -> str:
response = self.client.get(
f"{EUNIV}/study/myperiod.htm",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
)
if "spMonthlyPeriod" in response.text:
return response.text
if self._profile.get("token"):
self.authorize(self._profile)
response = self.client.get(
f"{EUNIV}/study/myperiod.htm",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
)
return response.text
def credential_alive(self) -> bool:
try:
response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
except SessionExpired:
return False
payload = response.json()
return isinstance(payload, dict) and bool(payload.get("cnName"))
def _pending_exams(self, count: int) -> list[dict]:
if count <= 0:
return []
+70 -2
View File
@@ -4,9 +4,11 @@ from __future__ import annotations
import json
import secrets
import threading
import time
from dataclasses import dataclass
from sqlalchemy import select
from sqlalchemy.orm import Session
from euniv.client import EunivClient, JigsawRejected, ManualJigsaw, SessionExpired
@@ -55,14 +57,24 @@ def _persist(db: Session, employee_id: str, password: str, client: EunivClient,
db.commit()
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> dict:
def login_and_store(
db: Session,
employee_id: str,
password: str,
client_factory=EunivClient,
manual: bool = False,
) -> dict:
_purge_pending()
account = db.get(Account, employee_id)
if account and account.password_cipher and account.credential_cipher:
if decrypt_secret(account.password_cipher) == password and _credential_still_valid(account, client_factory):
return {"employee_id": employee_id}
_drop_employee(employee_id)
client = client_factory(employee_id, password)
held = False
try:
try:
profile = client.login()
profile = client.login(manual=manual)
except ManualJigsaw as exc:
attempt_id = secrets.token_urlsafe(18)
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
@@ -75,6 +87,17 @@ def login_and_store(db: Session, employee_id: str, password: str, client_factory
client.close()
def _credential_still_valid(account: Account, client_factory) -> bool:
client = client_factory(account.employee_id, decrypt_secret(account.password_cipher))
try:
client.restore(json.loads(decrypt_secret(account.credential_cipher)))
return bool(client.credential_alive())
except Exception:
return False
finally:
client.close()
def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
_purge_pending()
pending = _pending.get(attempt_id)
@@ -129,5 +152,50 @@ def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dic
client.close()
def revoke_credential(db: Session, employee_id: str) -> None:
account = db.get(Account, employee_id)
if account is None:
return
account.credential_cipher = ""
db.commit()
def refresh_stored_credentials(client_factory=EunivClient) -> None:
from euniv.db import SessionLocal
with SessionLocal() as db:
accounts = list(db.scalars(select(Account)))
for account in accounts:
if not account.credential_cipher:
continue
client = client_factory(account.employee_id, decrypt_secret(account.password_cipher))
try:
previous = json.loads(decrypt_secret(account.credential_cipher))
client.restore(previous)
if client.credential_alive():
updated = client.export_credential()
if _dump(updated) != _dump(previous):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
continue
profile = client.login()
_persist(db, account.employee_id, decrypt_secret(account.password_cipher), client, profile)
except Exception:
continue
finally:
client.close()
def start_credential_refresh(interval_seconds: int = 1800) -> threading.Event:
stop = threading.Event()
def loop() -> None:
while not stop.wait(interval_seconds):
refresh_stored_credentials()
threading.Thread(target=loop, name="euniv-credential-refresh", daemon=True).start()
return stop
def stored_password(account: Account) -> str:
return decrypt_secret(account.password_cipher)
+37
View File
@@ -0,0 +1,37 @@
"""浏览器登录状态。只标识是谁,不存放 e 学凭证。"""
from __future__ import annotations
from fastapi import Response
from euniv.crypto import decrypt_secret, encrypt_secret
COOKIE_NAME = "euniv_session"
MAX_AGE = 30 * 24 * 60 * 60
def read_employee_id(cookies) -> str | None:
raw = cookies.get(COOKIE_NAME)
if not raw:
return None
try:
employee_id = decrypt_secret(raw)
except Exception:
return None
employee_id = employee_id.strip()
return employee_id or None
def write_session(response: Response, employee_id: str) -> None:
response.set_cookie(
COOKIE_NAME,
encrypt_secret(employee_id),
max_age=MAX_AGE,
httponly=True,
samesite="lax",
path="/",
)
def clear_session(response: Response) -> None:
response.delete_cookie(COOKIE_NAME, path="/")
+1
View File
@@ -8,3 +8,4 @@ _root = _backend.parent / "Temp" / "pytest"
_root.mkdir(parents=True, exist_ok=True)
os.environ["EUNIV_SECRET_KEY"] = "test-secret-key"
os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db")
os.environ["EUNIV_DISABLE_REFRESH"] = "1"
+67 -7
View File
@@ -25,9 +25,22 @@ class FakeClient:
def close(self) -> None:
return None
def login(self) -> dict:
def login(self, manual: bool = False) -> dict:
if manual:
raise ManualJigsaw({
"big_img": "data:image/png;base64,YQ==",
"small_img": "data:image/png;base64,Yg==",
"y": 56,
"width": 280,
"height": 172,
"piece_width": 48,
"piece_height": 48,
})
return dict(self._profile)
def credential_alive(self) -> bool:
return True
def authorize(self, profile: dict) -> None:
self._profile = dict(profile)
@@ -82,8 +95,8 @@ 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.login_and_store = lambda db, employee_id, password, manual=False: service_module.login_and_store(
db, employee_id, password, FakeClient, manual=manual
)
api_module.fetch_home = lambda db, employee_id: service_module.fetch_home(db, employee_id, FakeClient)
client = TestClient(api_module.app)
@@ -99,7 +112,7 @@ def test_login_stores_password_and_credential_only() -> None:
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"})
home = client.get("/api/home")
assert home.status_code == 200
body = home.json()
assert body["name"] == "测试用户"
@@ -134,7 +147,7 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
def close(self) -> None:
return None
def login(self) -> dict:
def login(self, manual: bool = False) -> dict:
raise ManualJigsaw({
"big_img": "data:image/png;base64,YQ==",
"small_img": "data:image/png;base64,Yg==",
@@ -174,8 +187,8 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
"yxt_token": "yxt-manual",
}
api_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store(
db, employee_id, password, ManualClient
api_module.login_and_store = lambda db, employee_id, password, manual=False: service_module.login_and_store(
db, employee_id, password, ManualClient, manual=manual
)
api_module.submit_jigsaw = service_module.submit_jigsaw
client = TestClient(api_module.app)
@@ -200,3 +213,50 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
account = db.get(Account, "6650000146")
assert account is not None
assert decrypt_secret(account.password_cipher) == "secret-pass"
def test_browser_session_logout_and_revoke() -> None:
import euniv.api as api_module
import euniv.service as service_module
calls = {"login": 0}
class RememberClient(FakeClient):
def login(self, manual: bool = False) -> dict:
calls["login"] += 1
return super().login(manual=manual)
api_module.login_and_store = lambda db, employee_id, password, manual=False: service_module.login_and_store(
db, employee_id, password, RememberClient, manual=manual
)
client = TestClient(api_module.app)
first = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert first.status_code == 200
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
before = decrypt_secret(account.credential_cipher)
second = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert second.json() == {"employee_id": "6650000146"}
assert calls["login"] == 1
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
assert decrypt_secret(account.credential_cipher) == before
assert client.get("/api/session").json() == {"employee_id": "6650000146"}
assert client.post("/api/logout").status_code == 200
assert client.get("/api/session").status_code == 401
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
assert account.credential_cipher
again = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert again.status_code == 200
assert calls["login"] == 1
assert client.post("/api/revoke").status_code == 200
assert client.get("/api/session").status_code == 401
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
assert account.credential_cipher == ""
assert decrypt_secret(account.password_cipher) == "secret-pass"