57 lines
1.5 KiB
Python
57 lines
1.5 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
|
|
|
|
|
|
@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)
|
|
|
|
|
|
@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:
|
|
login_and_store(db, employee_id, body.password)
|
|
except RuntimeError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
return {"employee_id": employee_id}
|
|
|
|
|
|
@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")
|