"""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 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
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 hash_password, new_token, token_digest, verify_password
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
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 now_ms() -> int:
return int(time.time() * 1000)
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 "")
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 visible_clause(viewer_id: str):
"""一条活动对当前账号可见的条件:公开活动、自己发起的、自己参加过的。"""
return or_(
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:
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 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)
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:
members = people.get(row["id"], [])
mine = next((m for m in members if m["user_id"] == viewer_id), None)
items.append(
{
**activity_public(row),
"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,
}
)
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"))
)
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
)
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,
}
# ---------------------------------------------------------------- 请求模型
EMAIL_PATTERN = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
PHONE_PATTERN = r"^1[3-9][0-9]{9}$"
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", "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 RegisterIn(EmailCodeIn):
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(EmailCodeIn):
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 ActivityIn(BaseModel):
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):
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:
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)
await _migrate_legacy(conn)
yield
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 ''"))
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 "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)))
app = FastAPI(title="WorkLog 活动记录", version="2.0.0", lifespan=lifespan)
@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
if 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:; connect-src 'self'; object-src 'none'; base-uri 'none'; "
"frame-ancestors 'none'; form-action 'self'"
)
if request.url.path.startswith(("/api/", "/join/")):
response.headers["Cache-Control"] = "no-store"
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 网络抖动时快速失败,避免请求永久挂起。"""
import aiosmtplib
from email.message import EmailMessage
message = EmailMessage()
message["From"] = SMTP_FROM
message["To"] = to
message["Subject"] = subject
message.set_content(body)
if html:
message.add_alternative(html, subtype="html")
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)
except aiosmtplib.errors.SMTPRecipientsRefused as exc:
# 收件人被拒(邮箱不存在等),把服务端的拒绝原因透出
raise HTTPException(status_code=400, detail="邮件服务器拒绝该收件地址,请检查邮箱") from exc
except aiosmtplib.errors.SMTPAuthenticationError as exc:
# 授权码被拒(535):多数是授权码失效或账号 SMTP 服务被风控
print(f"[smtp] 认证失败({SMTP_USER}):{exc}")
raise HTTPException(
status_code=502,
detail="邮件服务认证失败(授权码可能已失效),请联系管理员检查邮箱设置",
) from exc
except (asyncio.TimeoutError, OSError, aiosmtplib.errors.SMTPException) as exc:
# QQ 等服务商在认证被拒时不回 535 而是直接断连(表现为 SMTPServerDisconnected),
# 连不上和被拒绝对外要区分开,便于管理员排查
text_msg = str(exc).lower()
if "unexpected eof" in text_msg or "connection lost" in text_msg:
print(f"[smtp] 连接被服务器提前断开(可能为认证被拒/风控):{exc}")
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'
| 时间 | '
f'{_fmt_dt(activity["start_at"])} |
'
f'| 地点 | '
f'{activity["location"] or "(未填写)"} |
'
)
desc = (activity["description"] or "").strip()
if desc:
detail += (
f'| 说明 | '
f'{desc} |
'
)
return f"""\
WorkLog 活动记录
{organizer_name} 发起了一场新活动
如果你也参加了这场活动,点下面的按钮一条记录即可:
我也参加过
打开链接后确认参加,链接 {JOIN_LINK_DAYS} 天内有效。
也可以打开 WorkLog 查看全部活动记录。
"""
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:
"""给除发起人外的所有已注册用户发新活动通知。发信在后台任务里逐个进行,
单个失败只打日志,不影响活动创建,也不阻塞 API 响应。"""
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 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}/"
ok = failed = 0
for user_id, email, _name in recipients:
token = new_token()
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()
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, f"【WorkLog】{organizer_name} 发起了新活动:{row['title']}", plain, html)
ok += 1
except Exception as exc: # 通知失败不影响活动本身
failed += 1
print(f"[notify] 发送失败 to={email}: {exc}")
# 顺手清掉过期的旧链接
await db.execute(delete(join_links).where(join_links.c.expires_at < now_ms()))
await db.commit()
print(f"[notify] 活动「{row['title']}」通知完成:成功 {ok},失败 {failed}")
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:
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="该邮箱已被注册")
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 == payload.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=payload.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 验证码",
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="验证码已失效,请重新获取")
# ---------------------------------------------------------------- 账号
@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=hash_password(new_token()),
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},
}
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=404, detail="该邮箱尚未注册")
await _consume_email_code(db, payload.email, payload.email_code, "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)}
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/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")
)
).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")
)
).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()))
)
).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"))
.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"))
.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"))
.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(
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 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(
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())
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 秒内同一账号提交同名的活动直接返回已有那条。"""
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,
)
)
)
).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(),
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 _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.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"]:
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:
row = await fetch_activity(db, activity_id)
if row["organizer_id"] != viewer["id"]:
raise HTTPException(status_code=403, detail="只有发起人可以修改该活动")
changes = {k: v for k, v in payload.model_dump(exclude_unset=True).items() if v is not None}
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.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)
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)
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)
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)
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 = """\
一键参加 · WorkLog
"""
def _join_page(message: str, state: str, activity_title: str = "", extra: str = "") -> str:
icon = "✓" if state == "ok" else ("?" if state == "confirm" else "✕")
btn = (
f'打开 WorkLog'
if state == "ok"
else ""
)
title_html = f'{escape(activity_title)}
' if activity_title else ""
heading = {"ok": "记录成功", "confirm": "确认参加", "err": "无法完成"}[state]
return JOIN_PAGE.format().replace(
'',
f'{icon}
'
f'
{heading}
{title_html}'
f'
{escape(str(message))}
{btn}{extra}
',
)
@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 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"]))
return HTMLResponse(_join_page(
"确认将你记为该活动的参加人。", "confirm", row["title"],
'',
))
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()