feat: track duty email confirmations and add throttled account email tests
This commit is contained in:
+75
-3
@@ -38,6 +38,8 @@ from .models import activities, auth_limits, email_verifications, join_links, me
|
||||
from .security import hash_password, new_token, token_digest, verify_password
|
||||
from .backup import backup_loop, parse_time
|
||||
from .duty import BEIJING, duty_status, load_schedule, reminder_loop
|
||||
from .duty import resolve_recipients
|
||||
from . import duty_receipts
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_DIR = BASE_DIR.parent
|
||||
@@ -547,6 +549,7 @@ async def lifespan(_app: FastAPI):
|
||||
duty_task = asyncio.create_task(reminder_loop(
|
||||
duty_path, _db_path.with_name("duty-reminders.db"), duty_accounts, _send_email,
|
||||
os.getenv("WORKLOG_DUTY_EMAILS", str(_db_path.parent / "duty-emails.json")),
|
||||
_site_base_url(),
|
||||
))
|
||||
try:
|
||||
yield
|
||||
@@ -639,7 +642,7 @@ async def security_headers(request: Request, call_next):
|
||||
"img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; "
|
||||
"frame-ancestors 'none'; form-action 'self'"
|
||||
)
|
||||
if request.url.path.startswith(("/api/", "/join/")):
|
||||
if request.url.path.startswith(("/api/", "/join/", "/duty-confirm/")):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
@@ -1147,15 +1150,84 @@ async def update_me(payload: ProfileIn, user: dict = Depends(current_user), db:
|
||||
# ---------------------------------------------------------------- 成员
|
||||
|
||||
@app.get("/api/duty/current")
|
||||
async def current_duty(_viewer: dict = Depends(current_user)) -> dict:
|
||||
async def current_duty(_viewer: dict = Depends(current_user), db: AsyncSession = Depends(get_db)) -> dict:
|
||||
path = Path(os.getenv("WORKLOG_DUTY_SCHEDULE", str(PROJECT_DIR / "duty/schedule.json")))
|
||||
if not path.exists():
|
||||
return duty_status({"enabled": False}, datetime.now(BEIJING))
|
||||
try:
|
||||
return duty_status(load_schedule(path), datetime.now(BEIJING))
|
||||
data = duty_status(load_schedule(path), 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"]):
|
||||
if not shift:
|
||||
continue
|
||||
recipients, _ = resolve_recipients({name: [shift["slot"]] for name in shift["names"]}, accounts, overrides)
|
||||
emails = {name: email for email, names in recipients.items() for name in names}
|
||||
day = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING).date().isoformat()
|
||||
shift["reminders"] = [await asyncio.to_thread(duty_receipts.status, _duty_state(), day, shift["slot"], name, emails.get(name), time.time()) for name in shift["names"]]
|
||||
return data
|
||||
except (ValueError, KeyError, TypeError, OSError) as exc:
|
||||
raise HTTPException(status_code=503, detail="值班安排暂时无法读取") from exc
|
||||
|
||||
|
||||
def _duty_state():
|
||||
return _db_path.with_name("duty-reminders.db")
|
||||
|
||||
|
||||
@app.post("/api/auth/test-email")
|
||||
async def test_account_email(viewer: dict = Depends(current_user)):
|
||||
email = viewer.get("email", "").strip()
|
||||
if not email:
|
||||
raise HTTPException(status_code=409, detail="当前账号尚未绑定邮箱")
|
||||
if not await asyncio.to_thread(duty_receipts.reserve_test, _duty_state(), email, time.time()):
|
||||
raise HTTPException(status_code=429, detail="同一邮箱2分钟内只能测试一次,请稍后重试", headers={"Retry-After": "120"})
|
||||
await _send_email(email, "【WorkLog】邮箱连通性测试", "这是一封由你在账号设置中主动发送的测试邮件。收到本邮件表示当前邮件发送服务可以向你的绑定邮箱投递邮件。\n\nWorkLog")
|
||||
return {"ok": True, "retry_after": 120}
|
||||
|
||||
|
||||
def _duty_overrides():
|
||||
import json
|
||||
path = Path(os.getenv("WORKLOG_DUTY_EMAILS", str(_db_path.parent / "duty-emails.json")))
|
||||
return json.loads(path.read_text(encoding="utf-8-sig")) if path.exists() else {}
|
||||
|
||||
|
||||
class DutyRemindIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=64)
|
||||
start_at: int
|
||||
|
||||
|
||||
@app.post("/api/duty/remind")
|
||||
async def remind_duty(payload: DutyRemindIn, viewer: dict = Depends(current_user), db: AsyncSession = Depends(get_db)):
|
||||
data = await current_duty(viewer, db)
|
||||
shift = next((s for s in (data["current"], data["next"]) if s and s["start_at"] == payload.start_at and payload.name in s["names"]), None)
|
||||
if not shift:
|
||||
raise HTTPException(status_code=409, detail="值班安排已变化,请刷新页面")
|
||||
accounts = [dict(r) for r in (await db.execute(select(users.c.display_name, users.c.email))).mappings()]
|
||||
recipients, _ = resolve_recipients({payload.name: [shift["slot"]]}, accounts, _duty_overrides())
|
||||
if not recipients:
|
||||
raise HTTPException(status_code=409, detail="未找到唯一的绑定邮箱,请核对姓名和账号")
|
||||
email = next(iter(recipients))
|
||||
start = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING)
|
||||
try:
|
||||
sent = await duty_receipts.send_notice(_duty_state(), start.date().isoformat(), {payload.name: [shift["slot"]]}, email, shift["end_at"] / 1000, _send_email, "值班提醒", f"日期:{start:%Y-%m-%d},{start:%H:%M} 开始(北京时间)", _site_base_url())
|
||||
except HTTPException:
|
||||
raise
|
||||
if not sent:
|
||||
raise HTTPException(status_code=429, detail="已确认、已达3次上限或距上次发送不足1分钟")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@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")
|
||||
if targets is None:
|
||||
return HTMLResponse(_join_page("确认链接无效或本轮值班已结束。", "err"), 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"))
|
||||
|
||||
@app.get("/api/stats/overview")
|
||||
async def overview(db: AsyncSession = Depends(get_db), _viewer: dict = Depends(current_user)) -> dict:
|
||||
members = int((await db.execute(select(func.count()).select_from(users))).scalar() or 0)
|
||||
|
||||
Reference in New Issue
Block a user