From bc62f1123002f758e81f7ee6b86ed604e601087b Mon Sep 17 00:00:00 2001 From: azzz <811446351@qq.com> Date: Thu, 29 Oct 2026 16:27:34 +0800 Subject: [PATCH] WorkLog initial import --- .env.example | 17 + .gitignore | 4 + Dockerfile | 23 + README.md | 87 +++ UPGRADE.md | 22 + clear_db.py | 181 +++++ config.toml | 35 + dist/assets/styles.css | 410 +++++++++++ dist/index.html | 181 +++++ dist/js/app.js | 738 ++++++++++++++++++++ package.bat | 66 ++ package.sh | 68 ++ repair_db.py | 248 +++++++ requirements.txt | 8 + server/__init__.py | 1 + server/main.py | 1495 ++++++++++++++++++++++++++++++++++++++++ server/models.py | 131 ++++ server/security.py | 40 ++ start.sh | 19 + 19 files changed, 3774 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 UPGRADE.md create mode 100644 clear_db.py create mode 100644 config.toml create mode 100644 dist/assets/styles.css create mode 100644 dist/index.html create mode 100644 dist/js/app.js create mode 100644 package.bat create mode 100644 package.sh create mode 100644 repair_db.py create mode 100644 requirements.txt create mode 100644 server/__init__.py create mode 100644 server/main.py create mode 100644 server/models.py create mode 100644 server/security.py create mode 100644 start.sh diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..13b44aa --- /dev/null +++ b/.env.example @@ -0,0 +1,17 @@ +# 复制为 .env 后按需修改(.env 不入库) +WORKLOG_HOST=127.0.0.1 +WORKLOG_PORT=37777 +WORKLOG_DB=./data/worklog.db +WORKLOG_SESSION_DAYS=30 +WORKLOG_DEV_MODE=false +# 外网部署必填:邮件链接只使用此配置,不读取客户端 Host/代理头 +# WORKLOG_BASE_URL=https://worklog.example.com + +# 邮箱验证码 SMTP(缺少配置时拒绝发码;本机调试需显式启用 DEV_MODE 并绑定 127.0.0.1) +# WORKLOG_SMTP_HOST=smtp.qq.com +# WORKLOG_SMTP_PORT=465 +# WORKLOG_SMTP_USER=notify@example.com +# WORKLOG_SMTP_PASSWORD=授权码 +# WORKLOG_SMTP_FROM=WorkLog +# WORKLOG_SMTP_TLS=ssl +# WORKLOG_EMAIL_CODE_TTL_MIN=10 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b6bde21 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.env +data/ +__pycache__/ +*.pyc diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a6f953d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM python:3.11-slim + +WORKDIR /app + +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt + +COPY server /app/server +COPY dist /app/dist +COPY config.toml /app/config.toml + +RUN mkdir -p /app/data + +ENV WORKLOG_HOST=0.0.0.0 \ + WORKLOG_PORT=37777 \ + WORKLOG_DB=/app/data/worklog.db \ + WORKLOG_FRONTEND=/app/dist + +EXPOSE 37777 + +VOLUME /app/data + +CMD ["python", "-m", "server.main"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..0be72e3 --- /dev/null +++ b/README.md @@ -0,0 +1,87 @@ +# WorkLog · 活动记录网站 + +以**账号**为单位记录每人参加的活动:注册账号 → 发布/报名活动 → 每条参加记录带状态与备注 → 在「成员」里点开任何人,查看 TA 公开的活动记录与统计。 + +后端 FastAPI + SQLAlchemy(异步)+ SQLite,前端原生 HTML/CSS/JS(无构建步骤),后端同端口托管前端。 + +## 功能 + +- **账号体系**:邮箱 + 六位数字验证码注册/登录(注册需填写姓名、所属部门、邮箱、手机号),Bearer 会话默认 30 天有效,可改姓名、部门、签名和手机号 +- **活动记录**:标题 / 分类(8 类)/ 时间 / 地点 / 描述 / 名额 / 公开或私密;发起人自动写入一条参加记录 +- **参加方式**:在活动墙自行报名公开活动;或由**发起人按账号名代登记**(适合"帮大家统一记录"的场景) +- **状态与备注**:报名中 / 已参加 / 缺席,本人或发起人可改;每人可写自己的备注 +- **我的记录**:按状态筛选、搜索、出席率与分类统计 +- **看到别人**:成员列表带每人统计;他人主页只展示公开活动的记录(私密活动仅发起人与参加者可见) + +## 快速开始 + +依赖已在系统 Python(3.13)中可用。若在干净环境: + +```bash +python -m pip install -r requirements.txt +``` + +启动(在 WorkLog 目录下): + +```bash +python -m server.main +``` + +打开 http://127.0.0.1:37777 ,注册账号即可使用。 + +配置见 `config.toml`,可用环境变量覆盖:`WORKLOG_HOST` / `WORKLOG_PORT` / `WORKLOG_DB` / `WORKLOG_SESSION_DAYS`(复制 `.env.example` 为 `.env` 也可以)。数据落在 `data/worklog.db`,`.gitignore` 已排除。 + +注册表单与后端统一校验五项必填内容:姓名不超过 32 字符、所属部门从固定列表选择、有效邮箱、不重复的 11 位大陆手机号、6 位数字邮箱验证码。用户名和旧版兼容字段由后端生成,用户无需填写;历史账号缺少部门或手机号仍可登录。升级已有服务器请看 `UPGRADE.md`。 + +## 安全与部署 + +活动发布和「我也参加过」直接生效,现版本没有管理员审核流程。 + +- **验证码**:数据库保存带盐的 PBKDF2 摘要;每条最多尝试 5 次,一次使用后失效,同用途重新发码会废止旧码。每邮箱 10 分钟最多发码 5 次,每 IP 最多发码 30 次、提交注册/登录校验 60 次;限流计数保存在 SQLite,服务重启后仍有效。 +- **开发模式**:默认关闭。缺少 SMTP 配置时返回 503,不回显验证码;仅本机调试可设置 `WORKLOG_DEV_MODE=true`,同时将 `WORKLOG_HOST=127.0.0.1`。发码接口还会检查连接来源为回环地址。 +- **会话和邮件链接**:数据库只保存随机令牌的 SHA-256 摘要。邮件链接 GET 只展示确认页,POST 确认后才登记,令牌只能消费一次;活动改成私密后旧邀请被拒绝。默认关闭 Uvicorn 访问日志,避免邮件 URL 凭据入日志。 +- **隐私与页面防护**:邮箱和手机号只在本人资料中返回,成员列表、他人主页及概览不包含私密活动统计;页面输出转义用户内容,启用 CSP、防嵌入、禁止 MIME 嗅探和无 Referer 策略,API/邮件确认页禁止缓存。浏览器修改请求仅接受同源提交。 +- **数据库升级**:启动自动补充尝试次数和限流表,将旧会话/邮件令牌转成摘要;旧明文验证码会作废,需重新获取。计数更新不依赖 SQLite 3.35 才加入的 `RETURNING` 语法,兼容较旧的服务器 SQLite。邮箱(忽略大小写)和非空手机号有唯一索引;若历史数据重复,需先处理冲突再启动。升级前保留数据库备份。 + +将 SMTP 主机、端口、账号及授权码写入本机 `.env`(参考 `.env.example`)。共享的 `config.toml` 不保存凭据,打包脚本排除 `.env`、数据库文件及 WAL/SHM 文件。已经分发过的明文授权码需要在邮箱服务端更换,历史压缩包和数据库备份应妥善保管。 + +外网部署时设置 `WORKLOG_BASE_URL=https://你的域名`,并通过 HTTPS 访问。邮件链接只使用此配置,留空时回退到本机地址,不信任请求 Host 或转发头。默认不信任代理 IP 头;部署在反向代理后时,应用会按代理连接 IP 汇总限流,可在代理层另外设置客户端限流,同时避免记录 `/join/` 令牌 URL。前端仍将 Bearer 令牌保存在浏览器 localStorage,使用完应退出登录。 + +## 目录结构 + +``` +WorkLog/ +├── server/ +│ ├── main.py # FastAPI 应用:账号、活动、参加记录、统计 API + 前端托管 +│ ├── models.py # 用户、会话、验证码、活动、参加记录、邮件链接、限流计数 +│ └── security.py # PBKDF2 口令散列、会话令牌 +├── dist/ +│ ├── index.html +│ ├── assets/styles.css +│ └── js/app.js # 前端 SPA 逻辑 +├── tests/ # API、邮件通知及安全回归测试(unittest + httpx ASGI) +├── config.toml # 端口 / 数据库路径 / 会话天数 +└── requirements.txt +``` + +## API 一览 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| POST | `/api/auth/register` / `login` / `logout` | 注册 / 登录 / 退出 | +| GET/PATCH | `/api/auth/me` | 我的资料与统计 / 改资料、密码 | +| GET | `/api/activities` | `scope=all/mine/joined/upcoming`,支持 `q`、`category`、`user_id`、`date_from/to` | +| POST | `/api/activities` | 创建(可代登记 participants) | +| GET/PATCH/DELETE | `/api/activities/{id}` | 详情 / 编辑(仅发起人)/ 删除(仅发起人) | +| POST | `/api/activities/{id}/join` · `leave` | 报名 / 退出 | +| POST | `/api/activities/{id}/participants` | 发起人按账号名添加成员 | +| PATCH/DELETE | `/api/activities/{id}/participants/{user_id}` | 改状态备注 / 移出 | +| GET | `/api/users` · `/api/users/{id}` | 成员列表 / 他人主页(公开记录+统计) | +| GET | `/api/stats/overview` | 全站概览 | +| GET | `/api/health` · `/api/meta` | 健康检查 / 分类字典 | + +运行测试: + +```bash +python -m unittest discover -s tests -v +``` diff --git a/UPGRADE.md b/UPGRADE.md new file mode 100644 index 0000000..e4cec2b --- /dev/null +++ b/UPGRADE.md @@ -0,0 +1,22 @@ +# 本次更新与服务器升级 + +## 注册表单 + +姓名、所属部门、邮箱、手机号和邮箱验证码全部必填,前后端规则保持一致。邮箱用于登录及接收验证码;手机号为 11 位大陆手机号,邮箱和手机号不能重复。验证码限定 6 位数字,支持系统自动填充。校验失败显示具体中文原因,避免出现 `[object Object]`。姓名和部门对成员展示,邮箱和手机号只在本人资料返回。 + +现有数据库的 `users` 表已经包含全部注册字段,不需要手动加字段。旧版 `username`、`password_hash`、`role` 非空列继续由后端写入,兼容服务器当前表结构。新注册必须选择部门,旧账号中的空部门或空手机号不影响登录。 + +## 数据库核对结果(2026-10-14) + +按用户提供的 `worklog.db`、`worklog.db-wal`、`worklog.db-shm` 的配套副本检查,当前数据库完整性正常:7 个账号、5 场活动、17 条参加记录;无重复邮箱/手机号,无外键引用错误。 + +另附的 `worklog.db.bak-20261014-105608` 是更早的快照,有 19 条外键引用异常,且参加记录比当前库少。本次更新以当前数据库及配套 WAL 为准,不需要恢复该旧备份。此次核对不改动提供的四个原始文件。 + +## 更新已有服务器 + +1. 停止 WorkLog 服务,并备份服务器当前数据库。若有 WAL,保留主库和配套 WAL/SHM,或使用 SQLite backup 接口生成完整备份,不要只在运行时单独复制主库。 +2. 将 ZIP 解压到新目录,再覆盖服务器项目中的 `server/`、`dist/`、`tests/`、`requirements.txt`、`start.sh` 及文档。保留服务器原有的 `data/`、`.env`、`config.toml`,避免覆盖数据库、端口及 SMTP 配置。 +3. 在项目目录执行 `python -m pip install -r requirements.txt`,然后按原方式重启(例如 `python -m server.main` 或 `bash start.sh`)。要求 Python 3.11 或以上。 +4. 启动会自动完成兼容升级:补充验证码尝试次数和限流表、创建邮箱/手机号唯一索引,并将旧会话和邮件令牌转为摘要;旧明文验证码会失效,需要重新获取。既有账号、活动及参加记录保留。 + +生产环境关闭 `WORKLOG_DEV_MODE` 并保留有效的 SMTP 配置;邮件链接的公网地址通过 `WORKLOG_BASE_URL` 设置。包内仅提供 `.env.example` 配置示例,不包含本机凭据和数据库。 diff --git a/clear_db.py b/clear_db.py new file mode 100644 index 0000000..6503f17 --- /dev/null +++ b/clear_db.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""WorkLog 数据库清除脚本(Windows / Linux 通用)。 + +用法: + python clear_db.py 交互式选择清除范围 + python clear_db.py --junk -y 只清过期会话、已用/过期验证码(安全,不动业务数据) + python clear_db.py --activities -y 清空活动和参加记录(保留用户) + python clear_db.py --all -y 清空全部业务数据(恢复初始状态) + +可选参数: + --db PATH 指定数据库文件(默认按 WORKLOG_DB / config.toml 的 database.path 解析) + --no-backup 清除前不做备份(默认备份为 <库名>.bak-时间戳,放在同目录) + -y, --yes 跳过确认 +""" + +from __future__ import annotations + +import argparse +import os +import sqlite3 +import sys +import time +from datetime import datetime +from pathlib import Path + +PROJECT_DIR = Path(__file__).resolve().parent + +TABLES = ("users", "sessions", "email_verifications", "activities", "participations") + +SCOPE_NAMES = { + "junk": "只清理过期数据(过期会话、已用/过期验证码)", + "activities": "清空活动数据(活动 + 参加记录,用户保留)", + "all": "清空全部业务数据(用户、活动、会话、验证码,恢复初始状态)", +} + + +def resolve_db_path(explicit: str | None) -> Path: + """与 server/main.py 相同的解析顺序:--db > WORKLOG_DB > config.toml > ./data/worklog.db""" + raw = explicit or os.getenv("WORKLOG_DB") + if not raw: + raw = "./data/worklog.db" + config_path = Path(os.getenv("WORKLOG_CONFIG", str(PROJECT_DIR / "config.toml"))) + try: + import tomllib + + with open(config_path, "rb") as fh: + cfg = tomllib.load(fh) + raw = cfg.get("database", {}).get("path", raw) + except Exception: + pass + path = Path(raw) + return path if path.is_absolute() else PROJECT_DIR / path + + +def table_counts(conn: sqlite3.Connection) -> dict[str, int | None]: + counts: dict[str, int | None] = {} + for table in TABLES: + try: + counts[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] + except sqlite3.OperationalError: + counts[table] = None + return counts + + +def build_plan(scope: str, now_ms: int): + """返回 [(说明, DELETE 语句, 参数)]。all 必须先删子表再删父表,避免外键阻塞。""" + if scope == "junk": + return [ + ("过期登录会话", "DELETE FROM sessions WHERE expires_at < ?", (now_ms,)), + ( + "已用/过期邮箱验证码", + "DELETE FROM email_verifications WHERE used = 1 OR expires_at < ?", + (now_ms,), + ), + ] + if scope == "activities": + return [ + ("参加记录", "DELETE FROM participations", ()), + ("活动", "DELETE FROM activities", ()), + ] + return [ + ("参加记录", "DELETE FROM participations", ()), + ("活动", "DELETE FROM activities", ()), + ("登录会话", "DELETE FROM sessions", ()), + ("邮箱验证码", "DELETE FROM email_verifications", ()), + ("用户", "DELETE FROM users", ()), + ] + + +def main() -> int: + parser = argparse.ArgumentParser(description="WorkLog 数据库清除脚本") + group = parser.add_mutually_exclusive_group() + group.add_argument("--junk", action="store_true", help="只清过期会话和已用/过期验证码") + group.add_argument("--activities", action="store_true", help="清空活动与参加记录,保留用户") + group.add_argument("--all", action="store_true", help="清空全部业务数据") + parser.add_argument("--db", help="数据库文件路径(默认 WORKLOG_DB / config.toml)") + parser.add_argument("--no-backup", action="store_true", help="清除前不备份") + parser.add_argument("-y", "--yes", action="store_true", help="跳过确认") + args = parser.parse_args() + + scope = ( + "junk" + if args.junk + else "activities" + if args.activities + else "all" + if args.all + else None + ) + + db_path = resolve_db_path(args.db) + if not db_path.exists(): + print(f"[!] 数据库不存在:{db_path}") + return 1 + + conn = sqlite3.connect(str(db_path)) + counts = table_counts(conn) + print(f"数据库:{db_path} ({db_path.stat().st_size / 1024:.0f} KB)") + print("当前数据:") + for table in TABLES: + value = counts[table] + print(f" {table:<20}{value if value is not None else '(表不存在)'}") + + if scope is None: + print("\n请选择清除范围:") + print(" 1) 只清理过期数据(过期会话、已用/过期验证码)—— 安全") + print(" 2) 清空活动数据(活动 + 参加记录,保留用户)") + print(" 3) 清空全部数据(用户、活动、会话、验证码,恢复初始状态)") + print(" 0) 取消") + choice = input("请输入编号: ").strip() + scope = {"1": "junk", "2": "activities", "3": "all"}.get(choice) + if scope is None: + print("已取消。") + return 0 + + plan = build_plan(scope, int(time.time() * 1000)) + print(f"\n即将执行:{SCOPE_NAMES[scope]}") + for name, _, _ in plan: + print(f" - 删除{name}") + if scope != "junk": + print("注意:清除后已登录用户会被强制下线,该操作不可撤销(有备份可恢复)。") + if not args.yes: + if input("输入 yes 继续: ").strip().lower() != "yes": + print("已取消。") + return 0 + + if not args.no_backup: + stamp = datetime.now().strftime("%Y%m%d-%H%M%S") + backup_path = db_path.with_name(f"{db_path.name}.bak-{stamp}") + dest = sqlite3.connect(str(backup_path)) + with dest: + conn.backup(dest) + dest.close() + print(f"已备份到:{backup_path}") + + total = 0 + try: + with conn: + for name, sql, params in plan: + cursor = conn.execute(sql, params) + print(f" 已删除{name}: {cursor.rowcount} 条") + total += cursor.rowcount + except sqlite3.OperationalError as exc: + print(f"[!] 清除失败:{exc}") + print(" 若提示表不存在,请先启动一次服务(python -m server.main)完成建表后再试。") + conn.close() + return 1 + print(f"共删除 {total} 条记录。") + + try: + conn.execute("PRAGMA wal_checkpoint(TRUNCATE)") + conn.execute("VACUUM") + print(f"完成(VACUUM 后 {db_path.stat().st_size / 1024:.0f} KB)。") + except sqlite3.Error as exc: + print(f"VACUUM 已跳过({exc}),不影响清除结果。") + conn.close() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/config.toml b/config.toml new file mode 100644 index 0000000..e098ab4 --- /dev/null +++ b/config.toml @@ -0,0 +1,35 @@ +# WorkLog 配置。环境变量优先级更高:WORKLOG_HOST / WORKLOG_PORT / WORKLOG_DB / WORKLOG_SESSION_DAYS +# SMTP 凭据放在本机 .env;未配置邮件服务时拒绝发送验证码。 + +[server] +host = "0.0.0.0" +port = 37777 +frontend_dir = "./dist" +# 对外访问地址(用于邮件里的链接)。留空时使用本机地址; +# 通过固定域名/IP 访问时建议写全,如 "http://你的服务器IP:37777" +base_url = "" + +[notify] +# 有人发起活动(参与不算)时,给其他所有已注册用户发邮件通知,邮件里带"一键我也参加过"按钮 +enabled = true + +[database] +path = "./data/worklog.db" + +[auth] +# 登录有效期(天) +session_days = 30 +# 仅限绑定 127.0.0.1 的本机开发;生产必须关闭 +dev_mode = false + +[smtp] +host = "smtp.qq.com" +port = 465 +user = "" +password = "" +# 发件人,留空则用 user +from = "" +# ssl / starttls / none +tls = "ssl" +# 验证码有效期(分钟) +code_ttl_min = 10 diff --git a/dist/assets/styles.css b/dist/assets/styles.css new file mode 100644 index 0000000..0ae8491 --- /dev/null +++ b/dist/assets/styles.css @@ -0,0 +1,410 @@ +/* WorkLog 活动记录 — 样式 */ + +:root { + --bg: #f4f6fa; + --card: #ffffff; + --ink: #1f2430; + --muted: #6b7280; + --line: #e5e8ef; + --primary: #4361ee; + --primary-ink: #ffffff; + --primary-soft: #eef1fd; + --ok: #12805c; + --ok-soft: #e2f5ec; + --warn: #b45309; + --warn-soft: #fdf1e0; + --bad: #b42323; + --bad-soft: #fdeaea; + --radius: 14px; + --shadow: 0 1px 2px rgba(17, 24, 39, .05), 0 8px 24px -12px rgba(17, 24, 39, .12); +} + +* { box-sizing: border-box; } + +html, body { + margin: 0; + padding: 0; + background: var(--bg); + color: var(--ink); + font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif; + font-size: 15px; + line-height: 1.55; +} + +.hidden { display: none !important; } +.muted { color: var(--muted); font-size: 13px; } + +button { font: inherit; cursor: pointer; } +input, select, textarea { + font: inherit; + color: var(--ink); + background: #fff; + border: 1px solid var(--line); + border-radius: 10px; + padding: 9px 12px; + outline: none; +} +input:focus, select:focus, textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(67, 97, 238, .15); } +textarea { width: 100%; resize: vertical; } + +.btn { + border: 1px solid var(--line); + background: #fff; + color: var(--ink); + border-radius: 10px; + padding: 9px 16px; + font-weight: 500; + transition: .15s; +} +.btn:hover { border-color: var(--primary); color: var(--primary); } +.btn.primary { background: var(--primary); border-color: var(--primary); color: var(--primary-ink); } +.btn.primary:hover { filter: brightness(1.08); color: #fff; } +.btn.danger { color: var(--bad); border-color: #f2c4c4; } +.btn.danger:hover { background: var(--bad-soft); } +.btn.ghost { border-color: transparent; background: transparent; } +.btn.ghost:hover { background: var(--primary-soft); } +.btn.sm { padding: 5px 10px; font-size: 13px; border-radius: 8px; } +.btn.block { width: 100%; } +.btn:disabled { opacity: .55; cursor: not-allowed; } + +/* ---------- 顶栏 ---------- */ +#topbar { + position: sticky; + top: 0; + z-index: 50; + background: rgba(255, 255, 255, .92); + backdrop-filter: blur(8px); + border-bottom: 1px solid var(--line); +} +.topbar-inner { + max-width: 1080px; + margin: 0 auto; + display: flex; + align-items: center; + gap: 18px; + padding: 10px 20px; +} +.brand { font-weight: 700; font-size: 17px; white-space: nowrap; } +#nav { display: flex; gap: 4px; flex: 1; } +#nav a { + color: var(--muted); + text-decoration: none; + padding: 7px 12px; + border-radius: 9px; + font-weight: 500; +} +#nav a:hover { color: var(--ink); background: var(--primary-soft); } +#nav a.active { color: var(--primary); background: var(--primary-soft); } +.topbar-user { display: flex; align-items: center; gap: 10px; white-space: nowrap; } +#topbar-name { font-weight: 600; font-size: 14px; } +.menu-toggle { display: none; background: none; border: none; font-size: 20px; } + +/* ---------- 布局 ---------- */ +.container { max-width: 1080px; margin: 0 auto; padding: 24px 20px 60px; } +.container.narrow { max-width: 640px; } +.page-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 16px; + flex-wrap: wrap; + margin-bottom: 16px; +} +.page-head h2 { margin: 0 0 2px; font-size: 22px; } +.page-head p { margin: 0; } +.filters { display: flex; gap: 8px; flex-wrap: wrap; } +.filters input, .filters select { min-width: 130px; } + +.stats-row { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 18px; } +.stat { + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 10px 16px; + min-width: 96px; + box-shadow: var(--shadow); +} +.stat b { display: block; font-size: 20px; } +.stat span { color: var(--muted); font-size: 12px; } + +.chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; } +.chip { + border: 1px solid var(--line); + background: #fff; + border-radius: 999px; + padding: 4px 12px; + font-size: 13px; + color: var(--muted); +} +.chip.active { background: var(--primary); border-color: var(--primary); color: #fff; } +.chip:hover { border-color: var(--primary); color: var(--primary); } +.chip.active:hover { color: #fff; } + +/* ---------- 卡片列表 ---------- */ +.card-list { display: flex; flex-direction: column; gap: 12px; } +.acard { + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 16px 18px; + box-shadow: var(--shadow); + transition: .15s; +} +.acard:hover { border-color: #c9d4f5; } +.acard-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; } +.acard h3 { margin: 0; font-size: 17px; cursor: pointer; } +.acard h3:hover { color: var(--primary); } +.acard-meta { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; align-items: center; } +.meta-item { color: var(--muted); font-size: 13px; display: inline-flex; align-items: center; gap: 4px; } +.acard-desc { margin: 10px 0 0; color: #3d4351; font-size: 14px; white-space: pre-wrap; } +.acard-foot { + display: flex; + justify-content: space-between; + align-items: center; + gap: 10px; + flex-wrap: wrap; + margin-top: 12px; + padding-top: 12px; + border-top: 1px dashed var(--line); +} +.faces { display: flex; align-items: center; } +.face { + width: 28px; + height: 28px; + border-radius: 50%; + background: var(--primary); + color: #fff; + font-size: 12px; + font-weight: 600; + display: flex; + align-items: center; + justify-content: center; + border: 2px solid #fff; + margin-left: -8px; + cursor: pointer; +} +.face:first-child { margin-left: 0; } +.face.more { background: #e7eaf3; color: var(--muted); } +.face:hover { transform: translateY(-2px); } +.faces-label { margin-left: 8px; font-size: 13px; color: var(--muted); } +.acard-actions { display: flex; gap: 8px; flex-wrap: wrap; } + +.tag { + display: inline-block; + padding: 2px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 500; +} +.tag.cat { background: var(--primary-soft); color: var(--primary); } +.tag.pub { background: #e9f0fb; color: #275bd6; } +.tag.pri { background: #f0e9fb; color: #6d3fc0; } +.tag.joined { background: #e8f1fd; color: #1d5bbf; } +.tag.attended { background: var(--ok-soft); color: var(--ok); } +.tag.absent { background: var(--bad-soft); color: var(--bad); } +.tag.full { background: #f1f2f6; color: var(--muted); } + +/* ---------- 成员 ---------- */ +.member-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); + gap: 12px; +} +.mcard { + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 16px; + box-shadow: var(--shadow); + cursor: pointer; + transition: .15s; +} +.mcard:hover { border-color: #c9d4f5; transform: translateY(-2px); } +.mcard-top { display: flex; align-items: center; gap: 12px; } +.avatar { + width: 44px; + height: 44px; + border-radius: 50%; + background: linear-gradient(135deg, #4361ee, #7c3aed); + color: #fff; + font-weight: 600; + display: flex; + align-items: center; + justify-content: center; + font-size: 17px; + flex: none; +} +.mcard b { display: block; } +.mcard .muted { margin-top: 2px; } +.mcard-stats { display: flex; gap: 14px; margin-top: 12px; } +.mcard-stats div b { font-size: 16px; } +.mcard-stats div span { display: block; font-size: 12px; color: var(--muted); } +.mcard-bio { margin-top: 10px; font-size: 13px; color: #3d4351; } + +/* ---------- 个人主页 ---------- */ +.profile-header { + display: flex; + align-items: center; + gap: 16px; + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 20px; + box-shadow: var(--shadow); + margin-bottom: 14px; +} +.profile-header .avatar { width: 60px; height: 60px; font-size: 24px; } +.profile-header h2 { margin: 0; font-size: 20px; } +.profile-header p { margin: 3px 0 0; } + +/* ---------- 认证页 ---------- */ +.auth-wrap { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px; } +.auth-card { + width: 100%; + max-width: 400px; + background: var(--card); + border: 1px solid var(--line); + border-radius: 18px; + padding: 32px 28px; + box-shadow: var(--shadow); +} +.auth-title { margin: 0; font-size: 24px; text-align: center; } +.auth-sub { text-align: center; color: var(--muted); margin: 6px 0 18px; font-size: 13px; } +.tabs { display: flex; background: var(--bg); border-radius: 10px; padding: 4px; margin-bottom: 18px; } +.tab { flex: 1; border: none; background: transparent; padding: 8px; border-radius: 8px; font-weight: 500; color: var(--muted); } +.tab.active { background: #fff; color: var(--ink); box-shadow: var(--shadow); } + +/* ---------- 表单 ---------- */ +form label, .form-card label { display: block; margin-top: 14px; font-size: 13px; color: #3d4351; font-weight: 500; } +form input, form select, form textarea, .form-card input, .form-card select { width: 100%; margin-top: 5px; } +.hint-inline { color: var(--muted); font-weight: 400; } +.form-error { color: var(--bad); font-size: 13px; min-height: 18px; margin-top: 8px; } +.form-hint { font-size: 12px; margin-top: -6px; } +.code-row { display: flex; gap: 8px; margin-top: 5px; } +.code-row input { flex: 1; margin-top: 0; } +.code-row button { flex: none; white-space: nowrap; } +.code-row button:disabled { opacity: .55; cursor: not-allowed; } +.form-card { margin-bottom: 14px; } +.form-card h3 { margin: 0 0 4px; font-size: 16px; } +.form-row { display: flex; gap: 10px; } +.form-row > * { flex: 1; } +.form-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 18px; } +.checkline { display: flex; align-items: center; gap: 8px; margin-top: 14px; font-size: 14px; } +.checkline input { width: auto; margin: 0; } + +/* ---------- 弹层 ---------- */ +.modal-mask { + position: fixed; + inset: 0; + background: rgba(15, 23, 42, .45); + display: flex; + align-items: flex-start; + justify-content: center; + padding: 40px 16px; + z-index: 100; + overflow-y: auto; +} +.modal { + background: var(--card); + border-radius: 18px; + width: 100%; + max-width: 560px; + padding: 24px; + box-shadow: 0 24px 60px -12px rgba(15, 23, 42, .35); + animation: pop .18s ease-out; +} +@keyframes pop { from { transform: translateY(10px); opacity: 0; } to { transform: none; opacity: 1; } } +.modal h3 { margin: 0 0 4px; font-size: 18px; } +.modal .modal-sub { margin: 0 0 10px; } + +/* 详情 */ +.detail-head { display: flex; justify-content: space-between; gap: 12px; align-items: flex-start; } +.detail-meta { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 16px; margin: 14px 0; font-size: 14px; } +.detail-meta span.lbl { color: var(--muted); font-size: 12px; display: block; } +.detail-desc { + background: var(--bg); + border-radius: 10px; + padding: 12px 14px; + font-size: 14px; + white-space: pre-wrap; + margin: 12px 0; +} +.p-list { margin: 8px 0 0; padding: 0; list-style: none; } +.p-list li { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 0; + border-top: 1px dashed var(--line); + font-size: 14px; +} +.p-list li:first-child { border-top: none; } +.p-list .grow { flex: 1; } +.p-list .who { cursor: pointer; } +.p-list .who:hover { color: var(--primary); } +.p-list select { padding: 4px 8px; font-size: 13px; width: auto; } +.p-list .note { color: var(--muted); font-size: 12px; } +.add-member-row { display: flex; gap: 8px; margin-top: 12px; } +.add-member-row input { flex: 1; } + +/* ---------- 空态 / 加载 ---------- */ +.empty { + text-align: center; + color: var(--muted); + padding: 60px 20px; + border: 1px dashed var(--line); + border-radius: var(--radius); + background: rgba(255, 255, 255, .6); +} + +/* ---------- Toast ---------- */ +.toast { + position: fixed; + left: 50%; + bottom: 36px; + transform: translateX(-50%); + background: #1f2430; + color: #fff; + padding: 10px 18px; + border-radius: 999px; + font-size: 14px; + z-index: 200; + box-shadow: 0 10px 30px -8px rgba(0, 0, 0, .4); +} +.toast.err { background: var(--bad); } + +/* ---------- 响应式 ---------- */ +@media (max-width: 760px) { + #nav { + display: none; + position: absolute; + top: 100%; + left: 0; + right: 0; + background: #fff; + border-bottom: 1px solid var(--line); + flex-direction: column; + padding: 8px; + } + #nav.open { display: flex; } + .menu-toggle { display: block; margin-left: auto; } + .topbar-user { display: none; } + #new-activity-btn { display: none; } + .detail-meta { grid-template-columns: 1fr; } +} + +/* 成员简表 */ +#members-table { width: 100%; border-collapse: collapse; background: #fff; border: 1px solid var(--border, #e5e7eb); border-radius: 10px; overflow: hidden; } +#members-table th, #members-table td { padding: 10px 14px; text-align: left; border-bottom: 1px solid var(--border, #e5e7eb); font-size: 14px; } +#members-table th { background: #f9fafb; color: #6b7280; font-weight: 600; font-size: 13px; } +#members-table tbody tr:last-child td { border-bottom: none; } +#members-table tbody tr:hover { background: #f9fafb; } + +/* 审核 */ +.badge { display: inline-block; min-width: 16px; padding: 0 5px; margin-left: 4px; border-radius: 8px; background: #ef4444; color: #fff; font-size: 11px; line-height: 16px; text-align: center; } +.review-row { display: flex; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid #f0f0f0; } +.review-row:last-child { border-bottom: none; } +.review-row .grow { flex: 1; } +.tag.pending { background: #fef3c7; color: #92400e; } +.review-add { display: flex; align-items: center; gap: 8px; margin: 12px 0; } +.review-add input { flex: 1; margin-top: 0; } diff --git a/dist/index.html b/dist/index.html new file mode 100644 index 0000000..5192ed9 --- /dev/null +++ b/dist/index.html @@ -0,0 +1,181 @@ + + + + + + WorkLog · 活动记录 + + + +
+ + + + + + + +
+
+
+
+

