fix: 清掉无用接口和样式,并收紧登录与工号边界

This commit is contained in:
2026-11-16 11:30:59 +08:00
parent 7381b49e4c
commit 5b83b7e415
15 changed files with 232 additions and 329 deletions
+85 -60
View File
@@ -45,45 +45,43 @@ from euniv.service import (
)
from euniv.session import clear_session, write_session
from pydantic import BaseModel as _BaseModel
class MonthlyTargetBody(BaseModel):
monthly_target: int = Field(strict=True)
class MonthlyTargetBody(_BaseModel):
monthly_target: int
class ProxyBody(BaseModel):
scheme: str = Field(min_length=1, max_length=16)
host: str = Field(default="", max_length=255)
port: int | None = Field(default=None, ge=1, le=65535)
username: str = Field(default="", max_length=128)
password: str | None = Field(default=None, max_length=128)
class ProxyBody(_BaseModel):
scheme: str
host: str = ""
port: int | None = None
username: str = ""
password: str | None = None
class StudyStartBody(_BaseModel):
day: int
hour: int
minute: int
second: int
class StudyStartBody(BaseModel):
day: int = Field(strict=True)
hour: int = Field(strict=True)
minute: int = Field(strict=True)
second: int = Field(strict=True)
enabled: bool | None = None
class CourseWorkersBody(_BaseModel):
workers: int
class CourseWorkersBody(BaseModel):
workers: int = Field(strict=True)
class StudyBundleBody(_BaseModel):
monthly_target: int
day: int
hour: int
minute: int
second: int
class StudyBundleBody(BaseModel):
monthly_target: int = Field(strict=True)
day: int = Field(strict=True)
hour: int = Field(strict=True)
minute: int = Field(strict=True)
second: int = Field(strict=True)
enabled: bool = True
workers: int
workers: int = Field(strict=True)
class StudyControlBody(_BaseModel):
action: str
class StudyControlBody(BaseModel):
action: str = Field(min_length=1, max_length=16)
@asynccontextmanager
@@ -462,21 +460,6 @@ def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db))
return view_of(account)
@app.delete("/api/settings/proxy")
def delete_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.proxy import clear, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
clear(account)
db.commit()
from euniv.autostudy import restart_work
restart_work(account.employee_id)
return view_of(account)
@app.get("/api/settings/study-control")
def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.autostudy import autostudy_status
@@ -528,33 +511,61 @@ def post_study_control(body: StudyControlBody, request: Request, db: Session = D
return get_study_control(request, db)
def _same_origin(websocket: WebSocket) -> bool:
origin = websocket.headers.get("origin", "")
if not origin:
return True
from urllib.parse import urlparse
origin_host = (urlparse(origin).hostname or "").lower()
request_host = websocket.headers.get("host", "").split(":")[0].strip("[]").lower()
return bool(origin_host) and origin_host == request_host
def _ws_gate(cookies: dict) -> tuple[int, str]:
from euniv.db import SessionLocal
from euniv.session import COOKIE_NAME, open_seal, still_valid
with SessionLocal() as db:
if admin_session_active(cookies, load_config(db).admin_sessions_valid_after):
return 4403, ""
opened = open_seal(cookies.get(COOKIE_NAME, ""), "user")
if opened is None:
return 4401, ""
employee_id, issued = opened
account = db.get(Account, employee_id)
if account is None or not still_valid(issued, account.sessions_valid_after):
return 4401, ""
return 0, employee_id
@app.websocket("/api/settings/study-control/ws")
async def study_control_ws(websocket: WebSocket):
from euniv.study_control import payload_for
from euniv.study_push import register, unregister
if not _same_origin(websocket):
await websocket.close(code=4403)
return
await websocket.accept()
from euniv.db import SessionLocal
from euniv.session import COOKIE_NAME, open_seal, still_valid
with SessionLocal() as db:
if admin_session_active(websocket.cookies, load_config(db).admin_sessions_valid_after):
await websocket.close(code=4403)
return
opened = open_seal(websocket.cookies.get(COOKIE_NAME, ""), "user")
if opened is None:
await websocket.close(code=4401)
return
employee_id, issued = opened
account = db.get(Account, employee_id)
if account is None or not still_valid(issued, account.sessions_valid_after):
await websocket.close(code=4401)
return
code, employee_id = await asyncio.to_thread(_ws_gate, dict(websocket.cookies))
if code:
await websocket.close(code=code)
return
register(employee_id, websocket)
last_message = 0.0
try:
await websocket.send_json(await asyncio.to_thread(payload_for, employee_id))
while True:
await websocket.receive_text()
message = await websocket.receive()
if message.get("type") == "websocket.disconnect":
break
if "text" not in message:
continue
now = asyncio.get_running_loop().time()
if now - last_message < 1:
continue
last_message = now
await websocket.send_json(await asyncio.to_thread(payload_for, employee_id))
except WebSocketDisconnect:
pass
@@ -578,6 +589,20 @@ def training_detail(path: str, request: Request, db: Session = Depends(get_db))
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.api_route("/api", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"])
@app.api_route("/api/{rest:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"])
def api_fallback(rest: str = "") -> None:
raise HTTPException(status_code=405, detail="不支持该请求")
class _WebFiles(StaticFiles):
async def get_response(self, path: str, scope):
response = await super().get_response(path, scope)
if path in {"", "index.html"}:
response.headers["Cache-Control"] = "no-cache"
return response
_dist = Path(__file__).resolve().parents[2] / "web" / "dist"
if _dist.is_dir():
app.mount("/", StaticFiles(directory=_dist, html=True), name="web")
app.mount("/", _WebFiles(directory=_dist, html=True), name="web")
+1 -2
View File
@@ -165,7 +165,7 @@ def _cool_failed_sync(employee_id: str, *, invalid: bool = False) -> None:
with SessionLocal() as db:
sync = db.get(CourseSync, 1)
if sync is None:
sync = CourseSync(id=1, last_employee_id=employee_id, course_count=0)
sync = CourseSync(id=1, last_employee_id=employee_id)
db.add(sync)
sync.last_employee_id = employee_id
sync.next_allowed_at = datetime.now(timezone.utc) + timedelta(minutes=30)
@@ -231,7 +231,6 @@ def _fetch_and_store(trigger: str) -> bool:
sync.last_employee_id = employee_id
sync.finished_at = datetime.now(timezone.utc)
sync.next_allowed_at = sync.finished_at + next_gap()
sync.course_count = len(courses)
db.commit()
from euniv.autostudy import clear_study_hold, request_wake
+2 -3
View File
@@ -30,10 +30,9 @@ class CourseSync(Base):
__tablename__ = "course_sync"
id: Mapped[int] = mapped_column(primary_key=True)
last_employee_id: Mapped[str] = mapped_column(String(32), nullable=False, default="")
last_employee_id: Mapped[str] = mapped_column(String(64), nullable=False, default="")
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
next_allowed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
course_count: Mapped[int] = mapped_column(nullable=False, default=0)
class FinishedCourse(Base):
@@ -50,7 +49,7 @@ class FinishedCourse(Base):
class Account(Base):
__tablename__ = "accounts"
employee_id: Mapped[str] = mapped_column(String(32), primary_key=True)
employee_id: Mapped[str] = mapped_column(String(64), primary_key=True)
password_cipher: Mapped[str] = mapped_column(Text)
credential_cipher: Mapped[str] = mapped_column(Text, default="")
refresh_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
+55 -27
View File
@@ -32,6 +32,8 @@ _pending: dict[str, "PendingLogin"] = {}
_pending_qr: dict[str, "PendingQr"] = {}
_credential_guard = threading.Lock()
_credential_locks: dict[str, threading.Lock] = {}
_pending_guard = threading.RLock()
_pending_busy: set[str] = set()
def _credential_lock(employee_id: str) -> threading.Lock:
@@ -43,6 +45,11 @@ def _credential_lock(employee_id: str) -> threading.Lock:
return lock
def release_credential_lock(employee_id: str) -> None:
with _credential_guard:
_credential_locks.pop((employee_id or "").strip(), None)
@dataclass
class PendingLogin:
client: EunivClient
@@ -80,27 +87,40 @@ def start_pending_cleaner() -> None:
def _purge_pending() -> None:
now = time.time()
for attempt_id, pending in list(_pending.items()):
if now - pending.created > _PENDING_SECONDS:
with _pending_guard:
for attempt_id, pending in list(_pending.items()):
if attempt_id in _pending_busy or now - pending.created <= _PENDING_SECONDS:
continue
pending.client.close()
_pending.pop(attempt_id, None)
for attempt_id, pending in list(_pending_qr.items()):
if now - pending.created > _QR_SECONDS:
for attempt_id, pending in list(_pending_qr.items()):
if attempt_id in _pending_busy or now - pending.created <= _QR_SECONDS:
continue
pending.client.close()
_pending_qr.pop(attempt_id, None)
def _drop_qr(attempt_id: str) -> None:
pending = _pending_qr.pop(attempt_id, None)
with _pending_guard:
pending = _pending_qr.pop(attempt_id, None)
if pending is not None:
pending.client.close()
def _drop_employee(employee_id: str) -> None:
for attempt_id, pending in list(_pending.items()):
if pending.employee_id == employee_id:
pending.client.close()
_pending.pop(attempt_id, None)
closing = []
with _pending_guard:
for attempt_id, pending in list(_pending.items()):
if pending.employee_id == employee_id and attempt_id not in _pending_busy:
closing.append(pending)
_pending.pop(attempt_id, None)
for pending in closing:
pending.client.close()
def _release_pending(attempt_id: str) -> None:
with _pending_guard:
_pending_busy.discard(attempt_id)
def _persist(db: Session, employee_id: str, password: str | None, client: EunivClient, profile: dict) -> None:
@@ -221,7 +241,8 @@ def login_and_store(
profile = client.login(manual=manual, auto_attempts=auto_attempts)
except ManualJigsaw as exc:
attempt_id = secrets.token_urlsafe(18)
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
with _pending_guard:
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
held = True
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
except Exception as exc:
@@ -265,7 +286,10 @@ def _credential_still_valid(account: Account, client_factory) -> bool:
def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
_purge_pending()
pending = _pending.get(attempt_id)
with _pending_guard:
pending = _pending.get(attempt_id)
if pending is not None:
_pending_busy.add(attempt_id)
if pending is None:
raise RuntimeError("请重新登录")
try:
@@ -273,16 +297,21 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
except JigsawRejected:
pending.tries += 1
if pending.tries >= 5:
_pending.pop(attempt_id, None)
with _pending_guard:
_pending.pop(attempt_id, None)
pending.client.close()
raise RuntimeError("请重新登录")
pending.created = time.time()
return {"attempt_id": attempt_id, "jigsaw": pending.client.next_jigsaw()}
except Exception:
_pending.pop(attempt_id, None)
with _pending_guard:
_pending.pop(attempt_id, None)
pending.client.close()
raise
_pending.pop(attempt_id, None)
finally:
_release_pending(attempt_id)
with _pending_guard:
_pending.pop(attempt_id, None)
try:
resolved = _resolved_id(profile, pending.employee_id)
_persist(db, resolved, pending.password, pending.client, profile)
@@ -303,13 +332,17 @@ def start_qr_login(client_factory=EunivClient) -> dict:
client.close()
raise
attempt_id = secrets.token_urlsafe(18)
_pending_qr[attempt_id] = PendingQr(client, time.time())
with _pending_guard:
_pending_qr[attempt_id] = PendingQr(client, time.time())
return {"attempt_id": attempt_id, "qr_image": image, "ttl": 60}
def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> dict:
def poll_qr_login(db: Session, attempt_id: str) -> dict:
_purge_pending()
pending = _pending_qr.get(attempt_id)
with _pending_guard:
pending = _pending_qr.get(attempt_id)
if pending is not None:
_pending_busy.add(attempt_id)
if pending is None:
raise RuntimeError("请重新扫码")
try:
@@ -319,7 +352,10 @@ def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> d
except Exception:
_drop_qr(attempt_id)
raise
_pending_qr.pop(attempt_id, None)
finally:
_release_pending(attempt_id)
with _pending_guard:
_pending_qr.pop(attempt_id, None)
employee_id = str(profile.get("accountId") or profile.get("userName") or "").strip()
if not employee_id:
pending.client.close()
@@ -332,11 +368,6 @@ def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> d
pending.client.close()
def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
"""向 e 学现查首页信息。个人信息只出现在返回值里,不写入数据库。凭证变化时更新密文。"""
return _live(db, employee_id, client_factory, lambda client: _apply_hours_source(client, client.home_snapshot()))
def fetch_home_summary(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return _live(db, employee_id, client_factory, lambda client: _apply_hours_source(client, client.home_summary()))
@@ -484,6 +515,7 @@ def revoke_credential(db: Session, employee_id: str) -> None:
from euniv.autostudy import stop_account
stop_account(employee_id)
release_credential_lock(employee_id)
def refresh_stored_credentials(client_factory=EunivClient) -> None:
@@ -690,7 +722,3 @@ def _request_course_sync(employee_id: str) -> None:
from euniv.courses import request_course_sync
request_course_sync(employee_id)
def stored_password(account: Account) -> str:
return decrypt_secret(account.password_cipher)
+1 -8
View File
@@ -24,7 +24,6 @@ _inflight: set[str] = set()
_dirty: set[str] = set()
_urgent: set[str] = set()
_last_flush: dict[str, float] = {}
_latest: dict[str, dict] = {}
def attach_loop(loop: asyncio.AbstractEventLoop) -> None:
@@ -47,6 +46,7 @@ def unregister(employee_id: str, ws: WebSocket) -> None:
group.discard(ws)
if not group:
_clients.pop(key, None)
_last_flush.pop(key, None)
def notify(employee_id: str | None = None, urgent: bool = False) -> None:
@@ -59,12 +59,6 @@ def notify(employee_id: str | None = None, urgent: bool = False) -> None:
loop.call_soon_threadsafe(_mark, key, urgent)
def latest_of(employee_id: str) -> dict | None:
key = (employee_id or "").strip()
payload = _latest.get(key)
return dict(payload) if payload else None
def _mark(employee_id: str, urgent: bool) -> None:
_dirty.add(employee_id)
if urgent:
@@ -109,7 +103,6 @@ async def _flush(employee_id: str, armed: bool = False) -> None:
from euniv.study_control import payload_for
payload = await asyncio.to_thread(payload_for, employee_id)
_latest[employee_id] = payload
_last_flush[employee_id] = asyncio.get_running_loop().time()
dead: list[WebSocket] = []
for ws in sockets:
+23 -14
View File
@@ -24,6 +24,26 @@ def validate_start(day: object, hour: object, minute: object, second: object) ->
return int(day), int(hour), int(minute), int(second)
def _clamp_int(value: object, low: int, high: int, default: int) -> int:
if isinstance(value, bool):
return default
try:
number = int(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return default
return min(high, max(low, number))
def stored_start(account) -> tuple[int, int, int, int]:
"""读取时把非法时刻收进合法范围,避免首页状态接口报错。"""
return (
_clamp_int(getattr(account, "study_start_day", 1), 1, 31, 1),
_clamp_int(getattr(account, "study_start_hour", 0), 0, 23, 0),
_clamp_int(getattr(account, "study_start_minute", 0), 0, 59, 0),
_clamp_int(getattr(account, "study_start_second", 0), 0, 59, 0),
)
def apply(account, day: object, hour: object, minute: object, second: object) -> None:
d, h, m, s = validate_start(day, hour, minute, second)
account.study_start_day = d
@@ -33,18 +53,12 @@ def apply(account, day: object, hour: object, minute: object, second: object) ->
def label_of(account) -> str:
day = int(getattr(account, "study_start_day", 1) or 1)
hour = int(getattr(account, "study_start_hour", 0) or 0)
minute = int(getattr(account, "study_start_minute", 0) or 0)
second = int(getattr(account, "study_start_second", 0) or 0)
day, hour, minute, second = stored_start(account)
return f"每月{day}日 {hour:02d}:{minute:02d}:{second:02d}"
def view_of(account) -> dict:
day = int(getattr(account, "study_start_day", 1) or 1)
hour = int(getattr(account, "study_start_hour", 0) or 0)
minute = int(getattr(account, "study_start_minute", 0) or 0)
second = int(getattr(account, "study_start_second", 0) or 0)
day, hour, minute, second = stored_start(account)
enabled = getattr(account, "study_schedule_enabled", True)
return {
"day": day,
@@ -71,12 +85,7 @@ def month_key(now: datetime | None = None) -> str:
def start_at(account, now: datetime | None = None) -> datetime:
"""该账号在 now 所在月的开始时刻。2 月 31 日等按当月最后一天。"""
current = as_cn(now)
day, hour, minute, second = validate_start(
int(getattr(account, "study_start_day", 1) or 1),
int(getattr(account, "study_start_hour", 0) or 0),
int(getattr(account, "study_start_minute", 0) or 0),
int(getattr(account, "study_start_second", 0) or 0),
)
day, hour, minute, second = stored_start(account)
last = calendar.monthrange(current.year, current.month)[1]
return datetime(
current.year,