修复值班邮件跨站确认,独立记录未确认缺勤并与活动统计隔离
This commit is contained in:
+38
-6
@@ -645,7 +645,10 @@ async def security_headers(request: Request, call_next):
|
||||
origin = request.headers.get("origin")
|
||||
own_origin = str(request.base_url).rstrip("/")
|
||||
trusted_origin = BASE_URL or own_origin
|
||||
if request.method not in ("GET", "HEAD", "OPTIONS") and (
|
||||
# 此独立回执入口依赖不可猜测的邮件令牌及 GET 页面签发的表单令牌;
|
||||
# 邮件内置浏览器可能把合法表单提交标为 cross-site,其他入口仍严格检查。
|
||||
duty_confirmation_post = request.method == "POST" and re.fullmatch(r"/duty-confirm/[A-Za-z0-9_-]{32,128}", request.url.path)
|
||||
if not duty_confirmation_post and request.method not in ("GET", "HEAD", "OPTIONS") and (
|
||||
(origin and origin not in (own_origin, trusted_origin))
|
||||
or request.headers.get("sec-fetch-site") == "cross-site"
|
||||
):
|
||||
@@ -1239,7 +1242,9 @@ async def current_duty(_viewer: dict = Depends(current_user), db: AsyncSession =
|
||||
if not path.exists():
|
||||
return duty_status({"enabled": False}, datetime.now(BEIJING))
|
||||
try:
|
||||
data = duty_status(load_schedule(path), datetime.now(BEIJING))
|
||||
schedule = load_schedule(path)
|
||||
await asyncio.to_thread(duty_receipts.sync_absences, _duty_state(), schedule, datetime.now(BEIJING))
|
||||
data = duty_status(schedule, datetime.now(BEIJING))
|
||||
accounts = [dict(r) for r in (await db.execute(select(users.c.display_name, users.c.email))).mappings()]
|
||||
overrides = _duty_overrides()
|
||||
for shift in (data["current"], data["next"]):
|
||||
@@ -1258,6 +1263,17 @@ def _duty_state():
|
||||
return _db_path.with_name("duty-reminders.db")
|
||||
|
||||
|
||||
@app.get("/api/duty/absences")
|
||||
async def list_duty_absences(_viewer: dict = Depends(current_user), limit: int = Query(50, ge=1, le=100), offset: int = Query(0, ge=0)):
|
||||
path = Path(os.getenv("WORKLOG_DUTY_SCHEDULE", str(PROJECT_DIR / "duty/schedule.json")))
|
||||
if path.exists():
|
||||
try:
|
||||
await asyncio.to_thread(duty_receipts.sync_absences, _duty_state(), load_schedule(path), datetime.now(BEIJING))
|
||||
except (ValueError, KeyError, TypeError, OSError) as exc:
|
||||
raise HTTPException(status_code=503, detail="值班安排暂时无法读取") from exc
|
||||
return {"items": await asyncio.to_thread(duty_receipts.absence_records, _duty_state(), limit, offset)}
|
||||
|
||||
|
||||
@app.post("/api/auth/test-email")
|
||||
async def test_account_email(viewer: dict = Depends(current_user)):
|
||||
email = viewer.get("email", "").strip()
|
||||
@@ -1304,13 +1320,29 @@ async def remind_duty(payload: DutyRemindIn, viewer: dict = Depends(current_user
|
||||
@app.get("/duty-confirm/{token}", include_in_schema=False)
|
||||
@app.post("/duty-confirm/{token}", include_in_schema=False)
|
||||
async def confirm_duty(token: str, request: Request):
|
||||
targets = await asyncio.to_thread(duty_receipts.confirmation, _duty_state(), token, time.time(), request.method == "POST")
|
||||
from urllib.parse import parse_qs
|
||||
now = time.time()
|
||||
form_token = None
|
||||
if request.method == "POST":
|
||||
body = await request.body()
|
||||
if len(body) > 4096:
|
||||
raise HTTPException(status_code=400, detail="确认请求无效,请重新打开邮件链接")
|
||||
form_token = parse_qs(body.decode("utf-8", errors="replace")).get("confirmation_token", [None])[0]
|
||||
targets = await asyncio.to_thread(duty_receipts.confirmation, _duty_state(), token, now, request.method == "POST", form_token, True)
|
||||
if targets is None:
|
||||
return HTMLResponse(_join_page("确认链接无效或本轮值班已结束。", "err"), status_code=410)
|
||||
return HTMLResponse(_duty_confirmation_page("确认链接无效、表单已更新或本轮值班已结束,请重新打开邮件链接。"), status_code=410)
|
||||
text = ";".join(f"{day} {slot} {name}" for day, slot, name in targets)
|
||||
if request.method == "GET":
|
||||
return HTMLResponse(_join_page("请确认已知晓:" + text, "confirm", extra='<form method="post"><button class="btn" type="submit">确认已知晓值班安排</button></form>'))
|
||||
return HTMLResponse(_join_page("已确认值班安排,谢谢。", "ok"))
|
||||
nonce = await asyncio.to_thread(duty_receipts.issue_confirmation_form, _duty_state(), token, now)
|
||||
if not nonce:
|
||||
return HTMLResponse(_duty_confirmation_page("本轮确认链接已失效。"), status_code=410)
|
||||
return HTMLResponse(_duty_confirmation_page("请确认已知晓:" + text, nonce))
|
||||
return HTMLResponse(_duty_confirmation_page("已确认值班安排,谢谢。本次确认仅记录值班回执。"))
|
||||
|
||||
|
||||
def _duty_confirmation_page(message: str, nonce: str | None = None):
|
||||
form = f'<form method="post"><input type="hidden" name="confirmation_token" value="{escape(nonce, quote=True)}"><button type="submit">确认已知晓值班安排</button></form>' if nonce else ''
|
||||
return f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>值班邮件确认 · WorkLog</title><style>body{{font:16px/1.8 system-ui,sans-serif;background:#f5f7f5;color:#263c35;margin:0;padding:32px 20px}}main{{max-width:480px;margin:8vh auto;background:white;border:1px solid #e1e8e3;border-radius:16px;padding:28px}}h1{{font-size:24px}}button{{background:#28664f;color:white;border:0;border-radius:8px;padding:12px 20px;font:inherit;cursor:pointer}}p{{overflow-wrap:anywhere}}</style><main><h1>值班邮件确认</h1><p>{escape(message)}</p>{form}</main></html>'
|
||||
|
||||
@app.get("/api/stats/overview")
|
||||
async def overview(db: AsyncSession = Depends(get_db), _viewer: dict = Depends(current_user)) -> dict:
|
||||
|
||||
Reference in New Issue
Block a user