活动墙

+

看看大家都在参加什么

+
+
+ + + + + +
+
+
+
+ +
+
+ + +
+
+
+
+

我的记录

+

按账号记录你参加过的每一场活动

+
+
+ + +
+
+
+
+ +
+
+ + +
+
+
+

成员

点开任意成员,查看 TA 的活动记录

+
+ + + +
+
+
+ + + + + +
+
+ + +
+
+ +
+
+
+ +
+
+ + +
+
+

账号设置

+
+

个人资料

+ + + + + +
+
+

登录方式

+

使用注册邮箱 + 邮箱验证码登录,无需密码。登录状态保持 30 天。

+
+
+
+ + + + + + + +
+ + diff --git a/dist/js/app.js b/dist/js/app.js new file mode 100644 index 0000000..7a5a2e9 --- /dev/null +++ b/dist/js/app.js @@ -0,0 +1,738 @@ +/* WorkLog 活动记录 — 前端逻辑(原生 JS,无构建步骤) */ +"use strict"; + +(() => { + const API = "/api"; + const TOKEN_KEY = "worklog_token"; + + // ------------------------------------------------------------- 工具 + const $ = (sel) => document.querySelector(sel); + const $$ = (sel) => Array.from(document.querySelectorAll(sel)); + + const esc = (s) => + String(s ?? "").replace(/[&<>"']/g, (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); + + let departments = []; + + const fmtDate = (ms) => + new Date(ms).toLocaleString("zh-CN", { + year: "numeric", month: "2-digit", day: "2-digit", + hour: "2-digit", minute: "2-digit", hour12: false, + }); + const fmtDay = (ms) => + new Date(ms).toLocaleDateString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" }); + + const STATUS_LABEL = { joined: "已确认", attended: "已参加", absent: "缺席" }; + const toLocalInput = (ms) => { + const d = new Date(ms - new Date().getTimezoneOffset() * 60000); + return d.toISOString().slice(0, 16); + }; + + let toastTimer = null; + const toast = (msg, isErr = false) => { + const el = $("#toast"); + el.textContent = msg; + el.classList.toggle("err", isErr); + el.classList.remove("hidden"); + clearTimeout(toastTimer); + toastTimer = setTimeout(() => el.classList.add("hidden"), 2600); + }; + + // ------------------------------------------------------------- API + const getToken = () => localStorage.getItem(TOKEN_KEY) || ""; + const setToken = (t) => (t ? localStorage.setItem(TOKEN_KEY, t) : localStorage.removeItem(TOKEN_KEY)); + + function apiErrorMessage(detail, status) { + if (typeof detail === "string") return detail; + if (Array.isArray(detail)) { + const labels = { display_name: "姓名", department: "所属部门", email: "邮箱", phone: "手机号", email_code: "邮箱验证码" }; + return detail.map((error) => { + const field = labels[error.loc?.at(-1)] || "填写内容"; + if (error.type === "missing") return `请填写${field}`; + if (error.type === "string_too_long") return `${field}最多填写 ${error.ctx?.max_length} 个字符`; + if (error.type === "string_too_short") return `${field}至少填写 ${error.ctx?.min_length} 个字符`; + const message = String(error.msg || "格式不正确").replace(/^Value error,\s*/, ""); + return /[\u4e00-\u9fff]/.test(message) ? message : `${field}格式不正确`; + }).join(";"); + } + return `请求失败(${status})`; + } + + async function api(path, { method = "GET", body } = {}) { + const headers = { "Content-Type": "application/json" }; + const token = getToken(); + if (token) headers.Authorization = `Bearer ${token}`; + let res; + try { + res = await fetch(API + path, { + method, headers, + body: body === undefined ? undefined : JSON.stringify(body), + }); + } catch { + throw new Error("网络异常,请稍后重试"); + } + const data = await res.json().catch(() => ({})); + if (!res.ok) { + if (res.status === 401 && getToken()) { + setToken(""); + showAuth(); + throw new Error("登录已过期,请重新登录"); + } + throw new Error(apiErrorMessage(data.detail, res.status)); + } + return data; + } + + // ------------------------------------------------------------- 状态 + const state = { + me: null, + view: "feed", + feed: { q: "", department: "", scope: "all", items: [] }, + mine: { q: "", status: "", items: [], stats: null }, + members: { q: "", items: [] }, + user: { id: "", data: null }, + }; + + // ------------------------------------------------------------- 视图切换 + const VIEWS = ["auth", "feed", "mine", "members", "user", "profile"]; + function show(view) { + state.view = view; + VIEWS.forEach((v) => $(`#${v}-view`).classList.toggle("hidden", v !== view)); + const logged = !!state.me; + $("#topbar").classList.toggle("hidden", view === "auth" || !logged); + $$("#nav a").forEach((a) => a.classList.toggle("active", a.dataset.view === view)); + $("#nav").classList.remove("open"); + if (view === "feed") loadFeed(); + if (view === "mine") loadMine(); + if (view === "members") loadMembers(); + if (view === "profile") fillProfile(); + } + const showAuth = () => show("auth"); + + function enterApp(me) { + state.me = me; + $("#topbar-name").textContent = me.display_name; + show("feed"); + } + + // ------------------------------------------------------------- 验证码(注册/登录共用) + function bindSendCode(btnId, emailSel, hintSel, errSel, purpose) { + let cooldownUntil = 0; // 发出成功后的冷却截止时间戳,期间按钮保持禁用 + $(btnId).addEventListener("click", async () => { + const btn = $(btnId); + const emailInput = $(emailSel); + const email = emailInput.value.trim(); + if (!emailInput.checkValidity() || !email) { + $(errSel).textContent = "请先填写正确的邮箱地址"; + return; + } + if (Date.now() < cooldownUntil) return; // 冷却期内忽略连点 + $(errSel).textContent = ""; + btn.disabled = true; + btn.textContent = "发送中…"; + try { + const data = await api("/auth/send-code", { method: "POST", body: { email, purpose } }); + if (data.dev_code) { + $(hintSel).textContent = `【本机开发模式】验证码:${data.dev_code}`; + } else { + $(hintSel).textContent = "验证码已发送到你的邮箱,请注意查收"; + } + cooldownUntil = Date.now() + 60_000; + let left = 60; + const tick = () => { + if (Date.now() >= cooldownUntil && left <= 0) { btn.disabled = false; btn.textContent = "获取验证码"; return; } + btn.textContent = `${left}s 后重发`; + left -= 1; + setTimeout(tick, 1000); + }; + tick(); + } catch (err) { + btn.disabled = false; + btn.textContent = "获取验证码"; + $(errSel).textContent = err.message; + } + }); + } + + // ------------------------------------------------------------- 认证 + $("#login-form").addEventListener("submit", async (e) => { + e.preventDefault(); + const f = e.target; + const btn = $("#login-submit"); + $("#login-error").textContent = ""; + btn.disabled = true; + try { + const data = await api("/auth/login", { + method: "POST", + body: { email: f.email.value.trim(), email_code: f.email_code.value.trim() }, + }); + setToken(data.token); + enterApp(data.user); + } catch (err) { $("#login-error").textContent = err.message; } + finally { btn.disabled = false; } + }); + bindSendCode("#login-code-btn", "#login-form [name=email]", "#login-hint", "#login-error", "login"); + + $("#register-form").addEventListener("submit", async (e) => { + e.preventDefault(); + const f = e.target; + const btn = $("#register-submit"); + $("#register-error").textContent = ""; + if (!f.display_name.value.trim()) { + $("#register-error").textContent = "请填写姓名"; + f.display_name.focus(); + return; + } + if (!f.department.value) { + $("#register-error").textContent = "请选择所属部门"; + f.department.focus(); + return; + } + if (!/^1[3-9]\d{9}$/.test(f.phone.value.trim())) { + $("#register-error").textContent = "请填写正确的 11 位手机号"; + return; + } + btn.disabled = true; + try { + const data = await api("/auth/register", { + method: "POST", + body: { + display_name: f.display_name.value.trim(), + department: f.department.value, + email: f.email.value.trim(), + phone: f.phone.value.trim(), + email_code: f.email_code.value.trim(), + }, + }); + setToken(data.token); + enterApp(data.user); + toast("欢迎加入 WorkLog 🎉"); + } catch (err) { $("#register-error").textContent = err.message; } + finally { btn.disabled = false; } + }); + bindSendCode("#send-code-btn", "#register-form [name=email]", "#register-hint", "#register-error", "register"); + + $$(".tab").forEach((t) => + t.addEventListener("click", () => { + $$(".tab").forEach((x) => x.classList.toggle("active", x === t)); + $("#login-form").classList.toggle("hidden", t.dataset.auth !== "login"); + $("#register-form").classList.toggle("hidden", t.dataset.auth !== "register"); + }) + ); + + $("#logout-btn").addEventListener("click", async () => { + try { await api("/auth/logout", { method: "POST" }); } catch { /* ignore */ } + setToken(""); + state.me = null; + showAuth(); + }); + + // ------------------------------------------------------------- 顶栏 + $("#brand").addEventListener("click", () => show("feed")); + $("#new-activity-btn").addEventListener("click", () => openActivityForm()); + $("#feed-new").addEventListener("click", () => openActivityForm()); + $("#menu-toggle").addEventListener("click", () => $("#nav").classList.toggle("open")); + $$("#nav a").forEach((a) => + a.addEventListener("click", (e) => { e.preventDefault(); show(a.dataset.view); }) + ); + + // ------------------------------------------------------------- 活动卡片 + const initials = (name) => { + const s = String(name || "?").trim(); + // 中文取第一个字,避免溢出小圆头像 + return esc(/[\u4e00-\u9fff]/.test(s) ? s.slice(0, 1) : s.slice(0, 2).toUpperCase()); + }; + + function activityCard(a, opts = {}) { + const mine = a.my_participation; + const isOrganizer = a.organizer_id === state.me.id; + const full = a.capacity && a.participant_count >= a.capacity; + const statusTag = mine + ? `${STATUS_LABEL[mine.status] || mine.status}` + : ""; + const visTag = a.visibility === "private" + ? `私密` + : `公开`; + + const faces = a.participants.slice(0, 6).map((p) => + `${initials(p.display_name)}` + ).join(""); + const more = a.participant_count > 6 + ? `+${a.participant_count - 6}` : ""; + + const actions = []; + // "我也参加过":点击直接加入 + if (!mine && a.visibility === "public" && !full) { + actions.push(``); + } + if (mine && !isOrganizer) { + actions.push(``); + } + if (isOrganizer) { + actions.push(``); + actions.push(``); + } + + return ` +
+
+
+

${esc(a.title)}

+
+ ${visTag}${statusTag} + ${full ? `已满 ${a.capacity} 人` : ""} + 📅 ${fmtDate(a.start_at)} + ${a.location ? `📍 ${esc(a.location)}` : ""} +
+
+
+ ${a.description ? `

${esc(a.description).slice(0, 160)}${a.description.length > 160 ? "…" : ""}

` : ""} +
+
+ ${faces}${more} + ${a.participant_count} 人${opts.showOrganizer && a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ""} +
+
${actions.join("")}
+
+
`; + } + + function bindCardEvents(container) { + container.querySelectorAll(".acard").forEach((card) => { + const id = card.dataset.id; + const activity = findActivity(id); + card.querySelectorAll("[data-act]").forEach((btn) => { + btn.addEventListener("click", async (e) => { + e.stopPropagation(); + const act = btn.dataset.act; + if (act === "open") return openDetail(id); + if (act === "claim") { + try { await api(`/activities/${id}/claim`, { method: "POST" }); toast("已加入这条记录"); refreshCurrent(); } + catch (err) { toast(err.message, true); } + } + if (act === "leave") { + if (!confirm("确定退出这条活动吗?")) return; + try { await api(`/activities/${id}/leave`, { method: "POST" }); toast("已退出"); refreshCurrent(); } + catch (err) { toast(err.message, true); } + } + if (act === "edit") return openActivityForm(activity); + if (act === "delete") { + if (!confirm("删除后该活动及所有人的参加记录都会消失,确定?")) return; + try { await api(`/activities/${id}`, { method: "DELETE" }); toast("已删除"); refreshCurrent(); } + catch (err) { toast(err.message, true); } + } + }); + }); + card.querySelectorAll("[data-user]").forEach((f) => + f.addEventListener("click", (e) => { e.stopPropagation(); openUser(f.dataset.user); }) + ); + }); + } + + function findActivity(id) { + return ( + state.feed.items.find((x) => x.id === id) || + state.mine.items.find((x) => x.id === id) || + (state.user.data && state.user.data.items.find((x) => x.id === id)) || + null + ); + } + + function refreshCurrent() { + if (state.view === "feed") loadFeed(); + else if (state.view === "mine") loadMine(); + else if (state.view === "user" && state.user.id) loadUser(state.user.id); + else if (state.view === "members") loadMembers(); + } + + // ------------------------------------------------------------- 活动墙 + async function loadFeed() { + const p = new URLSearchParams(); + if (state.feed.q) p.set("q", state.feed.q); + if (state.feed.department) p.set("department", state.feed.department); + if (state.feed.scope && state.feed.scope !== "all") p.set("scope", state.feed.scope); + const data = await api(`/activities?${p}`); + state.feed.items = data.items; + $("#feed-list").innerHTML = data.items.map((a) => activityCard(a, { showOrganizer: true })).join(""); + $("#feed-list").classList.toggle("hidden", !data.items.length); + $("#feed-empty").classList.toggle("hidden", !!data.items.length); + bindCardEvents($("#feed-list")); + try { + const ov = await api("/stats/overview"); + $("#feed-stats").innerHTML = ` +
${ov.members}成员
+
${ov.activities}公开活动
+
${ov.records}参加记录
+
${ov.upcoming}未开始
`; + } catch { $("#feed-stats").innerHTML = ""; } + } + + $("#feed-q").addEventListener("input", debounce(() => { state.feed.q = $("#feed-q").value.trim(); loadFeed(); }, 350)); + $("#feed-dept").addEventListener("change", () => { state.feed.department = $("#feed-dept").value; loadFeed(); }); + $("#feed-scope").addEventListener("change", () => { state.feed.scope = $("#feed-scope").value; loadFeed(); }); + $("#feed-refresh").addEventListener("click", loadFeed); + + // ------------------------------------------------------------- 我的记录 + async function loadMine() { + const data = await api("/auth/me"); + state.mine.stats = data.stats; + const all = await api(`/activities?scope=joined&limit=200`); + state.mine.items = all.items; + renderMine(); + } + + function renderMine() { + const { q, status } = { q: $("#mine-q").value.trim(), status: $("#mine-status").value }; + let items = state.mine.items; + if (q) items = items.filter((a) => (a.title + a.location).toLowerCase().includes(q.toLowerCase())); + if (status) items = items.filter((a) => a.my_participation && a.my_participation.status === status); + + const s = state.mine.stats || {}; + $("#mine-stats").innerHTML = ` +
${s.total ?? 0}全部记录
+
${s.attended ?? 0}已参加
+
${s.joined ?? 0}报名中
+
${s.absent ?? 0}缺席
+
${Math.round((s.attendance_rate || 0) * 100)}%出席率
`; + + $("#mine-list").innerHTML = items.map((a) => activityCard(a)).join(""); + $("#mine-list").classList.toggle("hidden", !items.length); + $("#mine-empty").classList.toggle("hidden", !!items.length); + bindCardEvents($("#mine-list")); + } + + $("#mine-q").addEventListener("input", debounce(renderMine, 200)); + $("#mine-status").addEventListener("change", renderMine); + + // ------------------------------------------------------------- 成员 + async function loadMembers() { + const q = $("#members-q").value.trim(); + const dept = $("#members-dept").value; + const p = new URLSearchParams(); + if (q) p.set("q", q); + if (dept) p.set("department", dept); + const data = await api(`/users?${p}`); + state.members.items = data.items; + const compact = !$("#members-table").classList.contains("hidden"); + $("#members-list").innerHTML = data.items.map((u) => ` +
+
+
${initials(u.display_name)}
+
+ ${esc(u.display_name)} +
${u.department ? esc(u.department) : ""}
+
+
+
+
${u.total}参加
+
${u.attended}已参加
+
${u.organized}发起
+
+
`).join(""); + $("#members-table tbody").innerHTML = data.items.map((u) => ` + + ${esc(u.display_name)} + ${esc(u.department || "—")} + ${u.total} + `).join(""); + $("#members-list").classList.toggle("hidden", !data.items.length || compact); + $("#members-table").classList.toggle("hidden", !data.items.length || !compact); + $("#members-empty").classList.toggle("hidden", !!data.items.length); + $$("#members-list .mcard").forEach((c) => + c.addEventListener("click", () => openUser(c.dataset.user)) + ); + } + + $("#members-compact").addEventListener("click", () => { + const table = $("#members-table"); + const toCompact = table.classList.contains("hidden"); + table.classList.toggle("hidden", !toCompact); + $("#members-list").classList.toggle("hidden", toCompact || !$("#members-list").innerHTML); + $("#members-compact").textContent = toCompact ? "卡片" : "简表"; + }); + + $("#members-q").addEventListener("input", debounce(loadMembers, 300)); + $("#members-dept").addEventListener("change", loadMembers); + + function fillMembersDept() { + $("#members-dept").innerHTML = `` + + (departments || []).map((d) => ``).join(""); + } + + // ------------------------------------------------------------- 他人主页 + async function openUser(userId) { + $("#user-view").classList.add("hidden"); + state.user.id = userId; + await loadUser(userId); + show("user"); + } + + async function loadUser(userId) { + const data = await api(`/users/${userId}`); + state.user.data = data; + const u = data.user; + $("#user-header").innerHTML = ` +
${initials(u.display_name)}
+
+

${esc(u.display_name)} ${data.is_self ? '我' : ""}

+

${u.department ? `${esc(u.department)} · ` : ""}加入于 ${fmtDay(u.created_at)}

+
`; + const s = data.stats; + $("#user-stats").innerHTML = ` +
${s.total}可见记录
+
${s.attended}已参加
+
${s.organized}发起
+
${Math.round((s.attendance_rate || 0) * 100)}%出席率
`; + $("#user-list").innerHTML = data.items.map((a) => activityCard(a)).join(""); + $("#user-list").classList.toggle("hidden", !data.items.length); + $("#user-empty").classList.toggle("hidden", !!data.items.length); + bindCardEvents($("#user-list")); + } + + $("#user-back").addEventListener("click", () => show("members")); + + // ------------------------------------------------------------- 弹层 + function modal(html) { + $("#modal-root").innerHTML = ``; + const mask = $("#modal-root .modal-mask"); + mask.addEventListener("click", (e) => { if (e.target === mask) closeModal(); }); + document.addEventListener("keydown", escListener); + return mask; + } + const escListener = (e) => { if (e.key === "Escape") closeModal(); }; + const closeModal = () => { $("#modal-root").innerHTML = ""; document.removeEventListener("keydown", escListener); }; + + // ---- 新建 / 编辑活动 + function openActivityForm(existing = null) { + const isEdit = !!existing; + modal(` +

${isEdit ? "编辑活动" : "记录一场活动"}

+ +
+ +
+ + +
+ + +
+
+ + +
+
`); + + $("#act-cancel").addEventListener("click", closeModal); + $("#act-form").addEventListener("submit", async (e) => { + e.preventDefault(); + const f = e.target; + const btn = $("#act-submit"); + const startMs = f.start_at.value ? new Date(f.start_at.value).getTime() : 0; + if (!startMs) { $("#act-error").textContent = "请选择开始时间"; return; } + const body = { + title: f.title.value.trim(), + start_at: startMs, + location: f.location.value.trim(), + description: f.description.value.trim(), + visibility: f.visibility.checked ? "public" : "private", + }; + btn.disabled = true; + try { + if (isEdit) { + await api(`/activities/${existing.id}`, { method: "PATCH", body }); + toast("已保存"); + } else { + const data = await api("/activities", { method: "POST", body }); + toast(data.duplicate ? "这条记录刚刚已提交过" : "已记录 ✓"); + } + closeModal(); + refreshCurrent(); + } catch (err) { + $("#act-error").textContent = err.message; + btn.disabled = false; + } + }); + } + + // ---- 活动详情 + async function openDetail(id) { + let data; + try { data = await api(`/activities/${id}`); } catch (err) { toast(err.message, true); return; } + const a = data.activity; + const canEdit = data.can_edit; + const mine = a.my_participation; + const full = a.capacity && a.participant_count >= a.capacity; + + const rows = a.participants.map((p) => { + const isSelfRow = p.user_id === state.me.id; + const canManage = canEdit || isSelfRow; + const statusSel = canManage + ? `` + : `${STATUS_LABEL[p.status] || p.status}`; + const removeBtn = (canEdit && p.role !== "organizer") || (isSelfRow && p.role !== "organizer") + ? `` + : ""; + return `
  • + ${initials(p.display_name)} + ${esc(p.display_name)} + ${p.role === "organizer" ? '· 记录人' : ""} + ${p.note ? `
    ${esc(p.note)}
    ` : ""} +
    + ${statusSel}${removeBtn} +
  • `; + }).join(""); + + const claimBtn = !mine && a.visibility === "public" && !full + ? `` : ""; + const leaveBtn = mine && !canEdit + ? `` : ""; + const editBtn = canEdit ? `` : ""; + const delBtn = canEdit ? `` : ""; + const noteRow = mine + ? `` + : ""; + + modal(` +
    +
    +

    ${esc(a.title)}

    +
    + ${a.visibility === "private" ? `私密` : `公开`} + ${mine ? `${STATUS_LABEL[mine.status] || mine.status}` : ""} + ${full ? `名额已满` : ""} +
    +
    + +
    +
    +
    时间📅 ${fmtDate(a.start_at)}${a.start_at >= Date.now() ? "(未开始)" : ""}
    +
    地点📍 ${a.location ? esc(a.location) : "未填写"}
    +
    记录人${esc(a.organizer?.display_name || "未知")}
    +
    人数${a.participant_count}${a.capacity ? ` / ${a.capacity}` : ""} · 已参加 ${a.attended_count}
    +
    + ${a.description ? `
    ${esc(a.description)}
    ` : ""} + ${noteRow} +

    一起参加过(${a.participant_count})

    + +
    + ${claimBtn}${leaveBtn}${editBtn}${delBtn} +
    `); + + $("#d-close").addEventListener("click", closeModal); + + const reload = async () => { + closeModal(); + await openDetail(id); + refreshCurrent(); + }; + + const on = (sel, fn) => { const el = $(sel); if (el) el.addEventListener("click", fn); }; + on("#d-claim", async () => { try { await api(`/activities/${id}/claim`, { method: "POST" }); toast("已加入这条记录"); reload(); } catch (err) { toast(err.message, true); } }); + on("#d-leave", async () => { + if (!confirm("确定退出这条活动吗?")) return; + try { await api(`/activities/${id}/leave`, { method: "POST" }); toast("已退出"); reload(); } catch (err) { toast(err.message, true); } + }); + on("#d-edit", () => openActivityForm(a)); + on("#d-del", async () => { + if (!confirm("删除后该活动及所有人的参加记录都会消失,确定?")) return; + try { await api(`/activities/${id}`, { method: "DELETE" }); toast("已删除"); closeModal(); refreshCurrent(); } catch (err) { toast(err.message, true); } + }); + + const noteInput = $("#d-note"); + if (noteInput) { + let timer = null; + noteInput.addEventListener("input", () => { + clearTimeout(timer); + timer = setTimeout(async () => { + try { + await api(`/activities/${id}/participants/${state.me.id}`, { method: "PATCH", body: { note: noteInput.value } }); + } catch (err) { toast(err.message, true); } + }, 600); + }); + } + + $$("#modal-root [data-role=status]").forEach((sel) => + sel.addEventListener("change", async () => { + try { + await api(`/activities/${id}/participants/${sel.dataset.uid}`, { method: "PATCH", body: { status: sel.value } }); + toast("状态已更新"); + reload(); + } catch (err) { toast(err.message, true); } + }) + ); + $$("#modal-root [data-role=remove]").forEach((btn) => + btn.addEventListener("click", async () => { + if (!confirm("将该成员移出这条活动?")) return; + try { await api(`/activities/${id}/participants/${btn.dataset.uid}`, { method: "DELETE" }); toast("已移出"); reload(); } + catch (err) { toast(err.message, true); } + }) + ); + $$("#modal-root [data-user]").forEach((f) => + f.addEventListener("click", () => { closeModal(); openUser(f.dataset.user); }) + ); + } + + // ------------------------------------------------------------- 设置 + function fillProfile() { + $("#pf-name").value = state.me.display_name; + $("#pf-dept").value = state.me.department || ""; + $("#pf-phone").value = state.me.phone || ""; + $("#pf-email").textContent = state.me.email || "(未绑定)"; + } + $("#pf-save").addEventListener("click", async () => { + const phone = $("#pf-phone").value.trim(); + if (phone && !/^1[3-9]\d{9}$/.test(phone)) { toast("请填写正确的 11 位手机号", true); return; } + try { + const data = await api("/auth/me", { method: "PATCH", body: { display_name: $("#pf-name").value.trim(), department: $("#pf-dept").value, phone } }); + state.me = data.user; + $("#topbar-name").textContent = state.me.display_name; + toast("资料已保存"); + } catch (err) { toast(err.message, true); } + }); + + // ------------------------------------------------------------- 启动 + function debounce(fn, wait) { + let t = null; + return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), wait); }; + } + + function fillFeedDept() { + $("#feed-dept").innerHTML = `` + + (departments || []).map((d) => ``).join(""); + } + + async function boot() { + try { + const m = await api("/meta"); + departments = m.departments || []; + // 注册页部门下拉:固定五个部门 + const deptOptions = + `` + + departments.map((d) => ``).join(""); + $("#register-form [name=department]").innerHTML = deptOptions; + // 设置页部门下拉(可留空表示未选择) + $("#pf-dept").innerHTML = + `` + + departments.map((d) => ``).join(""); + // 活动墙部门筛选:固定五个部门,未登录即可用 + fillFeedDept(); + // 成员页部门筛选 + fillMembersDept(); + } catch { + $("#register-error").textContent = "部门信息加载失败,请刷新页面重试"; + } + + if (!getToken()) return showAuth(); + try { + const data = await api("/auth/me"); + enterApp(data.user); + } catch { showAuth(); } + } + + boot(); +})(); diff --git a/package.bat b/package.bat new file mode 100644 index 0000000..8a33c43 --- /dev/null +++ b/package.bat @@ -0,0 +1,66 @@ +@echo off +setlocal enabledelayedexpansion + +rem ============================================================ +rem Package script: stop the local WorkLog service, then zip the +rem project. The database (data/), logs and caches are excluded. +rem Usage: package.bat (output: worklog-.zip in this folder) +rem ============================================================ + +set "PROJECT_DIR=%~dp0" +if "%PROJECT_DIR:~-1%"=="\" set "PROJECT_DIR=%PROJECT_DIR:~0,-1%" + +if not defined WORKLOG_PORT set "WORKLOG_PORT=37777" + +rem ---------- 1. stop the service listening on the port ---------- +echo [1/2] Checking port %WORKLOG_PORT% ... +set "STOPPED=" +for /f "tokens=5" %%P in ('netstat -ano ^| findstr /r /c:":%WORKLOG_PORT% .*LISTENING"') do ( + if not "%%P"=="0" ( + echo Stopping PID=%%P + taskkill /F /PID %%P >nul 2>&1 + set "STOPPED=1" + ) +) +if defined STOPPED ( + echo Local service stopped. + timeout /t 1 /nobreak >nul +) else ( + echo Nothing listening on port %WORKLOG_PORT%. +) + +rem ---------- 2. package ---------- +for /f %%I in ('powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss"') do set "STAMP=%%I" +set "ZIP_NAME=worklog-%STAMP%.zip" +set "ZIP_PATH=%PROJECT_DIR%\%ZIP_NAME%" +set "STAGE=%TEMP%\worklog-pkg-%STAMP%" + +echo [2/2] Packing ... +if exist "%STAGE%" rmdir /s /q "%STAGE%" +mkdir "%STAGE%" >nul 2>&1 + +rem Exclude dirs: __pycache__ / .venv / .git / data (data holds the database) +robocopy "%PROJECT_DIR%" "%STAGE%" /E /XD __pycache__ .venv .git data /XF .env .env.* .run-dev.log *.log *.pyc *.zip *.db *.db-* *.sqlite *.sqlite-* *.sqlite3 *.sqlite3-* *.bak* /NFL /NDL /NJH /NJS /NP >nul +if errorlevel 8 ( + echo Copy failed, aborted. + rmdir /s /q "%STAGE%" >nul 2>&1 + exit /b 1 +) +copy /y "%PROJECT_DIR%\.env.example" "%STAGE%\.env.example" >nul + +if exist "%ZIP_PATH%" del /f /q "%ZIP_PATH%" +rem Python zipfile keeps forward slashes in entry names (Compress-Archive writes backslashes) +python -c "import os,zipfile;S=r'%STAGE%';O=r'%ZIP_PATH%';z=zipfile.ZipFile(O,'w',zipfile.ZIP_DEFLATED);[z.write(os.path.join(R,f),os.path.relpath(os.path.join(R,f),S).replace(chr(92),'/')) for R,D,F in os.walk(S) for f in F];z.close()" +if errorlevel 1 ( + echo Compression failed, aborted. + rmdir /s /q "%STAGE%" >nul 2>&1 + exit /b 1 +) + +rmdir /s /q "%STAGE%" >nul 2>&1 + +for %%I in ("%ZIP_PATH%") do set "ZIP_SIZE=%%~zI" +echo. +echo Done: %ZIP_PATH% +echo Size: %ZIP_SIZE% bytes (database data/ excluded) +endlocal diff --git a/package.sh b/package.sh new file mode 100644 index 0000000..ba7ed8a --- /dev/null +++ b/package.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# 打包脚本:停掉本地正在运行的 WorkLog 服务,然后打成 zip(不含数据库/日志/运行产物)。 +# 用法:bash package.sh (产物:worklog-<日期>.zip,放在项目同级目录) +set -euo pipefail + +PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +APP_NAME="WorkLog" +PORT="${WORKLOG_PORT:-37777}" +PYTHON="${PYTHON:-python}" + +# ---------- 1. 关闭本地服务 ---------- +# 优先按端口找进程(Windows 用 netstat,Linux/mac 用 lsof/ss) +stopped=0 +if command -v netstat.exe >/dev/null 2>&1 && command -v taskkill.exe >/dev/null 2>&1; then + pids=$(netstat.exe -ano | grep -E "TCP.*:${PORT}\s.*LISTENING" | awk '{print $5}' | sort -u || true) + for pid in $pids; do + if [ -n "$pid" ] && [ "$pid" != "0" ]; then + echo "停止进程 PID=$pid (端口 $PORT)" + taskkill.exe //F //PID "$pid" || true + stopped=1 + fi + done +else + if command -v lsof >/dev/null 2>&1; then + pids=$(lsof -ti tcp:"$PORT" 2>/dev/null || true) + elif command -v ss >/dev/null 2>&1; then + pids=$(ss -lptn "sport = :$PORT" 2>/dev/null | grep -oP 'pid=\K[0-9]+' | sort -u) + else + pids="" + fi + for pid in $pids; do + echo "停止进程 PID=$pid (端口 $PORT)" + kill -9 "$pid" 2>/dev/null || true + stopped=1 + done +fi +[ "$stopped" = "1" ] && echo "本地服务已停止" || echo "端口 $PORT 上没有运行中的服务" +sleep 1 + +# ---------- 2. 打包 ---------- +STAMP="$(date +%Y%m%d-%H%M%S)" +ZIP_NAME="worklog-${STAMP}.zip" + +# 用 Python zipfile 打包(Windows Git Bash 无 zip 命令),排除数据库/日志/缓存 +"$PYTHON" - "$PROJECT_DIR" "$ZIP_NAME" << 'PYEOF' +import fnmatch, os, sys, zipfile + +project, zip_name = os.path.abspath(sys.argv[1]), sys.argv[2] +out_path = os.path.join(os.path.dirname(project), zip_name) +skip_dirs = {"__pycache__", ".venv", ".git", "data"} +skip_files = {".env", ".run-dev.log"} +skip_ext = (".pyc", ".zip", ".log") + +with zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED) as zf: + for root, dirs, files in os.walk(project): + dirs[:] = [d for d in dirs if d not in skip_dirs] + for f in files: + if (f in skip_files or f.endswith(skip_ext) + or (f.startswith('.env.') and f != '.env.example') + or any(fnmatch.fnmatch(f, pattern) for pattern in ('*.db', '*.db-*', '*.sqlite', '*.sqlite-*', '*.sqlite3', '*.sqlite3-*', '*.bak*'))): + continue + full = os.path.join(root, f) + arc = os.path.relpath(full, project).replace(os.sep, "/") + zf.write(full, arc) +print("packed ->", out_path) +PYEOF + +echo "打包完成:$(dirname "$PROJECT_DIR")/$ZIP_NAME" diff --git a/repair_db.py b/repair_db.py new file mode 100644 index 0000000..a0c0ce7 --- /dev/null +++ b/repair_db.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""WorkLog 数据库损坏检测与修复脚本(Windows / Linux 通用,只用标准库)。 + +用法: + python repair_db.py --check 只做完整性检测 + python repair_db.py 检测,损坏则恢复到 <库名>.recovered + python repair_db.py --replace -y 恢复后用修复库替换原库(坏库存为 .corrupt-时间戳) + +说明: + "database disk image is malformed" 表示数据库文件损坏,常见诱因: + 服务运行中直接拷贝/上传覆盖了 db 文件、文件传输被截断、磁盘写满、 + 残留的 -wal/-shm 文件与主库不匹配。 + 修复优先用 sqlite3 命令行的 .recover(最完整);没有 sqlite3 命令时 + 退化为逐表读取复制(损坏页所在表的数据可能缺失,脚本会逐表报告)。 +""" + +from __future__ import annotations + +import argparse +import os +import shutil +import sqlite3 +import subprocess +import sys +from datetime import datetime +from pathlib import Path + +PROJECT_DIR = Path(__file__).resolve().parent +TABLES = ("users", "sessions", "email_verifications", "activities", "participations") +SIDE_SUFFIXES = ("-wal", "-shm", "-journal") + + +def resolve_db_path(explicit: str | None) -> Path: + """与 server/main.py / clear_db.py 一致:--db > WORKLOG_DB > config.toml > ./data/worklog.db""" + raw = explicit or os.getenv("WORKLOG_DB") + if not raw: + raw = "./data/worklog.db" + config_path = Path(os.getenv("WORKLOG_CONFIG", str(PROJECT_DIR / "config.toml"))) + try: + import tomllib + + with open(config_path, "rb") as fh: + cfg = tomllib.load(fh) + raw = cfg.get("database", {}).get("path", raw) + except Exception: + pass + path = Path(raw) + return path if path.is_absolute() else PROJECT_DIR / path + + +def integrity_report(path: Path) -> tuple[bool, str]: + """返回 (是否完好, 详情)。只读打开,不改动文件。""" + try: + conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True) + except sqlite3.DatabaseError as exc: + return False, f"无法打开数据库:{exc}" + try: + rows = conn.execute("PRAGMA integrity_check").fetchall() + except sqlite3.DatabaseError as exc: + return False, str(exc) + finally: + conn.close() + bad = [r[0] for r in rows if r[0] != "ok"] + return (not bad), ("ok" if not bad else ";".join(bad[:5])) + + +def table_counts(path: Path) -> dict[str, int | None]: + counts: dict[str, int | None] = {} + try: + conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True) + except sqlite3.DatabaseError: + return {t: None for t in TABLES} + for table in TABLES: + try: + counts[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] + except sqlite3.DatabaseError: + counts[table] = None + conn.close() + return counts + + +def recover_with_cli(src: Path, dst: Path) -> bool: + """sqlite3 命令行可用时用 .recover,最完整。""" + cli = shutil.which("sqlite3") + if not cli: + return False + proc = subprocess.run([cli, str(src), ".recover"], capture_output=True, text=True) + if proc.returncode != 0 or not proc.stdout.strip(): + return False + dst.unlink(missing_ok=True) + out = sqlite3.connect(str(dst)) + try: + out.executescript(proc.stdout) + out.commit() + except sqlite3.DatabaseError: + out.close() + return False + out.close() + return True + + +def recover_with_python(src: Path, dst: Path) -> tuple[bool, list[str]]: + """兜底方案:只读打开坏库,逐表复制到新库。返回 (是否成功, 说明)。""" + notes: list[str] = [] + try: + ro = sqlite3.connect(f"file:{src}?mode=ro&immutable=1", uri=True) + except sqlite3.DatabaseError as exc: + return False, [f"坏库打不开:{exc}"] + try: + master = ro.execute( + "SELECT type, name, sql FROM sqlite_master WHERE sql IS NOT NULL" + ).fetchall() + except sqlite3.DatabaseError as exc: + ro.close() + return False, [f"连表结构都读不出来,无法恢复({exc}),只能删库重建。"] + + dst.unlink(missing_ok=True) + out = sqlite3.connect(str(dst)) + tables: list[str] = [] + for typ, name, sql in master: + if name.startswith("sqlite_"): + continue + try: + out.execute(sql) + if typ == "table": + tables.append(name) + except sqlite3.DatabaseError as exc: + notes.append(f"跳过 {typ} {name}:{exc}") + out.commit() + + for table in tables: + recovered = 0 + truncated = False + try: + cur = ro.execute(f'SELECT * FROM "{table}"') + except sqlite3.DatabaseError as exc: + notes.append(f"表 {table} 无法读取:{exc}") + continue + cols = [d[0] for d in cur.description] + col_list = ",".join(f'"{c}"' for c in cols) + marks = ",".join("?" * len(cols)) + insert = f'INSERT OR IGNORE INTO "{table}" ({col_list}) VALUES ({marks})' + while True: + try: + batch = cur.fetchmany(200) + except sqlite3.DatabaseError as exc: + notes.append(f"表 {table} 读取中断于第 {recovered} 行之后:{exc}") + truncated = True + break + if not batch: + break + try: + out.executemany(insert, batch) + out.commit() + recovered += len(batch) + except sqlite3.DatabaseError: + # 这一批里混着坏行,逐行抢救能救多少是多少 + for row in batch: + try: + out.execute(insert, row) + recovered += 1 + except sqlite3.DatabaseError: + pass + out.commit() + print(f" 表 {table}: 恢复 {recovered} 行" + ("(有缺失)" if truncated else "")) + + out.commit() + out.close() + ro.close() + return True, notes + + +def main() -> int: + parser = argparse.ArgumentParser(description="WorkLog 数据库损坏检测与修复") + parser.add_argument("--db", help="数据库文件路径(默认 WORKLOG_DB / config.toml)") + parser.add_argument("--check", action="store_true", help="只检测,不修复") + parser.add_argument("--replace", action="store_true", help="修复成功后替换原库(坏库自动备份)") + parser.add_argument("-y", "--yes", action="store_true", help="跳过确认") + args = parser.parse_args() + + db_path = resolve_db_path(args.db) + if not db_path.exists(): + print(f"[!] 数据库不存在:{db_path}") + return 1 + + print(f"数据库:{db_path} ({db_path.stat().st_size / 1024:.0f} KB)") + for suffix in SIDE_SUFFIXES: + side = db_path.with_name(db_path.name + suffix) + if side.exists(): + print(f" 注意:存在伴随文件 {side.name} ({side.stat().st_size / 1024:.0f} KB)") + + healthy, report = integrity_report(db_path) + if healthy: + print("完整性检查:通过,数据库没有损坏。") + return 0 + + print(f"完整性检查:损坏({report})") + if args.check: + return 1 + + if not args.yes: + print("修复前请确认服务已停止(运行中的服务继续写坏库会越写越糟)。") + if input("输入 yes 继续: ").strip().lower() != "yes": + print("已取消。") + return 0 + + recovered_path = db_path.with_suffix(db_path.suffix + ".recovered") + notes: list[str] = [] + if recover_with_cli(db_path, recovered_path): + print("已用 sqlite3 .recover 完成恢复。") + else: + print("sqlite3 命令行不可用,用逐表复制方式恢复……") + ok, notes = recover_with_python(db_path, recovered_path) + if not ok: + for line in notes: + print(f" {line}") + print("[!] 恢复失败。若数据不重要,删除该库重启服务即可重建空库。") + return 1 + + ok2, report2 = integrity_report(recovered_path) + print(f"修复库完整性:{'通过' if ok2 else '仍有问题(' + report2 + ')'}") + print("修复后各表行数:") + for table, count in table_counts(recovered_path).items(): + print(f" {table:<20}{count if count is not None else '(表不存在)'}") + for line in notes: + print(f" 备注:{line}") + + if args.replace: + stamp = datetime.now().strftime("%Y%m%d-%H%M%S") + corrupt_backup = db_path.with_name(f"{db_path.name}.corrupt-{stamp}") + db_path.rename(corrupt_backup) + for suffix in SIDE_SUFFIXES: + side = db_path.with_name(db_path.name + suffix) + if side.exists(): + # 旧库的 wal/shm 绝不能留给新库用,一并挪走 + side.rename(db_path.with_name(f"{db_path.name}{suffix}.corrupt-{stamp}")) + recovered_path.replace(db_path) + print(f"已替换。坏库保留在:{corrupt_backup}") + print("现在可以启动服务了(python -m server.main 或 bash start.sh)。") + else: + print(f"修复库在:{recovered_path}") + print("确认无误后手动替换:") + print(f" mv {db_path} {db_path}.corrupt && mv {recovered_path} {db_path}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..78d3607 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +fastapi>=0.115,<1 +uvicorn[standard]>=0.30,<1 +SQLAlchemy>=2.0.36,<3 +aiosqlite>=0.20,<1 +aiosmtplib>=3,<6 +pydantic>=2.7,<3 +# 仅测试时需要 +httpx>=0.27,<1 diff --git a/server/__init__.py b/server/__init__.py new file mode 100644 index 0000000..8c0e132 --- /dev/null +++ b/server/__init__.py @@ -0,0 +1 @@ +"""WorkLog 活动记录网站后端包。""" diff --git a/server/main.py b/server/main.py new file mode 100644 index 0000000..5c12876 --- /dev/null +++ b/server/main.py @@ -0,0 +1,1495 @@ +"""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} 发起了一场新活动

    +
    +

    {activity["title"]}

    + {detail}
    +
    +

    如果你也参加了这场活动,点下面的按钮一条记录即可:

    +

    + 我也参加过 +

    +

    + 打开链接后确认参加,链接 {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() diff --git a/server/models.py b/server/models.py new file mode 100644 index 0000000..708b669 --- /dev/null +++ b/server/models.py @@ -0,0 +1,131 @@ +"""数据库表结构(SQLAlchemy Core)。 + +四张表:users(账号)、sessions(登录会话)、activities(活动)、 +participations(参加记录,也就是"某人参加过某活动"这一事实)。 +时间统一存毫秒时间戳整数,前端用 new Date(ms) 渲染。 +""" + +from __future__ import annotations + +from sqlalchemy import ( + Column, + ForeignKey, + Index, + Integer, + MetaData, + String, + Table, + Text, + UniqueConstraint, + func, +) + +metadata = MetaData() + +auth_limits = Table( + "auth_limits", metadata, + Column("key", String(64), primary_key=True), + Column("window_start", Integer, nullable=False), + Column("count", Integer, nullable=False), +) + +users = Table( + "users", + metadata, + Column("id", String(36), primary_key=True), + Column("username", String(64), nullable=False, unique=True), + Column("display_name", String(64), nullable=False), + Column("department", String(64), nullable=False, default=""), + Column("email", String(255), nullable=False, default=""), + # 登录改为邮箱+验证码后不再用密码,但列保留(老数据兼容) + Column("password_hash", String(255), nullable=False, default=""), + # 邮箱用于验证码登录;新用户注册必填手机号,一人一号(历史空值保留兼容) + Column("phone", String(11), nullable=False, default=""), + # 遗留列:管理员体系已移除,但老库的 role 列带 NOT NULL 约束,插入必须带上 + Column("role", String(16), nullable=False, default="member"), + Column("bio", String(200), nullable=False, default=""), + Column("created_at", Integer, nullable=False), + Column("last_login_at", Integer, nullable=False, default=0), +) +Index("ix_users_email", users.c.email) +Index("uq_users_email", func.lower(users.c.email), unique=True, sqlite_where=users.c.email != "") +Index("uq_users_phone", users.c.phone, unique=True, sqlite_where=users.c.phone != "") + +email_verifications = Table( + "email_verifications", + metadata, + Column("id", String(36), primary_key=True), + Column("email", String(255), nullable=False), + Column("code", String(255), nullable=False), + Column("attempts", Integer, nullable=False, default=0), + # 预留:register / reset 等用途 + Column("purpose", String(32), nullable=False, default="register"), + Column("expires_at", Integer, nullable=False), + Column("used", Integer, nullable=False, default=0), + Column("created_at", Integer, nullable=False), +) +Index("ix_email_verifications_email", email_verifications.c.email) + +sessions = Table( + "sessions", + metadata, + Column("token", String(64), primary_key=True), + Column("user_id", String(36), ForeignKey("users.id", ondelete="CASCADE"), nullable=False), + Column("created_at", Integer, nullable=False), + Column("expires_at", Integer, nullable=False), +) +Index("ix_sessions_user", sessions.c.user_id) + +activities = Table( + "activities", + metadata, + Column("id", String(36), primary_key=True), + Column("title", String(120), nullable=False), + Column("start_at", Integer, nullable=False), + Column("location", String(120), nullable=False, default=""), + Column("description", Text, nullable=False, default=""), + Column("visibility", String(16), nullable=False, default="public"), + # 名额上限;NULL 表示不限 + Column("capacity", Integer, nullable=True), + # 兼容老库保留该列;无审核流后恒为 approved + Column("status", String(16), nullable=False, default="approved"), + Column("organizer_id", String(36), ForeignKey("users.id"), nullable=False), + Column("created_at", Integer, nullable=False), + Column("updated_at", Integer, nullable=False), +) +Index("ix_activities_start", activities.c.start_at) +Index("ix_activities_organizer", activities.c.organizer_id) + +participations = Table( + "participations", + metadata, + Column("id", String(36), primary_key=True), + Column("activity_id", String(36), ForeignKey("activities.id", ondelete="CASCADE"), nullable=False), + Column("user_id", String(36), ForeignKey("users.id", ondelete="CASCADE"), nullable=False), + # organizer 为发起人,member 为共同参加人("我也参加过") + Column("role", String(16), nullable=False, default="member"), + # 参加状态:joined 已确认 / attended 已参加 / absent 缺席 + Column("status", String(16), nullable=False, default="joined"), + Column("note", String(500), nullable=False, default=""), + Column("joined_at", Integer, nullable=False), + Column("updated_at", Integer, nullable=False), + UniqueConstraint("activity_id", "user_id", name="uq_participation_activity_user"), +) +Index("ix_participations_user", participations.c.user_id) + +join_links = Table( + "join_links", + metadata, + # 邮件"一键我也参加过"的令牌:点一次即消费,转正为一条参加记录 + Column("id", String(36), primary_key=True), + Column("token", String(64), nullable=False, unique=True), + Column("activity_id", String(36), ForeignKey("activities.id", ondelete="CASCADE"), nullable=False), + Column("user_id", String(36), ForeignKey("users.id", ondelete="CASCADE"), nullable=False), + Column("expires_at", Integer, nullable=False), + # 0=可用 1=已点击 2=已失效(活动删除等) + Column("used", Integer, nullable=False, default=0), + Column("created_at", Integer, nullable=False), +) +Index("ix_join_links_activity", join_links.c.activity_id) + +TABLES = (users, sessions, email_verifications, activities, participations, join_links) diff --git a/server/security.py b/server/security.py new file mode 100644 index 0000000..78db70c --- /dev/null +++ b/server/security.py @@ -0,0 +1,40 @@ +"""口令散列与登录令牌。只依赖标准库,避免额外依赖。""" + +from __future__ import annotations + +import hashlib +import hmac +import secrets + +ALGORITHM = "pbkdf2_sha256" +ITERATIONS = 240_000 + + +def hash_password(password: str) -> str: + """返回 pbkdf2_sha256$<迭代次数>$<盐hex>$<摘要hex>。""" + salt = secrets.token_bytes(16) + digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, ITERATIONS) + return f"{ALGORITHM}${ITERATIONS}${salt.hex()}${digest.hex()}" + + +def verify_password(password: str, stored: str) -> bool: + try: + algorithm, iterations, salt_hex, digest_hex = stored.split("$") + if algorithm != ALGORITHM: + return False + digest = hashlib.pbkdf2_hmac( + "sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), int(iterations) + ) + except (ValueError, TypeError): + return False + return hmac.compare_digest(digest.hex(), digest_hex) + + +def new_token() -> str: + """会话令牌,43 个字符的 URL 安全随机串。""" + return secrets.token_urlsafe(32) + + +def token_digest(token: str) -> str: + """数据库只保存高熵令牌的摘要,数据库副本不能直接充当登录凭据。""" + return hashlib.sha256(token.encode("utf-8")).hexdigest() diff --git a/start.sh b/start.sh new file mode 100644 index 0000000..26e72e7 --- /dev/null +++ b/start.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# 启动脚本:安装依赖(首次)并启动 WorkLog 服务。 +# 用法:bash start.sh +set -euo pipefail + +PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$PROJECT_DIR" + +PYTHON="${PYTHON:-python}" + +# 依赖未装时自动安装 +if ! "$PYTHON" -c "import fastapi, uvicorn, sqlalchemy, aiosqlite, aiosmtplib, tomllib; from pydantic import field_validator" >/dev/null 2>&1; then + echo "安装依赖..." + "$PYTHON" -m pip install -r requirements.txt +fi + +mkdir -p data +echo "启动 WorkLog:$PYTHON -m server.main" +exec "$PYTHON" -m server.main