2103 lines
99 KiB
Python
2103 lines
99 KiB
Python
"""WorkLog —— 活动记录网站后端。
|
||
|
||
FastAPI + SQLAlchemy(异步)+ SQLite,同端口托管 dist 下的原生前端。
|
||
核心模型:账号(users)、活动(activities)、参加记录(participations)。
|
||
每个账号记录自己参加过的活动,也能看到其他账号公开的活动记录。
|
||
|
||
启动:python -m server.main
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import os
|
||
import re
|
||
import secrets
|
||
import time
|
||
import tomllib
|
||
import uuid
|
||
from html import escape
|
||
from ipaddress import ip_address
|
||
from contextlib import asynccontextmanager
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import Any, Literal, Optional
|
||
|
||
import uvicorn
|
||
from fastapi import Depends, FastAPI, HTTPException, Query, Request
|
||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||
from sqlalchemy import and_, delete, event, func, insert, inspect, or_, select, text, update
|
||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||
from sqlalchemy.exc import IntegrityError
|
||
from sqlalchemy.schema import CreateIndex
|
||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||
|
||
from .models import activities, auth_limits, email_verifications, join_links, metadata, participations, sessions, users
|
||
from .security import EMAIL_PATTERN, PHONE_PATTERN, hash_password, new_token, now_ms, token_digest, verify_password
|
||
from .mail_pages import confirmation_page, join_page
|
||
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
|
||
from . import center
|
||
from . import center_duty
|
||
from . import center_export
|
||
from . import recruit
|
||
from . import timetables as timetable_routes
|
||
from .models import center_activity_meta, center_items, center_loans
|
||
import json
|
||
|
||
BASE_DIR = Path(__file__).resolve().parent
|
||
PROJECT_DIR = BASE_DIR.parent
|
||
|
||
|
||
def _load_dotenv(path: Path) -> None:
|
||
"""极简 .env 读取:已存在的环境变量优先。"""
|
||
if not path.exists():
|
||
return
|
||
for raw_line in path.read_text(encoding="utf-8").splitlines():
|
||
line = raw_line.strip()
|
||
if not line or line.startswith("#") or "=" not in line:
|
||
continue
|
||
key, value = line.split("=", 1)
|
||
key, value = key.strip(), value.strip().strip("\"'")
|
||
if key and key not in os.environ:
|
||
os.environ[key] = value
|
||
|
||
|
||
_load_dotenv(PROJECT_DIR / ".env")
|
||
|
||
CONFIG_PATH = Path(os.getenv("WORKLOG_CONFIG", str(PROJECT_DIR / "config.toml")))
|
||
try:
|
||
with CONFIG_PATH.open("rb") as handle:
|
||
CONFIG = tomllib.load(handle)
|
||
except FileNotFoundError:
|
||
CONFIG = {}
|
||
|
||
|
||
def cfg(section: str, key: str, default: Any = "") -> Any:
|
||
return CONFIG.get(section, {}).get(key, default)
|
||
|
||
|
||
HOST = os.getenv("WORKLOG_HOST", str(cfg("server", "host", "127.0.0.1")))
|
||
PORT = int(os.getenv("WORKLOG_PORT", cfg("server", "port", 34180)))
|
||
SESSION_DAYS = int(os.getenv("WORKLOG_SESSION_DAYS", cfg("auth", "session_days", 30)))
|
||
|
||
_db_path = Path(os.getenv("WORKLOG_DB", str(cfg("database", "path", "./data/worklog.db"))))
|
||
if not _db_path.is_absolute():
|
||
_db_path = (PROJECT_DIR / _db_path).resolve()
|
||
_db_path.parent.mkdir(parents=True, exist_ok=True)
|
||
DATABASE_URL = f"sqlite+aiosqlite:///{_db_path.as_posix()}"
|
||
|
||
_frontend = Path(os.getenv("WORKLOG_FRONTEND", str(cfg("server", "frontend_dir", "./dist"))))
|
||
FRONTEND_DIR = _frontend if _frontend.is_absolute() else (PROJECT_DIR / _frontend).resolve()
|
||
|
||
# 验证码回显必须显式开启,且仅允许本机开发。
|
||
SMTP_HOST = os.getenv("WORKLOG_SMTP_HOST", str(cfg("smtp", "host", "")))
|
||
SMTP_PORT = int(os.getenv("WORKLOG_SMTP_PORT", cfg("smtp", "port", 465)))
|
||
SMTP_USER = os.getenv("WORKLOG_SMTP_USER", str(cfg("smtp", "user", "")))
|
||
SMTP_PASSWORD = os.getenv("WORKLOG_SMTP_PASSWORD", str(cfg("smtp", "password", "")))
|
||
SMTP_FROM = os.getenv("WORKLOG_SMTP_FROM", str(cfg("smtp", "from", ""))) or SMTP_USER
|
||
SMTP_TLS = os.getenv("WORKLOG_SMTP_TLS", str(cfg("smtp", "tls", "ssl"))).lower() # ssl / starttls / none
|
||
EMAIL_CODE_TTL_MIN = int(os.getenv("WORKLOG_EMAIL_CODE_TTL_MIN", cfg("smtp", "code_ttl_min", 10)))
|
||
DEV_MODE = str(os.getenv("WORKLOG_DEV_MODE", cfg("auth", "dev_mode", False))).lower() in ("1", "true", "yes")
|
||
# 不使用客户端提供的 Host / X-Forwarded-* 构造含有令牌的邮件链接。
|
||
BASE_URL = os.getenv("WORKLOG_BASE_URL", str(cfg("server", "base_url", ""))).rstrip("/")
|
||
# 新活动邮件通知开关(发通知给除发起人外的所有已注册用户)
|
||
NOTIFY_ENABLED = str(os.getenv("WORKLOG_NOTIFY", cfg("notify", "enabled", True))).lower() not in ("0", "false", "no")
|
||
JOIN_LINK_DAYS = 7
|
||
# 每天定时备份数据库(写入 <库目录>/backups/,默认保留最近 14 份)
|
||
BACKUP_ENABLED = str(os.getenv("WORKLOG_BACKUP", cfg("backup", "enabled", True))).lower() not in ("0", "false", "no")
|
||
BACKUP_TIME = os.getenv("WORKLOG_BACKUP_TIME", str(cfg("backup", "time", "23:00")))
|
||
BACKUP_KEEP = int(os.getenv("WORKLOG_BACKUP_KEEP", cfg("backup", "keep", 14)))
|
||
|
||
STATUSES = ("joined", "attended", "absent")
|
||
# 队内固定五个部门
|
||
DEPARTMENTS = ["企业事业部", "培训宣讲部", "综合部", "新媒体部", "无敌赋能部"]
|
||
|
||
ACTIVITY_STATUSES = ("approved",)
|
||
# 同一账号 60 秒内提交同名的活动视为重复点击,只保留第一条
|
||
DUPLICATE_WINDOW_MS = 60_000
|
||
|
||
engine = create_async_engine(DATABASE_URL, future=True)
|
||
|
||
|
||
@event.listens_for(engine.sync_engine, "connect")
|
||
def _sqlite_pragmas(dbapi_connection, _record): # pragma: no cover - 由驱动回调
|
||
cursor = dbapi_connection.cursor()
|
||
cursor.execute("PRAGMA foreign_keys=ON")
|
||
cursor.execute("PRAGMA journal_mode=WAL")
|
||
cursor.close()
|
||
|
||
|
||
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
|
||
|
||
|
||
# ---------------------------------------------------------------- 基础工具
|
||
|
||
def new_id() -> str:
|
||
return uuid.uuid4().hex
|
||
|
||
|
||
def user_public(row: Any, *, include_contact: bool = False) -> dict:
|
||
result = {
|
||
"id": row["id"],
|
||
"username": row["username"],
|
||
"display_name": row["display_name"],
|
||
"department": row["department"],
|
||
"bio": row["bio"],
|
||
"created_at": row["created_at"],
|
||
}
|
||
if include_contact:
|
||
result.update(email=row["email"], phone=row["phone"] if "phone" in row.keys() else "")
|
||
# 前端据此判断是否强制引导设置密码。
|
||
# 老库的 password_hash 是注册时的随机占位值(用户本人不知道),
|
||
# 所以必须看 password_set 标记,不能只看 hash 是否非空。
|
||
result["has_password"] = bool(row["password_set"] if "password_set" in row.keys() else 0) and bool(
|
||
row["password_hash"] if "password_hash" in row.keys() else ""
|
||
)
|
||
return result
|
||
|
||
|
||
def activity_public(row: Any) -> dict:
|
||
return {
|
||
"id": row["id"],
|
||
"title": row["title"],
|
||
"start_at": row["start_at"],
|
||
"location": row["location"],
|
||
"description": row["description"],
|
||
"visibility": row["visibility"],
|
||
"capacity": row["capacity"],
|
||
"organizer_id": row["organizer_id"],
|
||
"created_at": row["created_at"],
|
||
"updated_at": row["updated_at"],
|
||
}
|
||
|
||
|
||
def normal_activity_clause():
|
||
return activities.c.id.not_in(select(center_activity_meta.c.activity_id))
|
||
|
||
|
||
def visible_clause(viewer_id: str):
|
||
"""一楼记录对登录成员全员可见;普通活动沿用公开、发起人和参加者规则。"""
|
||
return or_(
|
||
activities.c.id.in_(select(center_activity_meta.c.activity_id)),
|
||
activities.c.visibility == "public",
|
||
activities.c.organizer_id == viewer_id,
|
||
activities.c.id.in_(
|
||
select(participations.c.activity_id).where(
|
||
and_(participations.c.user_id == viewer_id, participations.c.status != "pending")
|
||
)
|
||
),
|
||
)
|
||
|
||
|
||
async def get_db():
|
||
async with SessionLocal() as session:
|
||
yield session
|
||
|
||
|
||
async def current_user(request: Request, db: AsyncSession = Depends(get_db)) -> dict:
|
||
header = request.headers.get("authorization", "")
|
||
token = header[7:].strip() if header.lower().startswith("bearer ") else ""
|
||
if not token:
|
||
token = request.cookies.get("worklog_token", "").strip()
|
||
if not token:
|
||
raise HTTPException(status_code=401, detail="请先登录")
|
||
row = (await db.execute(select(sessions).where(sessions.c.token == token_digest(token)))).mappings().first()
|
||
if row is None or row["expires_at"] <= now_ms():
|
||
raise HTTPException(status_code=401, detail="登录已过期,请重新登录")
|
||
user = (await db.execute(select(users).where(users.c.id == row["user_id"]))).mappings().first()
|
||
if user is None:
|
||
raise HTTPException(status_code=401, detail="账号不存在或已注销")
|
||
return dict(user)
|
||
|
||
|
||
async def fetch_activity(db: AsyncSession, activity_id: str):
|
||
row = (await db.execute(select(activities).where(activities.c.id == activity_id))).mappings().first()
|
||
if row is None:
|
||
raise HTTPException(status_code=404, detail="活动不存在")
|
||
return row
|
||
|
||
|
||
async def is_center_activity(db: AsyncSession, activity_id: str) -> bool:
|
||
return (await db.execute(select(center_activity_meta.c.activity_id).where(
|
||
center_activity_meta.c.activity_id == activity_id
|
||
))).first() is not None
|
||
|
||
|
||
async def require_participatory_activity(db: AsyncSession, activity_id: str):
|
||
if await is_center_activity(db, activity_id):
|
||
raise HTTPException(409, '赋能中心一楼活动仅作记录,不接受参加或参加状态变更')
|
||
|
||
|
||
async def participant_rows(db: AsyncSession, activity_ids: list[str]) -> dict[str, list[dict]]:
|
||
"""一次性取出若干活动的参加者,按活动 id 分组,避免逐条查询。"""
|
||
grouped: dict[str, list[dict]] = {}
|
||
if not activity_ids:
|
||
return grouped
|
||
rows = (
|
||
await db.execute(
|
||
select(participations, users.c.username, users.c.display_name)
|
||
.join(users, users.c.id == participations.c.user_id)
|
||
.where(participations.c.activity_id.in_(activity_ids))
|
||
.order_by(participations.c.joined_at.asc())
|
||
)
|
||
).mappings().all()
|
||
for row in rows:
|
||
grouped.setdefault(row["activity_id"], []).append(
|
||
{
|
||
"id": row["id"],
|
||
"user_id": row["user_id"],
|
||
"username": row["username"],
|
||
"display_name": row["display_name"],
|
||
"status": row["status"],
|
||
"note": row["note"],
|
||
"joined_at": row["joined_at"],
|
||
}
|
||
)
|
||
return grouped
|
||
|
||
|
||
async def serialize_activities(db: AsyncSession, rows: list[Any], viewer_id: str) -> list[dict]:
|
||
ids = [row["id"] for row in rows]
|
||
people = await participant_rows(db, ids)
|
||
meta_rows = (await db.execute(select(center_activity_meta).where(center_activity_meta.c.activity_id.in_(ids)))).mappings().all() if ids else []
|
||
photos = {r['activity_id']: json.loads(r['photo_ids']) for r in meta_rows}
|
||
materials = {r['activity_id']: r['material_id'] for r in meta_rows}
|
||
packages = await center.activity_materials(db, list(photos))
|
||
|
||
organizer_ids = {row["organizer_id"] for row in rows}
|
||
organizers: dict[str, dict] = {}
|
||
if organizer_ids:
|
||
found = (await db.execute(select(users).where(users.c.id.in_(organizer_ids)))).mappings().all()
|
||
organizers = {row["id"]: user_public(row) for row in found}
|
||
|
||
items = []
|
||
for row in rows:
|
||
is_center = row['id'] in photos
|
||
members = [] if is_center else people.get(row["id"], [])
|
||
mine = next((m for m in members if m["user_id"] == viewer_id), None)
|
||
items.append(
|
||
{
|
||
**activity_public(row),
|
||
"record_type": "center" if is_center else "normal",
|
||
"visibility": "public" if is_center else row['visibility'],
|
||
"capacity": None if is_center else row['capacity'],
|
||
"photo_ids": photos.get(row['id'], []),
|
||
"material_id": materials.get(row['id']),
|
||
"materials": packages.get(row['id'], []) if is_center else [],
|
||
"organizer": organizers.get(row["organizer_id"]),
|
||
"participants": members,
|
||
"participant_count": len(members),
|
||
"attended_count": sum(1 for m in members if m["status"] == "attended"),
|
||
"my_participation": mine,
|
||
}
|
||
)
|
||
for item in items:
|
||
item['photo_ids'] = list(dict.fromkeys([*item['photo_ids'], *(photo for package in item['materials'] for photo in package['photo_ids'])]))
|
||
return items
|
||
|
||
|
||
async def user_stats(db: AsyncSession, user_id: str, *, public_only: bool = False) -> dict:
|
||
"""某账号的记录统计;public_only=True 时只统计公开活动(别人看你的主页时用)。"""
|
||
stmt = (
|
||
select(participations.c.status, activities.c.start_at, activities.c.visibility)
|
||
.join(activities, activities.c.id == participations.c.activity_id)
|
||
.where(and_(participations.c.user_id == user_id, participations.c.status != "pending", normal_activity_clause()))
|
||
)
|
||
if public_only:
|
||
stmt = stmt.where(activities.c.visibility == "public")
|
||
rows = (await db.execute(stmt)).mappings().all()
|
||
|
||
organized_stmt = select(func.count()).select_from(activities).where(
|
||
activities.c.organizer_id == user_id, normal_activity_clause()
|
||
)
|
||
if public_only:
|
||
organized_stmt = organized_stmt.where(activities.c.visibility == "public")
|
||
organized = int((await db.execute(organized_stmt)).scalar() or 0)
|
||
|
||
total = len(rows)
|
||
attended = sum(1 for row in rows if row["status"] == "attended")
|
||
absent = sum(1 for row in rows if row["status"] == "absent")
|
||
upcoming = sum(1 for row in rows if row["start_at"] >= now_ms())
|
||
starts = [row["start_at"] for row in rows]
|
||
return {
|
||
"total": total,
|
||
"attended": attended,
|
||
"absent": absent,
|
||
"joined": total - attended - absent,
|
||
"organized": organized,
|
||
"upcoming": upcoming,
|
||
"attendance_rate": round(attended / total, 3) if total else 0.0,
|
||
"first_at": min(starts) if starts else None,
|
||
"last_at": max(starts) if starts else None,
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------- 请求模型
|
||
|
||
class EmailCodeIn(BaseModel):
|
||
email_code: str = Field(min_length=6, max_length=6, pattern=r"^[0-9]{6}$")
|
||
|
||
@field_validator("email_code", mode="before")
|
||
@classmethod
|
||
def check_code(cls, value: Any) -> str:
|
||
if not isinstance(value, str) or not re.fullmatch(r"[0-9]{6}", value.strip()):
|
||
raise ValueError("请输入 6 位数字验证码")
|
||
return value.strip()
|
||
|
||
|
||
class SendCodeIn(BaseModel):
|
||
email: str = Field(max_length=255)
|
||
purpose: Literal["register", "login", "reset", "bind"] = "login"
|
||
|
||
@field_validator("email")
|
||
@classmethod
|
||
def check_email(cls, value: str) -> str:
|
||
value = value.strip().lower()
|
||
if not re.match(EMAIL_PATTERN, value):
|
||
raise ValueError("邮箱格式不正确")
|
||
return value
|
||
|
||
|
||
class PasswordCodeIn(EmailCodeIn):
|
||
password: str = Field(min_length=10, max_length=128)
|
||
confirm_password: str = Field(min_length=10, max_length=128)
|
||
|
||
@model_validator(mode="after")
|
||
def passwords_match(self):
|
||
if self.password != self.confirm_password:
|
||
raise ValueError("两次输入的密码不一致")
|
||
return self
|
||
|
||
|
||
class RegisterIn(PasswordCodeIn):
|
||
display_name: str = Field(min_length=1, max_length=32)
|
||
department: str = Field(min_length=1, max_length=64)
|
||
email: str = Field(max_length=255)
|
||
phone: str = Field(min_length=11, max_length=11)
|
||
|
||
@field_validator("display_name")
|
||
@classmethod
|
||
def check_display_name(cls, value: str) -> str:
|
||
value = value.strip()
|
||
if not value:
|
||
raise ValueError("姓名不能为空")
|
||
return value
|
||
|
||
@field_validator("email")
|
||
@classmethod
|
||
def check_email(cls, value: str) -> str:
|
||
value = value.strip().lower()
|
||
if not re.match(EMAIL_PATTERN, value):
|
||
raise ValueError("邮箱格式不正确")
|
||
return value
|
||
|
||
@field_validator("department")
|
||
@classmethod
|
||
def check_department(cls, value: str) -> str:
|
||
value = value.strip()
|
||
if value not in DEPARTMENTS:
|
||
raise ValueError("部门必须是:" + "、".join(DEPARTMENTS))
|
||
return value
|
||
|
||
@field_validator("phone")
|
||
@classmethod
|
||
def check_phone(cls, value: str) -> str:
|
||
value = value.strip()
|
||
if not re.match(PHONE_PATTERN, value):
|
||
raise ValueError("手机号格式不正确")
|
||
return value
|
||
|
||
|
||
class LoginIn(BaseModel):
|
||
email: str = Field(max_length=255)
|
||
password: Optional[str] = Field(default=None, min_length=10, max_length=128)
|
||
email_code: Optional[str] = None
|
||
|
||
@field_validator("email")
|
||
@classmethod
|
||
def check_email(cls, value: str) -> str:
|
||
value = value.strip().lower()
|
||
if not re.match(EMAIL_PATTERN, value):
|
||
raise ValueError("邮箱格式不正确")
|
||
return value
|
||
|
||
@field_validator("email_code", mode="before")
|
||
@classmethod
|
||
def validate_optional_code(cls, value: Any) -> Optional[str]:
|
||
if value is None:
|
||
return None
|
||
return EmailCodeIn.check_code(value)
|
||
|
||
@model_validator(mode="after")
|
||
def exactly_one_login_method(self):
|
||
if bool(self.password) == bool(self.email_code):
|
||
raise ValueError("请选择密码登录或验证码登录")
|
||
return self
|
||
|
||
|
||
class SetPasswordIn(BaseModel):
|
||
"""登录态下设置/修改密码:只需要新密码本身,不需要邮箱验证码(当前会话即凭据)。"""
|
||
password: str = Field(min_length=10, max_length=128)
|
||
confirm_password: str = Field(min_length=10, max_length=128)
|
||
|
||
@model_validator(mode="after")
|
||
def passwords_match(self):
|
||
if self.password != self.confirm_password:
|
||
raise ValueError("两次输入的密码不一致")
|
||
return self
|
||
|
||
|
||
class ResetPasswordIn(PasswordCodeIn):
|
||
email: str = Field(max_length=255)
|
||
|
||
@field_validator("email")
|
||
@classmethod
|
||
def check_email(cls, value: str) -> str:
|
||
value = value.strip().lower()
|
||
if not re.match(EMAIL_PATTERN, value):
|
||
raise ValueError("邮箱格式不正确")
|
||
return value
|
||
|
||
|
||
class ProfileIn(BaseModel):
|
||
display_name: Optional[str] = Field(default=None, max_length=32)
|
||
department: Optional[str] = Field(default=None, max_length=64)
|
||
phone: Optional[str] = Field(default=None, max_length=11)
|
||
bio: Optional[str] = Field(default=None, max_length=200)
|
||
|
||
@field_validator("phone")
|
||
@classmethod
|
||
def check_phone(cls, value: Optional[str]) -> Optional[str]:
|
||
if value is None:
|
||
return value
|
||
value = value.strip()
|
||
if value and not re.match(PHONE_PATTERN, value):
|
||
raise ValueError("手机号格式不正确")
|
||
return value
|
||
|
||
|
||
class NewEmailIn(BaseModel):
|
||
email: str = Field(max_length=255)
|
||
|
||
@field_validator("email")
|
||
@classmethod
|
||
def validate_email(cls, value: str) -> str:
|
||
return SendCodeIn.check_email(value)
|
||
|
||
|
||
class ChangeEmailIn(NewEmailIn):
|
||
new_code: str
|
||
|
||
@field_validator("new_code", mode="before")
|
||
@classmethod
|
||
def validate_codes(cls, value):
|
||
return EmailCodeIn.check_code(value)
|
||
|
||
|
||
class ActivityIn(BaseModel):
|
||
material_id: Optional[str] = Field(default=None, max_length=32)
|
||
record_type: Literal['normal', 'center'] = 'normal'
|
||
photo_ids: list[str] = Field(default_factory=list)
|
||
title: str = Field(min_length=1, max_length=120)
|
||
start_at: int = Field(gt=0)
|
||
location: str = Field(default="", max_length=120)
|
||
description: str = Field(default="", max_length=2000)
|
||
visibility: Literal["public", "private"] = "public"
|
||
capacity: Optional[int] = Field(default=None, ge=1, le=500)
|
||
|
||
@field_validator("title")
|
||
@classmethod
|
||
def strip_title(cls, value: str) -> str:
|
||
value = value.strip()
|
||
if not value:
|
||
raise ValueError("活动名称不能为空")
|
||
return value
|
||
|
||
|
||
class ActivityPatch(BaseModel):
|
||
material_id: Optional[str] = Field(default=None, max_length=32)
|
||
record_type: Optional[Literal['normal', 'center']] = None
|
||
photo_ids: Optional[list[str]] = None
|
||
title: Optional[str] = Field(default=None, max_length=120)
|
||
start_at: Optional[int] = Field(default=None, gt=0)
|
||
location: Optional[str] = Field(default=None, max_length=120)
|
||
description: Optional[str] = Field(default=None, max_length=2000)
|
||
visibility: Optional[Literal["public", "private"]] = None
|
||
capacity: Optional[int] = Field(default=None, ge=1, le=500)
|
||
|
||
|
||
class ParticipationPatch(BaseModel):
|
||
status: Optional[Literal["joined", "attended", "absent"]] = None
|
||
note: Optional[str] = Field(default=None, max_length=500)
|
||
|
||
|
||
async def _find_user_by_email(db: AsyncSession, email: str):
|
||
return (
|
||
await db.execute(select(users).where(func.lower(users.c.email) == email.strip().lower()))
|
||
).mappings().first()
|
||
|
||
|
||
async def _require_participant(db: AsyncSession, activity_id: str, user_id: str):
|
||
row = (
|
||
await db.execute(
|
||
select(participations).where(
|
||
and_(participations.c.activity_id == activity_id, participations.c.user_id == user_id)
|
||
)
|
||
)
|
||
).mappings().first()
|
||
return row
|
||
|
||
|
||
async def _add_participant(db: AsyncSession, activity: Any, user_id: str, role: str, status: str, note: str = "") -> None:
|
||
await require_participatory_activity(db, activity['id'])
|
||
if activity["capacity"] is not None:
|
||
current = int(
|
||
(
|
||
await db.execute(
|
||
select(func.count()).select_from(participations).where(participations.c.activity_id == activity["id"])
|
||
)
|
||
).scalar()
|
||
or 0
|
||
)
|
||
if current >= int(activity["capacity"]):
|
||
raise HTTPException(status_code=409, detail="活动名额已满")
|
||
stamp = now_ms()
|
||
await db.execute(
|
||
insert(participations).values(
|
||
id=new_id(),
|
||
activity_id=activity["id"],
|
||
user_id=user_id,
|
||
role=role,
|
||
status=status,
|
||
note=note,
|
||
joined_at=stamp,
|
||
updated_at=stamp,
|
||
)
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------- 应用
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(_app: FastAPI):
|
||
if DEV_MODE and HOST not in ("127.0.0.1", "::1", "localhost"):
|
||
raise RuntimeError("开发验证码回显只能绑定本机地址,请关闭 WORKLOG_DEV_MODE 或修改 WORKLOG_HOST")
|
||
async with engine.begin() as conn:
|
||
await conn.run_sync(metadata.create_all)
|
||
columns = await conn.run_sync(lambda c: {col['name'] for col in inspect(c).get_columns('center_activity_meta')})
|
||
if 'material_id' not in columns:
|
||
await conn.execute(text('ALTER TABLE center_activity_meta ADD COLUMN material_id VARCHAR(32)'))
|
||
recruit_columns = await conn.run_sync(lambda c: {col['name'] for col in inspect(c).get_columns('recruit_announcements')})
|
||
if 'source_order' not in recruit_columns:
|
||
await conn.execute(text('ALTER TABLE recruit_announcements ADD COLUMN source_order INTEGER NOT NULL DEFAULT 0'))
|
||
await _migrate_legacy(conn)
|
||
# 一楼历史活动统一作为公开记录,历史参加数据保留存档但不再参与统计。
|
||
center_ids = select(center_activity_meta.c.activity_id)
|
||
await conn.execute(update(activities).where(activities.c.id.in_(center_ids)).values(visibility='public', capacity=None))
|
||
await conn.execute(update(join_links).where(join_links.c.activity_id.in_(center_ids), join_links.c.used == 0).values(used=2))
|
||
backup_task: asyncio.Task | None = None
|
||
if BACKUP_ENABLED:
|
||
hour, minute = parse_time(BACKUP_TIME)
|
||
backup_task = asyncio.create_task(backup_loop(_db_path, hour, minute, BACKUP_KEEP))
|
||
duty_task: asyncio.Task | None = None
|
||
upload_cleanup_task = asyncio.create_task(
|
||
center.orphan_upload_cleanup_loop(SessionLocal, lambda: _db_path.parent / 'uploads')
|
||
)
|
||
duty_path = Path(os.getenv("WORKLOG_DUTY_SCHEDULE", str(PROJECT_DIR / "duty/schedule.json")))
|
||
if duty_path.exists() and os.getenv("WORKLOG_DUTY_REMINDERS", "1").lower() not in ("0", "false", "no"):
|
||
async def duty_accounts():
|
||
async with SessionLocal() as db:
|
||
rows = await db.execute(select(users.c.display_name, users.c.email))
|
||
return [dict(row) for row in rows.mappings()]
|
||
|
||
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
|
||
finally:
|
||
if duty_task is not None:
|
||
duty_task.cancel()
|
||
await asyncio.gather(duty_task, return_exceptions=True)
|
||
upload_cleanup_task.cancel()
|
||
await asyncio.gather(upload_cleanup_task, return_exceptions=True)
|
||
if backup_task is not None:
|
||
backup_task.cancel()
|
||
await engine.dispose()
|
||
|
||
|
||
async def _migrate_legacy(conn) -> None:
|
||
"""老库平滑升级:users 补 phone 列;username 列允许为空(新注册只靠邮箱识别);
|
||
activities 的历史 pending 全部放行为 approved;一楼旧借用记录按库存安全迁移。"""
|
||
def _reflect(sync_conn):
|
||
insp = inspect(sync_conn)
|
||
names = insp.get_table_names()
|
||
return (
|
||
names,
|
||
{col["name"] for col in insp.get_columns("users")} if "users" in names else set(),
|
||
{col["name"] for col in insp.get_columns("activities")} if "activities" in names else set(),
|
||
)
|
||
|
||
tables, users_cols, activity_cols = await conn.run_sync(_reflect)
|
||
|
||
if "department" not in users_cols:
|
||
await conn.execute(text("ALTER TABLE users ADD COLUMN department VARCHAR(64) NOT NULL DEFAULT ''"))
|
||
if "email" not in users_cols:
|
||
await conn.execute(text("ALTER TABLE users ADD COLUMN email VARCHAR(255) NOT NULL DEFAULT ''"))
|
||
if "phone" not in users_cols:
|
||
await conn.execute(text("ALTER TABLE users ADD COLUMN phone VARCHAR(11) NOT NULL DEFAULT ''"))
|
||
if "password_set" not in users_cols:
|
||
# 老库的 password_hash 是注册时的随机占位值(用户本人不知道),
|
||
# 因此统一视为未设置密码,用户下次验证码登录时会被引导设置。
|
||
await conn.execute(text("ALTER TABLE users ADD COLUMN password_set INTEGER NOT NULL DEFAULT 0"))
|
||
for index in users.indexes:
|
||
if index.name in ("uq_users_email", "uq_users_phone"):
|
||
await conn.execute(CreateIndex(index, if_not_exists=True))
|
||
|
||
if "status" not in activity_cols:
|
||
await conn.execute(text("ALTER TABLE activities ADD COLUMN status VARCHAR(16) NOT NULL DEFAULT 'approved'"))
|
||
else:
|
||
# 去掉审核流:历史遗留的待审核活动全部放行
|
||
await conn.execute(
|
||
text("UPDATE activities SET status='approved' WHERE status IN ('pending','rejected')")
|
||
)
|
||
if "center_loans" in tables and "center_items" in tables:
|
||
await _migrate_center_loans(conn)
|
||
|
||
if "category" in activity_cols:
|
||
# SQLite 3.35+ 支持直接 DROP COLUMN
|
||
await conn.execute(text("ALTER TABLE activities DROP COLUMN category"))
|
||
|
||
code_columns = await conn.run_sync(lambda c: {col["name"] for col in inspect(c).get_columns("email_verifications")})
|
||
if "attempts" not in code_columns:
|
||
await conn.execute(text("ALTER TABLE email_verifications ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0"))
|
||
# 旧的六位明文验证码失效;会话和邮件链接保留有效性并转为摘要。
|
||
await conn.execute(delete(email_verifications).where(func.length(email_verifications.c.code) <= 10))
|
||
for table in (sessions, join_links):
|
||
tokens = (await conn.execute(select(table.c.token).where(func.length(table.c.token) != 64))).scalars().all()
|
||
for token in tokens:
|
||
await conn.execute(update(table).where(table.c.token == token).values(token=token_digest(token)))
|
||
|
||
|
||
async def _migrate_center_loans(conn) -> None:
|
||
"""扩展借出记录以支持与库存无关的登记,并迁移旧待审批记录。"""
|
||
await _migrate_center_loan_schema(conn)
|
||
rows = (await conn.execute(
|
||
select(center_loans)
|
||
.where(center_loans.c.status == 'pending')
|
||
.order_by(center_loans.c.created_at, center_loans.c.id)
|
||
)).mappings().all()
|
||
if not rows:
|
||
return
|
||
totals = dict((await conn.execute(select(center_items.c.id, center_items.c.quantity))).all())
|
||
active = dict((await conn.execute(
|
||
select(center_loans.c.item_id, func.coalesce(func.sum(center_loans.c.quantity), 0))
|
||
.where(center_loans.c.status == 'approved', center_loans.c.returned_at.is_(None))
|
||
.group_by(center_loans.c.item_id)
|
||
)).all())
|
||
for row in rows:
|
||
if row['returned_at'] is not None:
|
||
await conn.execute(
|
||
update(center_loans).where(center_loans.c.id == row['id']).values(status='returned')
|
||
)
|
||
continue
|
||
used = active.get(row['item_id'], 0)
|
||
available = max(0, totals.get(row['item_id'], 0) - used)
|
||
if row['quantity'] > 0 and row['quantity'] <= available:
|
||
await conn.execute(
|
||
update(center_loans).where(center_loans.c.id == row['id']).values(status='approved')
|
||
)
|
||
active[row['item_id']] = used + row['quantity']
|
||
else:
|
||
await conn.execute(
|
||
update(center_loans).where(center_loans.c.id == row['id']).values(
|
||
status='rejected',
|
||
reviewed_at=None,
|
||
review_note='免审批迁移:库存不足,原待审批记录未借出',
|
||
)
|
||
)
|
||
|
||
|
||
async def _migrate_center_loan_schema(conn) -> None:
|
||
"""SQLite 中支持库存外登记和登录页免登录借出,同时完整保留历史记录。"""
|
||
def _inspect(sync_conn):
|
||
columns = {column["name"]: column for column in inspect(sync_conn).get_columns("center_loans")}
|
||
item_id = columns.get("item_id")
|
||
user_id = columns.get("user_id")
|
||
if not item_id or not user_id:
|
||
return False
|
||
required = {"item_name", "guest_name", "guest_phone", "guest_college", "guest_activity_name"}
|
||
return (
|
||
not required.issubset(columns)
|
||
or not item_id.get("nullable", False)
|
||
or not user_id.get("nullable", False)
|
||
)
|
||
|
||
if not await conn.run_sync(_inspect):
|
||
return
|
||
|
||
legacy = "center_loans_legacy_schema"
|
||
await conn.execute(text(f"ALTER TABLE center_loans RENAME TO {legacy}"))
|
||
await conn.run_sync(center_loans.create)
|
||
source_columns = {
|
||
column["name"]
|
||
for column in await conn.run_sync(lambda c: inspect(c).get_columns(legacy))
|
||
}
|
||
|
||
def source(name, fallback="NULL"):
|
||
return name if name in source_columns else fallback
|
||
|
||
await conn.execute(text(f"""
|
||
INSERT INTO center_loans (
|
||
id, item_id, item_name, user_id, quantity, reason, contact,
|
||
guest_name, guest_phone, guest_college, guest_activity_name,
|
||
created_at, returned_at, status, reviewer_id, reviewed_at, review_note
|
||
)
|
||
SELECT
|
||
id, item_id, {source('item_name')}, user_id, quantity, reason, contact,
|
||
{source('guest_name')}, {source('guest_phone')}, {source('guest_college')}, {source('guest_activity_name')},
|
||
created_at, {source('returned_at')}, {source('status', "'approved'")},
|
||
{source('reviewer_id')}, {source('reviewed_at')}, {source('review_note', "''")}
|
||
FROM {legacy}
|
||
"""))
|
||
await conn.execute(text(f"DROP TABLE {legacy}"))
|
||
|
||
|
||
app = FastAPI(title="WorkLog 活动记录", version="2.0.0", lifespan=lifespan)
|
||
center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause)
|
||
center_duty.install(app, get_db, current_user)
|
||
center_export.install(app, get_db, current_user, visible_clause, lambda: _db_path.parent / 'uploads')
|
||
recruit.install(app, get_db, current_user, _db_path.parent / 'recruit-images')
|
||
|
||
def timetable_collectors():
|
||
values = os.getenv('WORKLOG_TIMETABLE_COLLECTORS')
|
||
emails = values.split(',') if values is not None else cfg('timetable', 'collector_emails', [])
|
||
return {email.strip().lower() for email in emails if email.strip()}
|
||
|
||
def timetable_admin_key():
|
||
return os.getenv('WORKLOG_TIMETABLE_ADMIN_KEY', str(cfg('timetable', 'admin_export_key', '')))
|
||
|
||
timetable_routes.install(app, get_db, current_user, lambda: _db_path.parent / 'timetables', timetable_collectors, timetable_admin_key)
|
||
|
||
|
||
@app.exception_handler(IntegrityError)
|
||
async def conflict_error(_request: Request, _exc: IntegrityError):
|
||
return JSONResponse({"detail": "记录已存在或已变更,请刷新后重试"}, status_code=409)
|
||
|
||
|
||
@app.middleware("http")
|
||
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
|
||
# 此独立回执入口依赖不可猜测的邮件令牌及 GET 页面签发的表单令牌;
|
||
# 邮件内置浏览器可能把合法表单提交标为 cross-site,其他入口仍严格检查。
|
||
token_confirmation_post = request.method == "POST" and re.fullmatch(r"/(?:duty-confirm|join|mail-test)/[A-Za-z0-9_-]{32,128}", request.url.path)
|
||
if not token_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"
|
||
):
|
||
response = JSONResponse({"detail": "不允许跨站提交"}, status_code=403)
|
||
else:
|
||
response = await call_next(request)
|
||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||
response.headers["X-Frame-Options"] = "DENY"
|
||
response.headers["Referrer-Policy"] = "no-referrer"
|
||
response.headers["Content-Security-Policy"] = (
|
||
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
|
||
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'none'; "
|
||
"frame-ancestors 'none'; form-action 'self'"
|
||
)
|
||
if request.url.path.startswith(("/api/", "/join/", "/duty-confirm/", "/mail-test/")):
|
||
response.headers["Cache-Control"] = "no-store"
|
||
elif request.method in ("GET", "HEAD") and (
|
||
request.url.path == "/"
|
||
or request.url.path.endswith(".html")
|
||
or not Path(request.url.path).suffix
|
||
):
|
||
# 让入口 HTML 每次重新校验,避免新脚本上线后仍被旧页面长期引用。
|
||
response.headers["Cache-Control"] = "no-cache"
|
||
elif request.method in ("GET", "HEAD") and Path(request.url.path).suffix in (".js", ".css"):
|
||
# 前端资源通过 ?v= 更新版本号;保留 ETag 校验以便紧急修复时立即生效。
|
||
response.headers["Cache-Control"] = "public, max-age=0, must-revalidate"
|
||
if request.url.path.startswith(("/join/", "/duty-confirm/", "/mail-test/")):
|
||
kind = "test" if request.url.path.startswith("/mail-test/") else ("duty" if request.url.path.startswith("/duty-confirm/") else "activity")
|
||
origin_kind = "none" if not origin else ("null" if origin == "null" else ("trusted" if origin in (own_origin, trusted_origin) else "other"))
|
||
site = request.headers.get("sec-fetch-site", "none")
|
||
site = site if site in ("none", "same-origin", "same-site", "cross-site") else "other"
|
||
print(f"[confirmation] {datetime.now(BEIJING):%Y-%m-%d %H:%M:%S} kind={kind} method={request.method} status={response.status_code} origin={origin_kind} site={site}", flush=True)
|
||
return response
|
||
|
||
|
||
@app.get("/api/health")
|
||
async def health() -> dict:
|
||
return {"ok": True, "time": now_ms()}
|
||
|
||
|
||
@app.get("/api/meta")
|
||
async def meta() -> dict:
|
||
return {"statuses": list(STATUSES), "departments": DEPARTMENTS, "time": now_ms()}
|
||
|
||
|
||
# ---------------------------------------------------------------- 邮箱验证码
|
||
|
||
def _random_code() -> str:
|
||
return f"{secrets.randbelow(1_000_000):06d}"
|
||
|
||
|
||
async def _send_email(to: str, subject: str, body: str, html: str | None = None) -> None:
|
||
"""通过 SMTP 发送邮件;未配置 SMTP 时抛错(调用方在开发模式下不会走到这里)。
|
||
超时保护:SMTP 网络抖动时快速失败,避免请求永久挂起。
|
||
所有发送成败都写入 logs/mail.log(maillog.log_mail)。"""
|
||
import aiosmtplib
|
||
from email.message import EmailMessage
|
||
from .maillog import log_mail
|
||
|
||
message = EmailMessage()
|
||
message["From"] = SMTP_FROM
|
||
message["To"] = to
|
||
message["Subject"] = subject
|
||
message.set_content(body)
|
||
if html:
|
||
message.add_alternative(html, subtype="html")
|
||
|
||
started = time.monotonic()
|
||
try:
|
||
if SMTP_TLS == "ssl":
|
||
await aiosmtplib.send(message, hostname=SMTP_HOST, port=SMTP_PORT, use_tls=True,
|
||
username=SMTP_USER or None, password=SMTP_PASSWORD or None,
|
||
timeout=15)
|
||
elif SMTP_TLS == "starttls":
|
||
await aiosmtplib.send(message, hostname=SMTP_HOST, port=SMTP_PORT, start_tls=True,
|
||
username=SMTP_USER or None, password=SMTP_PASSWORD or None,
|
||
timeout=15)
|
||
else:
|
||
await aiosmtplib.send(message, hostname=SMTP_HOST, port=SMTP_PORT,
|
||
username=SMTP_USER or None, password=SMTP_PASSWORD or None,
|
||
timeout=15)
|
||
log_mail("OK", to, subject, f"{time.monotonic() - started:.1f}s tls={SMTP_TLS} host={SMTP_HOST}:{SMTP_PORT}")
|
||
except aiosmtplib.errors.SMTPRecipientsRefused as exc:
|
||
# 收件人被拒(邮箱不存在等),把服务端的拒绝原因透出
|
||
log_mail("FAIL", to, subject, f"RecipientsRefused: {exc}")
|
||
raise HTTPException(status_code=400, detail="邮件服务器拒绝该收件地址,请检查邮箱") from exc
|
||
except aiosmtplib.errors.SMTPAuthenticationError as exc:
|
||
# 授权码被拒(535):多数是授权码失效或账号 SMTP 服务被风控
|
||
log_mail("FAIL", to, subject, f"认证失败(535): {exc}")
|
||
raise HTTPException(
|
||
status_code=502,
|
||
detail="邮件服务认证失败(授权码可能已失效),请联系管理员检查邮箱设置",
|
||
) from exc
|
||
except (asyncio.TimeoutError, OSError, aiosmtplib.errors.SMTPException) as exc:
|
||
# QQ 等服务商在认证被拒时不回 535 而是直接断连(表现为 SMTPServerDisconnected),
|
||
# 连不上和被拒绝对外要区分开,便于管理员排查
|
||
elapsed = f"{time.monotonic() - started:.1f}s"
|
||
log_mail("FAIL", to, subject, f"{type(exc).__name__}({elapsed}): {exc}")
|
||
text_msg = str(exc).lower()
|
||
if "unexpected eof" in text_msg or "connection lost" in text_msg:
|
||
raise HTTPException(
|
||
status_code=502,
|
||
detail="邮件服务器拒绝了本次发信(授权码可能已失效或账号发信被限制),请联系管理员检查邮箱设置",
|
||
) from exc
|
||
raise HTTPException(status_code=502, detail="邮件服务器连接失败,请稍后重试") from exc
|
||
|
||
|
||
# ---------------------------------------------------------------- 新活动邮件通知
|
||
|
||
def _fmt_dt(ms: int) -> str:
|
||
return time.strftime("%Y-%m-%d %H:%M", time.localtime(ms / 1000))
|
||
|
||
|
||
def _notify_mail_html(organizer_name: str, activity: Any, join_url: str, portal_url: str) -> str:
|
||
"""新活动通知邮件(HTML + 纯文本双份,纯文本由 set_content 提供)。"""
|
||
organizer_name = escape(organizer_name)
|
||
activity = {**dict(activity), **{key: escape(activity[key] or "") for key in ("title", "location", "description")}}
|
||
join_url, portal_url = escape(join_url, quote=True), escape(portal_url, quote=True)
|
||
detail = (
|
||
f'<tr><td style="padding:6px 0;color:#6b7280;width:72px;">时间</td>'
|
||
f'<td style="padding:6px 0;">{_fmt_dt(activity["start_at"])}</td></tr>'
|
||
f'<tr><td style="padding:6px 0;color:#6b7280;">地点</td>'
|
||
f'<td style="padding:6px 0;">{activity["location"] or "(未填写)"}</td></tr>'
|
||
)
|
||
desc = (activity["description"] or "").strip()
|
||
if desc:
|
||
detail += (
|
||
f'<tr><td style="padding:6px 0;color:#6b7280;vertical-align:top;">说明</td>'
|
||
f'<td style="padding:6px 0;white-space:pre-wrap;">{desc}</td></tr>'
|
||
)
|
||
return f"""\
|
||
<div style="margin:0;padding:24px;background:#f3f4f6;font-family:'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif;">
|
||
<div style="max-width:520px;margin:0 auto;background:#ffffff;border-radius:12px;padding:28px 32px;">
|
||
<p style="margin:0 0 4px;font-size:13px;color:#9ca3af;">WorkLog 活动记录</p>
|
||
<h2 style="margin:0 0 18px;font-size:20px;color:#111827;">{organizer_name} 发起了一场新活动</h2>
|
||
<div style="border-left:3px solid #2563eb;padding-left:14px;margin-bottom:22px;">
|
||
<p style="margin:0 0 8px;font-size:17px;font-weight:600;color:#111827;">{activity["title"]}</p>
|
||
<table style="font-size:14px;color:#374151;border-collapse:collapse;">{detail}</table>
|
||
</div>
|
||
<p style="margin:0 0 18px;font-size:14px;color:#6b7280;">如果你也参加了这场活动,点下面的按钮一条记录即可:</p>
|
||
<p style="margin:0 0 20px;">
|
||
<a href="{join_url}"
|
||
style="display:inline-block;background:#2563eb;color:#ffffff;text-decoration:none;
|
||
font-size:15px;font-weight:600;padding:11px 28px;border-radius:8px;">我也参加过</a>
|
||
</p>
|
||
<p style="margin:0;font-size:12px;color:#9ca3af;">
|
||
打开链接后确认参加,链接 {JOIN_LINK_DAYS} 天内有效。<br>
|
||
也可以<a href="{portal_url}" style="color:#2563eb;">打开 WorkLog</a> 查看全部活动记录。
|
||
</p>
|
||
</div>
|
||
</div>"""
|
||
|
||
|
||
def _notify_mail_text(organizer_name: str, activity: Any, join_url: str, portal_url: str) -> str:
|
||
lines = [
|
||
f"{organizer_name} 发起了一场新活动:{activity['title']}",
|
||
f"时间:{_fmt_dt(activity['start_at'])}",
|
||
f"地点:{activity['location'] or '(未填写)'}",
|
||
]
|
||
desc = (activity["description"] or "").strip()
|
||
if desc:
|
||
lines.append(f"说明:{desc}")
|
||
lines += [
|
||
"",
|
||
f"如果你也参加了这场活动,打开下面的链接并确认参加({JOIN_LINK_DAYS} 天内有效):",
|
||
join_url,
|
||
"",
|
||
f"也可以打开 WorkLog 查看全部活动记录:{portal_url}",
|
||
]
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _site_base_url(request: Request | None = None) -> str:
|
||
"""只使用受信任的部署配置,忽略请求里的域名和代理头。"""
|
||
if BASE_URL:
|
||
return BASE_URL
|
||
return f"http://127.0.0.1:{PORT}"
|
||
|
||
|
||
async def _notify_new_activity(activity_id: str, organizer_name: str, base_url: str) -> None:
|
||
"""给其他已注册用户通知新活动;最多同时发送3封,单封失败不影响其他收件人。"""
|
||
from .models import join_links # noqa: F401 (保证模块已被导入)
|
||
|
||
async with SessionLocal() as db:
|
||
row = (await db.execute(select(activities).where(activities.c.id == activity_id))).mappings().first()
|
||
if row is None: # 活动可能已被删除
|
||
return
|
||
if await is_center_activity(db, activity_id):
|
||
return
|
||
if row["visibility"] != "public":
|
||
return # 私密活动不群发
|
||
recipients = (
|
||
await db.execute(
|
||
select(users.c.id, users.c.email, users.c.display_name).where(
|
||
and_(users.c.email != "", users.c.id != row["organizer_id"])
|
||
)
|
||
)
|
||
).all()
|
||
|
||
portal = f"{base_url}/"
|
||
messages = []
|
||
for user_id, email, _name in recipients:
|
||
token = new_token()
|
||
messages.append((email, token, f"【WorkLog】{organizer_name} 发起了新活动:{row['title']}"))
|
||
await db.execute(insert(join_links).values(
|
||
id=new_id(), token=token_digest(token), activity_id=activity_id, user_id=user_id,
|
||
expires_at=now_ms() + JOIN_LINK_DAYS * 86_400_000,
|
||
used=0, created_at=now_ms(),
|
||
))
|
||
await db.commit()
|
||
|
||
semaphore = asyncio.Semaphore(3)
|
||
async def send_one(email: str, token: str, subject: str) -> bool:
|
||
async with semaphore:
|
||
join_url = f"{base_url}/join/{token}"
|
||
html = _notify_mail_html(organizer_name, row, join_url, portal)
|
||
plain = _notify_mail_text(organizer_name, row, join_url, portal)
|
||
try:
|
||
await _send_email(email, subject, plain, html)
|
||
return True
|
||
except Exception as exc:
|
||
print(f"[notify] 发送失败 to={email}: {exc}", flush=True)
|
||
return False
|
||
|
||
results = await asyncio.gather(*(send_one(*message) for message in messages))
|
||
ok = sum(results)
|
||
failed = len(results) - ok
|
||
# 顺手清掉过期的旧链接
|
||
await db.execute(delete(join_links).where(join_links.c.expires_at < now_ms()))
|
||
await db.commit()
|
||
print(f"[notify] 活动「{row['title']}」通知完成:成功 {ok},失败 {failed}", flush=True)
|
||
|
||
|
||
async def _count_recent_codes(db: AsyncSession, email: str) -> int:
|
||
"""同一邮箱 10 分钟内最多 5 条验证码,防刷。"""
|
||
since = now_ms() - 10 * 60_000
|
||
return int(
|
||
(
|
||
await db.execute(
|
||
select(func.count()).select_from(email_verifications)
|
||
.where(and_(email_verifications.c.email == email, email_verifications.c.created_at >= since))
|
||
)
|
||
).scalar()
|
||
or 0
|
||
)
|
||
|
||
|
||
async def _auth_limit(db: AsyncSession, key: str, maximum: int) -> None:
|
||
"""SQLite 原子计数,跨请求/进程共享;失败请求也计数,不信任代理 IP 头。"""
|
||
stamp = now_ms()
|
||
from sqlalchemy import case
|
||
expired = auth_limits.c.window_start <= stamp - 600_000
|
||
statement = sqlite_insert(auth_limits).values(key=token_digest(key), window_start=stamp, count=1)
|
||
statement = statement.on_conflict_do_update(
|
||
index_elements=[auth_limits.c.key],
|
||
set_={"count": case((expired, 1), else_=auth_limits.c.count + 1),
|
||
"window_start": case((expired, stamp), else_=auth_limits.c.window_start)},
|
||
)
|
||
# Avoid SQLite RETURNING (added in 3.35). The upsert takes SQLite's write lock;
|
||
# read its counter in the same transaction so older server builds stay atomic.
|
||
await db.execute(statement)
|
||
count = (await db.execute(select(auth_limits.c.count).where(auth_limits.c.key == token_digest(key)))).scalar_one()
|
||
await db.execute(delete(auth_limits).where(auth_limits.c.window_start < stamp - 86_400_000))
|
||
await db.commit()
|
||
if count > maximum:
|
||
raise HTTPException(status_code=429, detail="操作过于频繁,请稍后再试", headers={"Retry-After": "600"})
|
||
|
||
|
||
def _client_ip(request: Request) -> str:
|
||
return request.client.host if request.client else "unknown"
|
||
|
||
|
||
@app.post("/api/auth/send-code")
|
||
async def send_code(payload: SendCodeIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict:
|
||
return await _issue_code(payload, request, db)
|
||
|
||
|
||
async def _issue_code(payload: SendCodeIn, request: Request, db: AsyncSession, scoped_purpose: str | None = None) -> dict:
|
||
purpose = scoped_purpose or payload.purpose
|
||
if DEV_MODE:
|
||
try:
|
||
local = ip_address(_client_ip(request)).is_loopback
|
||
except ValueError:
|
||
local = False
|
||
if not local or request.url.hostname not in ("127.0.0.1", "localhost", "::1"):
|
||
raise HTTPException(status_code=403, detail="开发验证码仅供本机使用")
|
||
elif not (SMTP_HOST and SMTP_USER and SMTP_PASSWORD):
|
||
raise HTTPException(status_code=503, detail="邮件服务未配置,请联系管理员")
|
||
await _auth_limit(db, "send-ip:" + _client_ip(request), 30)
|
||
email = payload.email
|
||
if payload.purpose == "register":
|
||
exists = await _find_user_by_email(db, email)
|
||
if exists is not None:
|
||
raise HTTPException(status_code=409, detail="该邮箱已被注册")
|
||
elif payload.purpose == "reset" and await _find_user_by_email(db, email) is None:
|
||
raise HTTPException(status_code=404, detail="该邮箱尚未注册")
|
||
if await _count_recent_codes(db, email) >= 5:
|
||
raise HTTPException(status_code=429, detail="验证码发送过于频繁,请稍后再试")
|
||
await _auth_limit(db, "send-email:" + email, 5)
|
||
|
||
code = _random_code()
|
||
code_hash = await asyncio.to_thread(hash_password, code)
|
||
stamp = now_ms()
|
||
await db.execute(update(email_verifications).where(
|
||
email_verifications.c.email == email, email_verifications.c.purpose == purpose,
|
||
email_verifications.c.used == 0,
|
||
).values(used=1))
|
||
await db.execute(
|
||
insert(email_verifications).values(
|
||
id=new_id(), email=email, code=code_hash, purpose=purpose,
|
||
expires_at=stamp + EMAIL_CODE_TTL_MIN * 60_000, used=0, created_at=stamp,
|
||
)
|
||
)
|
||
await db.commit()
|
||
|
||
if DEV_MODE:
|
||
# 仅显式启用且来自本机的开发请求可以看到验证码。
|
||
return {"ok": True, "dev_code": code, "dev_mode": True}
|
||
|
||
try:
|
||
await _send_email(
|
||
email, "WorkLog 更换邮箱验证码" if scoped_purpose else "WorkLog 验证码",
|
||
f"你的验证码是 {code},{EMAIL_CODE_TTL_MIN} 分钟内有效。如果不是你本人的操作,请忽略本邮件。",
|
||
)
|
||
except HTTPException:
|
||
raise
|
||
except Exception as exc: # 兜底:其他未预期的发信错误
|
||
raise HTTPException(status_code=502, detail="邮件发送失败,请稍后重试") from exc
|
||
return {"ok": True, "dev_mode": False}
|
||
|
||
|
||
async def _consume_email_code(db: AsyncSession, email: str, code: str, purpose: str) -> None:
|
||
row = (
|
||
await db.execute(
|
||
select(email_verifications)
|
||
.where(and_(
|
||
email_verifications.c.email == email,
|
||
email_verifications.c.purpose == purpose,
|
||
email_verifications.c.used == 0,
|
||
))
|
||
.order_by(email_verifications.c.created_at.desc())
|
||
.limit(1)
|
||
)
|
||
).mappings().first()
|
||
if row is None:
|
||
raise HTTPException(status_code=400, detail="验证码不正确")
|
||
if row["expires_at"] <= now_ms():
|
||
raise HTTPException(status_code=400, detail="验证码已过期,请重新获取")
|
||
attempt = await db.execute(update(email_verifications).where(
|
||
email_verifications.c.id == row["id"], email_verifications.c.used == 0,
|
||
email_verifications.c.attempts < 5,
|
||
).values(attempts=email_verifications.c.attempts + 1))
|
||
await db.commit()
|
||
if attempt.rowcount != 1:
|
||
raise HTTPException(status_code=429, detail="验证码尝试次数过多,请重新获取")
|
||
if not await asyncio.to_thread(verify_password, code.strip(), row["code"]):
|
||
raise HTTPException(status_code=400, detail="验证码不正确")
|
||
consumed = await db.execute(update(email_verifications).where(
|
||
email_verifications.c.id == row["id"], email_verifications.c.used == 0,
|
||
email_verifications.c.expires_at > now_ms(),
|
||
).values(used=1))
|
||
await db.commit()
|
||
if consumed.rowcount != 1:
|
||
raise HTTPException(status_code=400, detail="验证码已失效,请重新获取")
|
||
|
||
|
||
# ---------------------------------------------------------------- 账号
|
||
|
||
def _email_change_purpose(user: dict, kind: str) -> str:
|
||
return f"ce-{kind}:" + token_digest(user["id"] + ":" + user["email"].lower())[:24]
|
||
|
||
|
||
async def _check_new_email(email: str, user: dict, db: AsyncSession):
|
||
if email == user["email"].lower():
|
||
raise HTTPException(status_code=409, detail="新邮箱不能与当前邮箱相同")
|
||
if await _find_user_by_email(db, email) is not None:
|
||
raise HTTPException(status_code=409, detail="该邮箱已被其他账号使用")
|
||
|
||
|
||
@app.post("/api/auth/email/new-code")
|
||
async def send_new_email_code(payload: NewEmailIn, request: Request, user: dict = Depends(current_user), db: AsyncSession = Depends(get_db)):
|
||
await _auth_limit(db, "change-email:" + user["id"], 10)
|
||
await _check_new_email(payload.email, user, db)
|
||
return await _issue_code(SendCodeIn(email=payload.email, purpose="bind"), request, db, _email_change_purpose(user, "new"))
|
||
|
||
|
||
async def _check_change_code(db, email, code, purpose):
|
||
email = email.strip().lower()
|
||
row = (await db.execute(select(email_verifications).where(
|
||
email_verifications.c.email == email, email_verifications.c.purpose == purpose,
|
||
email_verifications.c.used == 0,
|
||
).order_by(email_verifications.c.created_at.desc()).limit(1))).mappings().first()
|
||
if row is None or row["expires_at"] <= now_ms():
|
||
raise HTTPException(status_code=400, detail="验证码无效或已过期,请重新获取")
|
||
attempt = await db.execute(update(email_verifications).where(
|
||
email_verifications.c.id == row["id"], email_verifications.c.used == 0,
|
||
email_verifications.c.attempts < 5,
|
||
).values(attempts=email_verifications.c.attempts + 1))
|
||
await db.commit()
|
||
if attempt.rowcount != 1:
|
||
raise HTTPException(status_code=429, detail="验证码尝试次数过多,请重新获取")
|
||
if not await asyncio.to_thread(verify_password, code, row["code"]):
|
||
raise HTTPException(status_code=400, detail="验证码不正确")
|
||
return row["id"]
|
||
|
||
|
||
@app.post("/api/auth/email/change")
|
||
async def change_email(payload: ChangeEmailIn, request: Request, user: dict = Depends(current_user), db: AsyncSession = Depends(get_db)):
|
||
await _auth_limit(db, "verify-ip:" + _client_ip(request), 60)
|
||
await _check_new_email(payload.email, user, db)
|
||
new_id = await _check_change_code(db, payload.email, payload.new_code, _email_change_purpose(user, "new"))
|
||
consumed = await db.execute(update(email_verifications).where(
|
||
email_verifications.c.id == new_id, email_verifications.c.used == 0,
|
||
email_verifications.c.expires_at > now_ms(),
|
||
).values(used=1))
|
||
if consumed.rowcount != 1:
|
||
await db.rollback()
|
||
raise HTTPException(status_code=409, detail="验证码已失效,请重新获取")
|
||
changed = await db.execute(update(users).where(users.c.id == user["id"], users.c.email == user["email"]).values(email=payload.email))
|
||
if changed.rowcount != 1:
|
||
await db.rollback()
|
||
raise HTTPException(status_code=409, detail="绑定邮箱已变化,请刷新页面")
|
||
current_token = request.headers.get("authorization", "")[7:].strip()
|
||
await db.execute(delete(sessions).where(sessions.c.user_id == user["id"], sessions.c.token != token_digest(current_token)))
|
||
await db.execute(update(email_verifications).where(func.lower(email_verifications.c.email) == user["email"].lower(), email_verifications.c.used == 0).values(used=1))
|
||
await db.commit()
|
||
fresh = (await db.execute(select(users).where(users.c.id == user["id"]))).mappings().one()
|
||
return {"user": user_public(fresh, include_contact=True)}
|
||
|
||
@app.post("/api/auth/register")
|
||
async def register(payload: RegisterIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict:
|
||
await _auth_limit(db, "verify-ip:" + _client_ip(request), 60)
|
||
exists = await _find_user_by_email(db, payload.email)
|
||
if exists is not None:
|
||
raise HTTPException(status_code=409, detail="该邮箱已被注册")
|
||
phone_taken = (
|
||
await db.execute(select(users).where(users.c.phone == payload.phone))
|
||
).mappings().first()
|
||
if phone_taken is not None:
|
||
raise HTTPException(status_code=409, detail="该手机号已被绑定")
|
||
|
||
# 验证码校验(一次性)
|
||
await _consume_email_code(db, payload.email, payload.email_code, "register")
|
||
|
||
user_id = new_id()
|
||
stamp = now_ms()
|
||
display_name = payload.display_name.strip()
|
||
# username 不再用于登录,只作为展示用的唯一句柄(@xxx),由后端从邮箱前缀生成
|
||
username = await _unique_username(db, payload.email.split("@")[0])
|
||
await db.execute(
|
||
insert(users).values(
|
||
id=user_id,
|
||
username=username,
|
||
display_name=display_name,
|
||
department=payload.department.strip(),
|
||
email=payload.email,
|
||
phone=payload.phone,
|
||
password_hash=await asyncio.to_thread(hash_password, payload.password),
|
||
password_set=1,
|
||
role="member",
|
||
bio="",
|
||
created_at=stamp,
|
||
last_login_at=stamp,
|
||
)
|
||
)
|
||
token = await _issue_session(db, user_id, stamp)
|
||
await db.commit()
|
||
return {
|
||
"token": token,
|
||
"user": {"id": user_id, "username": username, "display_name": display_name,
|
||
"department": payload.department.strip(), "email": payload.email,
|
||
"phone": payload.phone, "bio": "", "created_at": stamp, "has_password": True},
|
||
}
|
||
|
||
|
||
async def _unique_username(db: AsyncSession, base: str) -> str:
|
||
"""由邮箱前缀生成唯一的 @handle:bugfix、bugfix2、bugfix3…纯中文姓名没有可用字符时回退随机串。"""
|
||
cleaned = re.sub(r"[^A-Za-z0-9_.-]", "", base.strip().lower()).strip("._-")
|
||
if not cleaned or len(cleaned) < 3:
|
||
cleaned = "u" + uuid.uuid4().hex[:8]
|
||
candidate = cleaned[:32]
|
||
n = 1
|
||
while True:
|
||
row = await _find_user_by_username(db, candidate)
|
||
if row is None:
|
||
return candidate
|
||
n += 1
|
||
suffix = str(n)
|
||
candidate = cleaned[: 32 - len(suffix)] + suffix
|
||
|
||
|
||
async def _find_user_by_username(db: AsyncSession, username: str):
|
||
return (
|
||
await db.execute(select(users).where(func.lower(users.c.username) == username.strip().lower()))
|
||
).mappings().first()
|
||
|
||
|
||
@app.post("/api/auth/login")
|
||
async def login(payload: LoginIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict:
|
||
await _auth_limit(db, "verify-ip:" + _client_ip(request), 60)
|
||
user = await _find_user_by_email(db, payload.email)
|
||
if user is None:
|
||
raise HTTPException(status_code=401, detail="邮箱或密码/验证码不正确")
|
||
if payload.password is not None:
|
||
# password_set=0 表示用户从未真正设置过密码(老库里只有随机占位值),
|
||
# 这类账号必须走验证码登录,不能凭占位 hash 校验密码。
|
||
password_ready = bool(user["password_set"] if "password_set" in user.keys() else 0) and bool(
|
||
user["password_hash"]
|
||
)
|
||
valid_password = password_ready and await asyncio.to_thread(
|
||
verify_password, payload.password, user["password_hash"]
|
||
)
|
||
if not valid_password:
|
||
raise HTTPException(status_code=401, detail="邮箱或密码不正确")
|
||
else:
|
||
await _consume_email_code(db, payload.email, payload.email_code or "", "login")
|
||
stamp = now_ms()
|
||
await db.execute(update(users).where(users.c.id == user["id"]).values(last_login_at=stamp))
|
||
token = await _issue_session(db, user["id"], stamp)
|
||
await db.commit()
|
||
return {"token": token, "user": user_public(user, include_contact=True)}
|
||
|
||
|
||
@app.post("/api/auth/set-password")
|
||
async def set_password(payload: SetPasswordIn, user: dict = Depends(current_user), db: AsyncSession = Depends(get_db)) -> dict:
|
||
"""登录态下设置/修改密码:无需邮箱验证码(当前会话即凭据)。
|
||
无密码老账号验证码登录后,前端会强制引导到这里。"""
|
||
password_hash = await asyncio.to_thread(hash_password, payload.password)
|
||
await db.execute(
|
||
update(users).where(users.c.id == user["id"]).values(password_hash=password_hash, password_set=1)
|
||
)
|
||
await db.commit()
|
||
return {"ok": True, "has_password": True}
|
||
|
||
|
||
@app.post("/api/auth/reset-password")
|
||
async def reset_password(payload: ResetPasswordIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict:
|
||
await _auth_limit(db, "verify-ip:" + _client_ip(request), 60)
|
||
user = await _find_user_by_email(db, payload.email)
|
||
if user is None:
|
||
raise HTTPException(status_code=404, detail="该邮箱尚未注册")
|
||
await _consume_email_code(db, payload.email, payload.email_code, "reset")
|
||
password_hash = await asyncio.to_thread(hash_password, payload.password)
|
||
await db.execute(
|
||
update(users).where(users.c.id == user["id"]).values(password_hash=password_hash, password_set=1)
|
||
)
|
||
await db.execute(delete(sessions).where(sessions.c.user_id == user["id"]))
|
||
await db.commit()
|
||
return {"ok": True}
|
||
|
||
|
||
async def _issue_session(db: AsyncSession, user_id: str, stamp: int) -> str:
|
||
token = new_token()
|
||
await db.execute(
|
||
insert(sessions).values(
|
||
token=token_digest(token),
|
||
user_id=user_id,
|
||
created_at=stamp,
|
||
expires_at=stamp + SESSION_DAYS * 86_400_000,
|
||
)
|
||
)
|
||
return token
|
||
|
||
|
||
@app.post("/api/auth/logout")
|
||
async def logout(request: Request, db: AsyncSession = Depends(get_db), _user: dict = Depends(current_user)) -> dict:
|
||
header = request.headers.get("authorization", "")
|
||
token = header[7:].strip() if header.lower().startswith("bearer ") else ""
|
||
if token:
|
||
await db.execute(delete(sessions).where(sessions.c.token == token_digest(token)))
|
||
await db.commit()
|
||
return {"ok": True}
|
||
|
||
|
||
@app.get("/api/auth/me")
|
||
async def me(user: dict = Depends(current_user), db: AsyncSession = Depends(get_db)) -> dict:
|
||
return {"user": user_public(user, include_contact=True), "stats": await user_stats(db, user["id"])}
|
||
|
||
|
||
@app.patch("/api/auth/me")
|
||
async def update_me(payload: ProfileIn, user: dict = Depends(current_user), db: AsyncSession = Depends(get_db)) -> dict:
|
||
changes: dict[str, Any] = {}
|
||
if payload.display_name is not None:
|
||
name = payload.display_name.strip()
|
||
if not name:
|
||
raise HTTPException(status_code=400, detail="姓名不能为空")
|
||
changes["display_name"] = name
|
||
if payload.bio is not None:
|
||
changes["bio"] = payload.bio.strip()
|
||
if payload.department is not None:
|
||
if payload.department and payload.department not in DEPARTMENTS:
|
||
raise HTTPException(status_code=400, detail="部门必须是:" + "、".join(DEPARTMENTS))
|
||
changes["department"] = payload.department.strip()
|
||
if payload.phone is not None:
|
||
if payload.phone and payload.phone != user.get("phone"):
|
||
phone_taken = (
|
||
await db.execute(select(users).where(users.c.phone == payload.phone, users.c.id != user["id"]))
|
||
).mappings().first()
|
||
if phone_taken is not None:
|
||
raise HTTPException(status_code=409, detail="该手机号已被绑定")
|
||
changes["phone"] = payload.phone
|
||
if not changes:
|
||
raise HTTPException(status_code=400, detail="没有需要修改的内容")
|
||
await db.execute(update(users).where(users.c.id == user["id"]).values(**changes))
|
||
await db.commit()
|
||
fresh = (await db.execute(select(users).where(users.c.id == user["id"]))).mappings().first()
|
||
return {"user": user_public(fresh, include_contact=True)}
|
||
|
||
|
||
# ---------------------------------------------------------------- 成员
|
||
|
||
@app.get("/api/duty/current")
|
||
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:
|
||
schedule = load_schedule(path)
|
||
data = duty_status(schedule, datetime.now(BEIJING))
|
||
accounts = [dict(r) for r in (await db.execute(select(users.c.id, 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"]]
|
||
for receipt in shift["reminders"]:
|
||
owners = [a for a in accounts if a["display_name"].strip() == receipt["name"]]
|
||
receipt["is_self"] = len(owners) == 1 and owners[0]["id"] == _viewer["id"]
|
||
receipt["can_confirm"] = receipt["is_self"] and not receipt["confirmed_at"] and time.time() < shift["end_at"] / 1000
|
||
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.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)):
|
||
# 兼容旧客户端读取历史数据,不再创建或补记任何缺勤记录。
|
||
return {"items": await asyncio.to_thread(duty_receipts.absence_records, _duty_state(), limit, offset), "recording_enabled": False}
|
||
|
||
|
||
@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
|
||
|
||
|
||
class ButtonTestIn(BaseModel):
|
||
kind: Literal["duty", "activity"]
|
||
|
||
|
||
@app.post("/api/auth/test-button-email")
|
||
async def test_button_email(payload: ButtonTestIn, 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分钟内只能测试一次,请稍后重试")
|
||
token = await asyncio.to_thread(duty_receipts.create_button_test, _duty_state(), payload.kind, time.time())
|
||
label = '值班确认' if payload.kind == 'duty' else '活动参加'
|
||
url = _site_base_url() + '/mail-test/' + token
|
||
text = f'这是{label}按钮测试邮件。打开链接后请点击页面中的确认按钮。仅用于测试,不改变正式活动和值班记录。链接24小时内有效。\n{url}'
|
||
html = f'<div style="font-family:sans-serif;line-height:1.8"><h2>{label}按钮测试</h2><p>仅测试邮件按钮跳转和确认,不改变正式记录。链接24小时内有效。</p><a href="{escape(url, quote=True)}" style="display:inline-block;padding:12px 24px;background:#28664f;color:white;border-radius:8px;text-decoration:none">{label}(测试)</a></div>'
|
||
await _send_email(email, f'【WorkLog测试】{label}按钮', text, html)
|
||
return {'ok': True, 'retry_after': 120}
|
||
|
||
|
||
@app.get('/mail-test/{token}', include_in_schema=False)
|
||
@app.post('/mail-test/{token}', include_in_schema=False)
|
||
async def confirm_button_test(token: str, request: Request):
|
||
from urllib.parse import parse_qs
|
||
kind = await asyncio.to_thread(duty_receipts.button_test, _duty_state(), token, time.time())
|
||
if not kind:
|
||
return HTMLResponse(_confirmation_page('测试链接无效或已过期。', title='邮件按钮测试'), status_code=410)
|
||
label = '值班确认' if kind == 'duty' else '活动参加'
|
||
if request.method == 'GET':
|
||
nonce = await asyncio.to_thread(duty_receipts.issue_activity_form, _duty_state(), token, 'mail-test')
|
||
return HTMLResponse(_confirmation_page('此操作仅用于按钮测试,不改变正式记录。', nonce, title=label + '测试', button_label='确认测试'))
|
||
body = await request.body()
|
||
nonce = parse_qs(body.decode('utf-8', errors='replace')).get('confirmation_token', [None])[0] if len(body) <= 4096 else None
|
||
if not await asyncio.to_thread(duty_receipts.validate_activity_form, _duty_state(), token, nonce, 'mail-test'):
|
||
return HTMLResponse(_confirmation_page('请重新打开测试邮件,再点击确认。', title='邮件按钮测试'), status_code=403)
|
||
await asyncio.to_thread(duty_receipts.button_test, _duty_state(), token, time.time(), True)
|
||
return HTMLResponse(_confirmation_page('按钮测试确认成功,正式活动和值班记录未发生变化。', title=label + '测试'))
|
||
|
||
|
||
class DutySiteConfirmIn(BaseModel):
|
||
model_config = {"extra": "forbid"}
|
||
start_at: int
|
||
|
||
|
||
@app.post("/api/duty/confirm")
|
||
async def confirm_own_duty(payload: DutySiteConfirmIn, 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), None)
|
||
if shift is None:
|
||
raise HTTPException(status_code=409, detail="值班安排已变化或本轮已结束,请刷新页面")
|
||
receipt = next((r for r in shift["reminders"] if r["is_self"]), None)
|
||
if receipt is None:
|
||
raise HTTPException(status_code=403, detail="只能确认自己的值班;同名账号请先联系负责人核对")
|
||
day = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING).date().isoformat()
|
||
confirmed = await asyncio.to_thread(duty_receipts.confirm_on_site, _duty_state(), day, shift["slot"], receipt["name"], viewer["email"], time.time(), shift["end_at"] / 1000)
|
||
if confirmed is None:
|
||
raise HTTPException(status_code=409, detail="本轮值班已结束,不能补确认")
|
||
return {"ok": True, "confirmed_at": confirmed}
|
||
|
||
|
||
@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:
|
||
duty_title = data.get("title", "值班提醒")
|
||
sent = await duty_receipts.send_notice(_duty_state(), start.date().isoformat(), {payload.name: [shift["slot"]]}, email, shift["end_at"] / 1000, _send_email, f"{duty_title}|邮件提醒", f"机构:{data.get('organization', '招生就业服务队')}\n日期:{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):
|
||
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(_confirmation_page("确认链接无效、表单已更新或本轮值班已结束,请重新打开邮件链接。"), status_code=410)
|
||
text = ";".join(f"{day} {slot} {name}" for day, slot, name in targets)
|
||
if request.method == "GET":
|
||
nonce = await asyncio.to_thread(duty_receipts.issue_confirmation_form, _duty_state(), token, now)
|
||
if not nonce:
|
||
return HTMLResponse(_confirmation_page("本轮确认链接已失效。"), status_code=410)
|
||
return HTMLResponse(_confirmation_page("请确认已知晓:" + text, nonce))
|
||
return HTMLResponse(_confirmation_page("已确认值班安排,谢谢。本次确认仅记录值班回执。"))
|
||
|
||
|
||
_confirmation_page = confirmation_page
|
||
|
||
@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)
|
||
public_activities = int(
|
||
(
|
||
await db.execute(
|
||
select(func.count()).select_from(activities)
|
||
.where(activities.c.visibility == "public", normal_activity_clause())
|
||
)
|
||
).scalar()
|
||
or 0
|
||
)
|
||
records = int(
|
||
(
|
||
await db.execute(
|
||
select(func.count())
|
||
.select_from(participations)
|
||
.join(activities, activities.c.id == participations.c.activity_id)
|
||
.where(participations.c.status != "pending", activities.c.visibility == "public", normal_activity_clause())
|
||
)
|
||
).scalar()
|
||
or 0
|
||
)
|
||
upcoming = int(
|
||
(
|
||
await db.execute(
|
||
select(func.count()).select_from(activities)
|
||
.where(and_(activities.c.visibility == "public", activities.c.start_at >= now_ms(), normal_activity_clause()))
|
||
)
|
||
).scalar()
|
||
or 0
|
||
)
|
||
departments = (
|
||
await db.execute(
|
||
select(users.c.department, func.count().label("n"))
|
||
.where(users.c.department != "")
|
||
.group_by(users.c.department)
|
||
.order_by(func.count().desc())
|
||
)
|
||
).all()
|
||
return {
|
||
"members": members,
|
||
"activities": public_activities,
|
||
"records": records,
|
||
"upcoming": upcoming,
|
||
"departments": [{"department": row[0], "count": int(row[1])} for row in departments],
|
||
}
|
||
|
||
|
||
@app.get("/api/users")
|
||
async def list_users(q: str = "", department: str = "", db: AsyncSession = Depends(get_db), _viewer: dict = Depends(current_user)) -> dict:
|
||
stmt = select(users).order_by(users.c.created_at.asc())
|
||
if q.strip():
|
||
like = f"%{q.strip()}%"
|
||
stmt = stmt.where(or_(users.c.username.like(like), users.c.display_name.like(like)))
|
||
if department.strip():
|
||
stmt = stmt.where(users.c.department == department.strip())
|
||
rows = (await db.execute(stmt.limit(200))).mappings().all()
|
||
|
||
user_ids = [row["id"] for row in rows] or [""]
|
||
totals = dict(
|
||
(
|
||
await db.execute(
|
||
select(participations.c.user_id, func.count())
|
||
.join(activities, activities.c.id == participations.c.activity_id)
|
||
.where(and_(participations.c.user_id.in_(user_ids),
|
||
activities.c.visibility == "public",
|
||
participations.c.status != "pending", normal_activity_clause()))
|
||
.group_by(participations.c.user_id)
|
||
)
|
||
).all()
|
||
)
|
||
attended = dict(
|
||
(
|
||
await db.execute(
|
||
select(participations.c.user_id, func.count())
|
||
.join(activities, activities.c.id == participations.c.activity_id)
|
||
.where(and_(participations.c.user_id.in_(user_ids),
|
||
activities.c.visibility == "public",
|
||
participations.c.status == "attended", normal_activity_clause()))
|
||
.group_by(participations.c.user_id)
|
||
)
|
||
).all()
|
||
)
|
||
organized = dict(
|
||
(
|
||
await db.execute(
|
||
select(activities.c.organizer_id, func.count())
|
||
.where(and_(activities.c.organizer_id.in_(user_ids),
|
||
activities.c.visibility == "public", normal_activity_clause()))
|
||
.group_by(activities.c.organizer_id)
|
||
)
|
||
).all()
|
||
)
|
||
items = [
|
||
{
|
||
**user_public(row),
|
||
"total": int(totals.get(row["id"], 0)),
|
||
"attended": int(attended.get(row["id"], 0)),
|
||
"organized": int(organized.get(row["id"], 0)),
|
||
}
|
||
for row in rows
|
||
]
|
||
return {"items": items, "count": len(items)}
|
||
|
||
|
||
@app.get("/api/users/{user_id}")
|
||
async def get_user(user_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||
row = (await db.execute(select(users).where(users.c.id == user_id))).mappings().first()
|
||
if row is None:
|
||
raise HTTPException(status_code=404, detail="账号不存在")
|
||
is_self = user_id == viewer["id"]
|
||
stmt = (
|
||
select(activities)
|
||
.where(visible_clause(viewer["id"]))
|
||
.where(
|
||
or_(
|
||
activities.c.organizer_id == user_id,
|
||
activities.c.id.in_(select(participations.c.activity_id).where(participations.c.user_id == user_id)),
|
||
)
|
||
)
|
||
)
|
||
if not is_self:
|
||
stmt = stmt.where(activities.c.visibility == "public")
|
||
rows = (await db.execute(stmt.order_by(activities.c.start_at.desc()).limit(200))).mappings().all()
|
||
return {
|
||
"user": user_public(row, include_contact=is_self),
|
||
"is_self": is_self,
|
||
"stats": await user_stats(db, user_id, public_only=not is_self),
|
||
"items": await serialize_activities(db, rows, viewer["id"]),
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------- 活动
|
||
|
||
@app.get("/api/activities")
|
||
async def list_activities(
|
||
record_type: Optional[Literal['normal', 'center']] = None,
|
||
scope: Literal["all", "mine", "joined", "upcoming"] = "all",
|
||
q: str = "",
|
||
department: str = "",
|
||
user_id: str = "",
|
||
date_from: Optional[int] = None,
|
||
date_to: Optional[int] = None,
|
||
limit: int = 100,
|
||
db: AsyncSession = Depends(get_db),
|
||
viewer: dict = Depends(current_user),
|
||
) -> dict:
|
||
stmt = select(activities).where(visible_clause(viewer["id"]))
|
||
if record_type == 'center': stmt = stmt.where(activities.c.id.in_(select(center_activity_meta.c.activity_id)))
|
||
elif record_type == 'normal': stmt = stmt.where(activities.c.id.not_in(select(center_activity_meta.c.activity_id)))
|
||
if user_id:
|
||
stmt = stmt.where(
|
||
or_(
|
||
activities.c.organizer_id == user_id,
|
||
activities.c.id.in_(select(participations.c.activity_id).where(participations.c.user_id == user_id)),
|
||
)
|
||
)
|
||
if user_id != viewer["id"]:
|
||
stmt = stmt.where(activities.c.visibility == "public")
|
||
if scope == "mine":
|
||
stmt = stmt.where(activities.c.organizer_id == viewer["id"])
|
||
elif scope == "joined":
|
||
stmt = stmt.where(normal_activity_clause(),
|
||
activities.c.id.in_(select(participations.c.activity_id).where(participations.c.user_id == viewer["id"]))
|
||
)
|
||
elif scope == "upcoming":
|
||
stmt = stmt.where(activities.c.start_at >= now_ms(), normal_activity_clause())
|
||
if department:
|
||
# 按部门过滤:该部门成员发起或参加的活动
|
||
dept_user_ids = select(users.c.id).where(users.c.department == department)
|
||
stmt = stmt.where(
|
||
or_(
|
||
activities.c.organizer_id.in_(dept_user_ids),
|
||
activities.c.id.in_(
|
||
select(participations.c.activity_id).where(participations.c.user_id.in_(dept_user_ids))
|
||
),
|
||
)
|
||
)
|
||
if q.strip():
|
||
like = f"%{q.strip()}%"
|
||
stmt = stmt.where(or_(activities.c.title.like(like), activities.c.description.like(like), activities.c.location.like(like)))
|
||
if date_from:
|
||
stmt = stmt.where(activities.c.start_at >= date_from)
|
||
if date_to:
|
||
stmt = stmt.where(activities.c.start_at <= date_to)
|
||
|
||
stmt = stmt.order_by(activities.c.start_at.desc()).limit(min(max(limit, 1), 200))
|
||
rows = (await db.execute(stmt)).mappings().all()
|
||
return {"items": await serialize_activities(db, rows, viewer["id"]), "count": len(rows)}
|
||
|
||
|
||
@app.post("/api/activities")
|
||
async def create_activity(payload: ActivityIn, request: Request, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||
"""记录一场活动:创建即对外生效(公开活动直接出现在活动墙)。
|
||
防重复提交:60 秒内同一账号提交同名的活动直接返回已有那条。"""
|
||
if payload.record_type == 'center':
|
||
if payload.material_id:
|
||
payload.photo_ids = list(dict.fromkeys([*payload.photo_ids, *await center.material_photos(db, payload.material_id, viewer['id'])]))
|
||
center.validate_photo_batch(payload.photo_ids)
|
||
await center.validate_photos(db, payload.photo_ids, viewer['id'], allow_empty=bool(payload.material_id))
|
||
payload.visibility = 'public'
|
||
payload.capacity = None
|
||
elif payload.photo_ids: raise HTTPException(422, '请先选择赋能中心一楼活动记录')
|
||
dup_since = now_ms() - DUPLICATE_WINDOW_MS
|
||
dup = (
|
||
await db.execute(
|
||
select(activities).where(
|
||
and_(
|
||
activities.c.organizer_id == viewer["id"],
|
||
activities.c.title == payload.title.strip(),
|
||
activities.c.created_at >= dup_since,
|
||
activities.c.id.in_(select(center_activity_meta.c.activity_id)) if payload.record_type == 'center' else activities.c.id.not_in(select(center_activity_meta.c.activity_id)),
|
||
)
|
||
)
|
||
)
|
||
).mappings().first()
|
||
if dup is not None:
|
||
items = await serialize_activities(db, [dup], viewer["id"])
|
||
return {"activity": items[0], "duplicate": True}
|
||
|
||
activity_id = new_id()
|
||
stamp = now_ms()
|
||
await db.execute(
|
||
insert(activities).values(
|
||
id=activity_id,
|
||
title=payload.title.strip(),
|
||
start_at=payload.start_at,
|
||
location=payload.location.strip() or ('赋能中心一楼' if payload.record_type == 'center' else ''),
|
||
description=payload.description.strip(),
|
||
visibility=payload.visibility,
|
||
capacity=payload.capacity,
|
||
status="approved",
|
||
organizer_id=viewer["id"],
|
||
created_at=stamp,
|
||
updated_at=stamp,
|
||
)
|
||
)
|
||
activity = await fetch_activity(db, activity_id)
|
||
await center.save_meta(db, activity_id, payload.record_type, payload.photo_ids, viewer['id'], payload.material_id)
|
||
# 发起人自己就是这条记录的主人(不算"报名")
|
||
if payload.record_type != 'center':
|
||
await _add_participant(db, activity, viewer["id"], "organizer", "attended" if payload.start_at <= stamp else "joined")
|
||
await db.commit()
|
||
items = await serialize_activities(db, [activity], viewer["id"])
|
||
|
||
# 通知其他已注册用户(公开活动):后台任务发邮件,不阻塞响应、不影响创建结果
|
||
if NOTIFY_ENABLED and payload.record_type != 'center' and payload.visibility == "public" and not DEV_MODE:
|
||
base_url = _site_base_url(request)
|
||
organizer_name = viewer.get("display_name") or viewer.get("username") or "有成员"
|
||
asyncio.create_task(_notify_new_activity(activity_id, organizer_name, base_url))
|
||
|
||
return {"activity": items[0], "duplicate": False}
|
||
|
||
|
||
@app.get("/api/activities/{activity_id}")
|
||
async def get_activity(activity_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||
row = await fetch_activity(db, activity_id)
|
||
if row["visibility"] != "public" and row["organizer_id"] != viewer["id"] and not await is_center_activity(db, activity_id):
|
||
member = await _require_participant(db, activity_id, viewer["id"])
|
||
if member is None or member["status"] == "pending":
|
||
raise HTTPException(status_code=403, detail="这是一条私密活动,你没有查看权限")
|
||
items = await serialize_activities(db, [row], viewer["id"])
|
||
can_edit = row["organizer_id"] == viewer["id"]
|
||
return {"activity": items[0], "can_edit": can_edit}
|
||
|
||
|
||
@app.patch("/api/activities/{activity_id}")
|
||
async def update_activity(
|
||
activity_id: str, payload: ActivityPatch, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)
|
||
) -> dict:
|
||
await db.execute(text('BEGIN IMMEDIATE'))
|
||
row = await fetch_activity(db, activity_id)
|
||
if row["organizer_id"] != viewer["id"]:
|
||
raise HTTPException(status_code=403, detail="只有发起人可以修改该活动")
|
||
provided = payload.model_dump(exclude_unset=True)
|
||
changes = {k: v for k, v in provided.items() if v is not None or k == 'capacity'}
|
||
old_meta = (await db.execute(select(center_activity_meta).where(center_activity_meta.c.activity_id == activity_id))).mappings().first()
|
||
kind = changes.pop('record_type', 'center' if old_meta else 'normal')
|
||
material_id = changes.pop('material_id', old_meta['material_id'] if old_meta else None)
|
||
photo_ids = changes.pop('photo_ids', json.loads(old_meta['photo_ids']) if old_meta else [])
|
||
if kind == 'center':
|
||
packages = await center.activity_materials(db, [activity_id]) if old_meta else {}
|
||
existing_photos = list(dict.fromkeys([*(json.loads(old_meta['photo_ids']) if old_meta else []), *(photo for package in packages.get(activity_id, []) for photo in package['photo_ids'])]))
|
||
if material_id:
|
||
photo_ids = list(dict.fromkeys([*photo_ids, *await center.material_photos(db, material_id, viewer['id'])]))
|
||
center.validate_photo_batch(photo_ids, existing_photos)
|
||
photo_ids = list(dict.fromkeys([*existing_photos, *photo_ids]))
|
||
await center.validate_photos(db, photo_ids, viewer['id'], existing_photos, allow_empty=bool(material_id or packages.get(activity_id)))
|
||
elif photo_ids and payload.record_type != 'normal': raise HTTPException(422, '请先选择赋能中心一楼活动记录')
|
||
if old_meta and old_meta['material_id']:
|
||
await center.link_material(db, activity_id, old_meta['material_id'])
|
||
await db.execute(delete(center_activity_meta).where(center_activity_meta.c.activity_id == activity_id))
|
||
if kind == 'center':
|
||
await db.execute(insert(center_activity_meta).values(activity_id=activity_id,photo_ids=json.dumps(photo_ids),material_id=material_id))
|
||
if material_id: await center.link_material(db, activity_id, material_id)
|
||
changes.update(visibility='public', capacity=None)
|
||
await db.execute(update(join_links).where(join_links.c.activity_id == activity_id, join_links.c.used == 0).values(used=2))
|
||
if not changes.get('location', row['location']).strip(): changes['location'] = '赋能中心一楼'
|
||
elif old_meta and await _require_participant(db, activity_id, viewer['id']) is None:
|
||
await _add_participant(db, row, viewer['id'], 'organizer', 'attended' if changes.get('start_at', row['start_at']) <= now_ms() else 'joined')
|
||
if "title" in changes:
|
||
changes["title"] = changes["title"].strip()
|
||
if not changes["title"]:
|
||
raise HTTPException(status_code=400, detail="活动名称不能为空")
|
||
if changes:
|
||
changes["updated_at"] = now_ms()
|
||
await db.execute(update(activities).where(activities.c.id == activity_id).values(**changes))
|
||
await db.commit()
|
||
fresh = await fetch_activity(db, activity_id)
|
||
items = await serialize_activities(db, [fresh], viewer["id"])
|
||
return {"activity": items[0]}
|
||
|
||
|
||
@app.post('/api/activities/{activity_id}/materials')
|
||
async def add_activity_material(activity_id: str, payload: center.MaterialIn, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||
await db.execute(text('BEGIN IMMEDIATE'))
|
||
row = await fetch_activity(db, activity_id)
|
||
if not await is_center_activity(db, activity_id):
|
||
raise HTTPException(409, '仅赋能中心一楼活动支持成员补充材料')
|
||
if not payload.photo_ids and not payload.material_id:
|
||
raise HTTPException(422, '请至少上传照片或ZIP附件')
|
||
package_photos = await center.material_photos(db, payload.material_id, viewer['id']) if payload.material_id else []
|
||
center.validate_photo_batch([*payload.photo_ids, *package_photos])
|
||
await center.validate_photos(db, payload.photo_ids, viewer['id'], allow_empty=bool(payload.material_id))
|
||
if payload.material_id:
|
||
await center.link_material(db, activity_id, payload.material_id)
|
||
if payload.photo_ids:
|
||
meta = (await db.execute(select(center_activity_meta).where(center_activity_meta.c.activity_id == activity_id))).mappings().one()
|
||
photos = list(dict.fromkeys([*json.loads(meta['photo_ids']), *payload.photo_ids]))
|
||
await db.execute(update(center_activity_meta).where(center_activity_meta.c.activity_id == activity_id).values(photo_ids=json.dumps(photos)))
|
||
await db.commit()
|
||
return {'activity': (await serialize_activities(db, [row], viewer['id']))[0]}
|
||
|
||
|
||
@app.delete("/api/activities/{activity_id}")
|
||
async def delete_activity(activity_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||
row = await fetch_activity(db, activity_id)
|
||
if row["organizer_id"] != viewer["id"]:
|
||
raise HTTPException(status_code=403, detail="只有发起人可以删除该活动")
|
||
await db.execute(delete(participations).where(participations.c.activity_id == activity_id))
|
||
await db.execute(delete(activities).where(activities.c.id == activity_id))
|
||
await db.commit()
|
||
return {"ok": True, "id": activity_id}
|
||
|
||
|
||
@app.post("/api/activities/{activity_id}/claim")
|
||
async def claim_activity(activity_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||
""""我也参加过":立即加入这条记录,不再需要管理员确认。"""
|
||
row = await fetch_activity(db, activity_id)
|
||
await require_participatory_activity(db, activity_id)
|
||
if row["visibility"] != "public":
|
||
raise HTTPException(status_code=403, detail="私密活动需要由发起人添加你参加")
|
||
if await _require_participant(db, activity_id, viewer["id"]) is not None:
|
||
raise HTTPException(status_code=409, detail="你已在这条记录里")
|
||
await _add_participant(db, row, viewer["id"], "member", "joined")
|
||
await db.commit()
|
||
fresh = await fetch_activity(db, activity_id)
|
||
items = await serialize_activities(db, [fresh], viewer["id"])
|
||
return {"activity": items[0], "joined": True}
|
||
|
||
|
||
@app.post("/api/activities/{activity_id}/leave")
|
||
async def leave_activity(activity_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||
row = await fetch_activity(db, activity_id)
|
||
await require_participatory_activity(db, activity_id)
|
||
if row["organizer_id"] == viewer["id"]:
|
||
raise HTTPException(status_code=400, detail="发起人不能退出自己的活动,可以选择删除该活动")
|
||
mine = await _require_participant(db, activity_id, viewer["id"])
|
||
if mine is None:
|
||
raise HTTPException(status_code=404, detail="你还没有参加这条活动")
|
||
await db.execute(delete(participations).where(participations.c.id == mine["id"]))
|
||
await db.commit()
|
||
if row["visibility"] == "private":
|
||
return {"ok": True}
|
||
fresh = await fetch_activity(db, activity_id)
|
||
items = await serialize_activities(db, [fresh], viewer["id"])
|
||
return {"activity": items[0]}
|
||
|
||
|
||
@app.delete("/api/activities/{activity_id}/participants/{user_id}")
|
||
async def remove_participant(
|
||
activity_id: str, user_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)
|
||
) -> dict:
|
||
row = await fetch_activity(db, activity_id)
|
||
await require_participatory_activity(db, activity_id)
|
||
if user_id == row["organizer_id"]:
|
||
raise HTTPException(status_code=400, detail="发起人不能被移除")
|
||
if row["organizer_id"] != viewer["id"] and user_id != viewer["id"]:
|
||
raise HTTPException(status_code=403, detail="只能移除自己,或由发起人移除成员")
|
||
target = await _require_participant(db, activity_id, user_id)
|
||
if target is None:
|
||
raise HTTPException(status_code=404, detail="该账号不在这条记录里")
|
||
await db.execute(delete(participations).where(participations.c.id == target["id"]))
|
||
await db.commit()
|
||
if row["visibility"] == "private" and row["organizer_id"] != viewer["id"]:
|
||
return {"ok": True}
|
||
fresh = await fetch_activity(db, activity_id)
|
||
items = await serialize_activities(db, [fresh], viewer["id"])
|
||
return {"activity": items[0]}
|
||
|
||
|
||
@app.patch("/api/activities/{activity_id}/participants/{user_id}")
|
||
async def update_participation(
|
||
activity_id: str, user_id: str, payload: ParticipationPatch,
|
||
db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user),
|
||
) -> dict:
|
||
row = await fetch_activity(db, activity_id)
|
||
await require_participatory_activity(db, activity_id)
|
||
is_organizer = row["organizer_id"] == viewer["id"]
|
||
if not is_organizer and user_id != viewer["id"]:
|
||
raise HTTPException(status_code=403, detail="只能修改自己的参加状态")
|
||
target = await _require_participant(db, activity_id, user_id)
|
||
if target is None:
|
||
raise HTTPException(status_code=404, detail="该账号不在这条记录里")
|
||
changes: dict[str, Any] = {}
|
||
if payload.status is not None:
|
||
changes["status"] = payload.status
|
||
if payload.note is not None:
|
||
changes["note"] = payload.note.strip()
|
||
if not changes:
|
||
raise HTTPException(status_code=400, detail="没有需要修改的内容")
|
||
changes["updated_at"] = now_ms()
|
||
await db.execute(update(participations).where(participations.c.id == target["id"]).values(**changes))
|
||
await db.commit()
|
||
fresh = await fetch_activity(db, activity_id)
|
||
items = await serialize_activities(db, [fresh], viewer["id"])
|
||
return {"activity": items[0]}
|
||
|
||
|
||
# ---------------------------------------------------------------- 邮件一键参加
|
||
|
||
_join_page = join_page
|
||
|
||
|
||
@app.get("/join/{token}", include_in_schema=False)
|
||
@app.post("/join/{token}", include_in_schema=False)
|
||
async def join_by_email_link(token: str, request: Request, db: AsyncSession = Depends(get_db)) -> HTMLResponse:
|
||
"""GET 只展示确认页,POST 才消费令牌,避免邮件扫描/预加载误登记。"""
|
||
link = (
|
||
await db.execute(select(join_links).where(join_links.c.token == token_digest(token)))
|
||
).mappings().first()
|
||
if link is None or link["used"] != 0:
|
||
return HTMLResponse(_join_page("该链接无效或已经使用过(每个人只需记录一次)。", "err"), status_code=200)
|
||
if link["expires_at"] <= now_ms():
|
||
return HTMLResponse(
|
||
_join_page("链接已过期。可以打开 WorkLog 在活动墙里手动记录。", "err"), status_code=200
|
||
)
|
||
|
||
row = (await db.execute(select(activities).where(activities.c.id == link["activity_id"]))).mappings().first()
|
||
user = (await db.execute(select(users).where(users.c.id == link["user_id"]))).mappings().first()
|
||
if row is None or user is None:
|
||
return HTMLResponse(_join_page("这条活动记录已被删除。", "err"), status_code=200)
|
||
if await is_center_activity(db, row['id']):
|
||
return HTMLResponse(_join_page('赋能中心一楼活动仅作记录,无需参加。', 'ok', row['title']))
|
||
if row["visibility"] != "public":
|
||
return HTMLResponse(_join_page("活动已改为私密,该邀请已失效。", "err"))
|
||
if request.method == "GET":
|
||
if await _require_participant(db, row["id"], user["id"]) is not None:
|
||
return HTMLResponse(_join_page("你已经在那条记录里了,无需重复添加。", "ok", row["title"]))
|
||
nonce = await asyncio.to_thread(duty_receipts.issue_activity_form, _duty_state(), token)
|
||
return HTMLResponse(_join_page(
|
||
"确认将你记为该活动的参加人。", "confirm", row["title"],
|
||
f'<form method="post"><input type="hidden" name="confirmation_token" value="{escape(nonce, quote=True)}"><button class="btn" type="submit">确认我也参加过</button></form>',
|
||
))
|
||
from urllib.parse import parse_qs
|
||
body = await request.body()
|
||
nonce = parse_qs(body.decode('utf-8', errors='replace')).get('confirmation_token', [None])[0] if len(body) <= 4096 else None
|
||
if not await asyncio.to_thread(duty_receipts.validate_activity_form, _duty_state(), token, nonce):
|
||
return HTMLResponse(_join_page("确认页面已更新,请重新打开邮件链接,再点击页面中的确认按钮。", "err"), status_code=403)
|
||
claimed = await db.execute(update(join_links).where(
|
||
join_links.c.id == link["id"], join_links.c.used == 0, join_links.c.expires_at > now_ms(),
|
||
).values(used=1))
|
||
if claimed.rowcount != 1:
|
||
return HTMLResponse(_join_page("该链接无效或已经使用过。", "err"))
|
||
if await _require_participant(db, row["id"], user["id"]) is not None:
|
||
# 已经是参加者(比如先在网页上记了):令牌作废即可,提示友好结果
|
||
await db.execute(update(join_links).where(join_links.c.id == link["id"]).values(used=1))
|
||
await db.commit()
|
||
return HTMLResponse(_join_page("你已经在那条记录里了,无需重复添加。", "ok", row["title"]), status_code=200)
|
||
try:
|
||
await _add_participant(db, row, user["id"], "member", "joined")
|
||
except HTTPException as exc: # 名额已满等业务错误
|
||
await db.rollback()
|
||
return HTMLResponse(_join_page(exc.detail, "err", row["title"]), status_code=200)
|
||
await db.execute(update(join_links).where(join_links.c.id == link["id"]).values(used=1))
|
||
await db.commit()
|
||
return HTMLResponse(
|
||
_join_page("已把你记为该活动的参加人,可在 WorkLog 中查看或修改状态。", "ok", row["title"]),
|
||
status_code=200,
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------- 前端托管
|
||
|
||
if FRONTEND_DIR.exists():
|
||
app.mount("/js", StaticFiles(directory=str(FRONTEND_DIR / "js")), name="js")
|
||
app.mount("/assets", StaticFiles(directory=str(FRONTEND_DIR / "assets")), name="assets")
|
||
|
||
@app.get("/", include_in_schema=False)
|
||
async def index() -> FileResponse:
|
||
return FileResponse(FRONTEND_DIR / "index.html")
|
||
|
||
@app.get("/{path:path}", include_in_schema=False)
|
||
async def spa(path: str):
|
||
candidate = (FRONTEND_DIR / path).resolve()
|
||
if candidate.is_relative_to(FRONTEND_DIR.resolve()) and candidate.is_file():
|
||
return FileResponse(candidate)
|
||
return FileResponse(FRONTEND_DIR / "index.html")
|
||
else: # pragma: no cover - 只在缺少前端目录时触发
|
||
@app.get("/", include_in_schema=False)
|
||
async def index_missing() -> JSONResponse:
|
||
return JSONResponse({"detail": "前端目录缺失,请确认 dist/ 存在"}, status_code=503)
|
||
|
||
|
||
def main() -> None:
|
||
# 邮件 URL 包含一次性凭据,不写入默认访问日志。
|
||
uvicorn.run(app, host=HOST, port=PORT, log_level="info", access_log=False, proxy_headers=False)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|