WorkLog 全量合并:密码登录体系、每日自动备份、发信日志、活动邮件通知一键参加
- 认证:注册设密码(双次确认,>=10 位)、密码/验证码双模式登录、邮箱验证码找回重置密码 - 备份:服务内置每天 23:00 自动备份到 data/backups/(默认保留 14 份),backup_db.py 支持手动/crontab - 发信日志:logs/mail-YYYYMM.log 记录每次发信成败与失败原因(535 认证失败/断连细分),按月滚动保留 6 个月 - 通知:发起活动群发邮件(参与不发),邮件内一键参加(一次性令牌、7 天有效、私密活动不群发) - 前端:报错细分(字段/类型/状态码全中文)、验证码按钮 60 秒防连点 - 部署:Dockerfile + entrypoint(seed 机制)、限流/唯一索引/令牌摘要等安全加固 - 工具:repair_db/clear_db 的 SQL 全部常量化,无动态拼接 - 测试:43 项全覆盖(注册/登录/活动/通知/备份/日志/安全)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""WorkLog 活动记录网站后端包。"""
|
||||
@@ -0,0 +1,94 @@
|
||||
"""SQLite 定时备份:每天固定时间用 backup API 做一致快照,保留最近 N 份。
|
||||
|
||||
备份写到数据库同目录的 backups/ 子目录;WAL 模式下 backup API 会
|
||||
自动合并 -wal 内容,服务运行中执行也安全。全部逻辑与 FastAPI 无关,
|
||||
可被 backup_db.py 命令行脚本复用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sqlite3
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _backup_once_sync(db_path: Path, backup_dir: Path, keep: int) -> Path:
|
||||
"""同步执行一次备份并按保留数量清理旧备份,返回备份文件路径。"""
|
||||
backup_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
dest = backup_dir / f"{db_path.stem}-{stamp}{db_path.suffix}"
|
||||
n = 1
|
||||
while dest.exists(): # 同一秒备份多次时加序号,不覆盖上一份
|
||||
n += 1
|
||||
dest = backup_dir / f"{db_path.stem}-{stamp}-{n}{db_path.suffix}"
|
||||
|
||||
# 只读连接 + backup API:对运行中的 WAL 库安全,快照包含未合并的 -wal 数据
|
||||
src = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True)
|
||||
try:
|
||||
dest_conn = sqlite3.connect(str(dest))
|
||||
try:
|
||||
with dest_conn:
|
||||
src.backup(dest_conn)
|
||||
finally:
|
||||
dest_conn.close()
|
||||
finally:
|
||||
src.close()
|
||||
|
||||
_prune(backup_dir, db_path, keep)
|
||||
return dest
|
||||
|
||||
|
||||
def _prune(backup_dir: Path, db_path: Path, keep: int) -> None:
|
||||
"""只清理本脚本命名规则的旧备份(<库名>-<时间戳>.db),误伤其他文件。"""
|
||||
if keep <= 0:
|
||||
return
|
||||
pattern = f"{db_path.stem}-*{db_path.suffix}"
|
||||
backups = sorted(backup_dir.glob(pattern), reverse=True)
|
||||
for old in backups[keep:]:
|
||||
try:
|
||||
old.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
async def backup_once(db_path: Path | str, backup_dir: Path | str | None = None, keep: int = 14) -> Path:
|
||||
"""异步执行一次备份:文件操作放到线程里,不阻塞事件循环。"""
|
||||
db_path = Path(db_path)
|
||||
directory = Path(backup_dir) if backup_dir else db_path.parent / "backups"
|
||||
return await asyncio.to_thread(_backup_once_sync, db_path, directory, keep)
|
||||
|
||||
|
||||
def seconds_until(hour: int, minute: int, now: datetime | None = None) -> float:
|
||||
"""距离下一个每天固定时刻的秒数;当前时刻已过今天的目标点则算明天。"""
|
||||
now = now or datetime.now()
|
||||
target = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
||||
if target <= now:
|
||||
target += timedelta(days=1)
|
||||
return (target - now).total_seconds()
|
||||
|
||||
|
||||
def parse_time(text: str) -> tuple[int, int]:
|
||||
""""23:00" -> (23, 0);非法输入回退 23:00。"""
|
||||
try:
|
||||
hour, minute = text.strip().split(":", 1)
|
||||
hour, minute = int(hour), int(minute)
|
||||
if 0 <= hour <= 23 and 0 <= minute <= 59:
|
||||
return hour, minute
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
return 23, 0
|
||||
|
||||
|
||||
async def backup_loop(db_path: Path | str, hour: int, minute: int, keep: int = 14) -> None:
|
||||
"""每天 hour:minute 备份一次,直到被 cancel。"""
|
||||
while True:
|
||||
delay = seconds_until(hour, minute)
|
||||
print(f"[backup] 下次自动备份在 {hour:02d}:{minute:02d}(约 {delay / 3600:.1f} 小时后)", flush=True)
|
||||
await asyncio.sleep(delay + 5) # +5 秒越过整点边界
|
||||
try:
|
||||
path = await backup_once(db_path, keep=keep)
|
||||
print(f"[backup] 自动备份完成:{path} ({path.stat().st_size / 1024:.0f} KB)", flush=True)
|
||||
except Exception as exc: # 单次失败不影响服务,明天继续
|
||||
print(f"[backup] 自动备份失败:{exc}", flush=True)
|
||||
await asyncio.sleep(30) # 跨过这一分钟,防止重复触发
|
||||
@@ -0,0 +1,51 @@
|
||||
"""发信日志:所有 SMTP 发送成败都记录到 logs/mail.log,便于排查"邮件发不出去"。
|
||||
|
||||
每行格式:2026-10-29 18:30:12 | OK|FAIL|SKIP | 收件人 | 主题 | 详情
|
||||
- OK 发送成功
|
||||
- FAIL 发送失败(详情为异常类型 + 完整信息)
|
||||
- SKIP 未配置 SMTP(开发模式),根本没尝试发
|
||||
日志文件按月滚动(mail-YYYYMM.log),保留最近 6 个月,全部失败也不影响业务流程。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_DIR = Path(__file__).resolve().parent.parent
|
||||
LOG_DIR = Path(__file__).resolve().parent.parent / "logs"
|
||||
|
||||
_LOCK = threading.Lock()
|
||||
KEEP_MONTHS = 6
|
||||
|
||||
|
||||
def log_mail(result: str, to: str, subject: str, detail: str = "") -> None:
|
||||
"""记一条发信日志。线程安全;日志写不进去只打印到控制台,绝不抛错。"""
|
||||
line = (
|
||||
f"{datetime.now():%Y-%m-%d %H:%M:%S} | {result:<4} | {to} | {subject}"
|
||||
+ (f" | {detail}" if detail else "")
|
||||
)
|
||||
try:
|
||||
with _LOCK:
|
||||
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
path = LOG_DIR / f"mail-{datetime.now():%Y%m}.log"
|
||||
with path.open("a", encoding="utf-8") as fh:
|
||||
fh.write(line + "\n")
|
||||
_prune_old()
|
||||
except OSError as exc:
|
||||
print(f"[maillog] 写日志失败:{exc}", flush=True)
|
||||
print(f"[mail] {line}", flush=True)
|
||||
|
||||
|
||||
def _prune_old() -> None:
|
||||
"""删除 KEEP_MONTHS 个月前的滚动日志。"""
|
||||
cutoff = time.strftime("%Y%m", time.localtime(time.time() - KEEP_MONTHS * 31 * 86400))
|
||||
for old in LOG_DIR.glob("mail-*.log"):
|
||||
stamp = old.stem.removeprefix("mail-")
|
||||
if stamp < cutoff:
|
||||
try:
|
||||
old.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
+1575
File diff suppressed because it is too large
Load Diff
@@ -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)
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user