feat: 保持浏览器登录,并显示我的学时里的本月学时
This commit is contained in:
+52
-9
@@ -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
@@ -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 []
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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="/")
|
||||
Reference in New Issue
Block a user