Files
EnuivTools/backend/euniv/api.py
T

69 lines
1.9 KiB
Python

"""登录接口。本地保存工号、加密密码和加密后的登录凭证。"""
from __future__ import annotations
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import Depends, FastAPI, HTTPException
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
@asynccontextmanager
async def lifespan(_app: FastAPI):
init_db()
yield
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)
class JigsawBody(BaseModel):
attempt_id: str = Field(min_length=8, max_length=64)
offset: int = Field(ge=0, le=2000)
@app.get("/api/health")
def health() -> dict:
return {"ok": True}
@app.post("/api/login")
def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
employee_id = body.employee_id.strip()
try:
return login_and_store(db, employee_id, body.password)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.post("/api/login/jigsaw")
def login_jigsaw(body: JigsawBody, db: Session = Depends(get_db)) -> dict:
try:
return submit_jigsaw(db, body.attempt_id, body.offset)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/home")
def home(employee_id: str, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home(db, employee_id.strip())
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
_dist = Path(__file__).resolve().parents[2] / "web" / "dist"
if _dist.is_dir():
app.mount("/", StaticFiles(directory=_dist, html=True), name="web")