refactor: 迁移收尾(管理员2FA)+ 抽取公共工具层,消除 router 间重复

补齐最后缺口:
- POST /api/v1/auth/admin_login/email、/auth/admin_login/verify(管理员 2FA Step2/3),
  复用 auth_routes 的票据表与尝试上限(跨栈共享),签发会话 Cookie

重构(消除约 200 行重复,11 个 router 受益):
- web/request_utils.py:request_data / safe_int / extract_id / cookies / dedup_ids
  原在各 router 各复制一份,现集中
- web/serializers.py:format_credits / user_public / record_req_log
- 各 router 改为导入别名,行为逐字不变

覆盖率:Flask 90 条业务路由全部有 FastAPI 等价端点(含 5 个向后兼容别名)。
验证:pytest 69/69;ruff All checks passed;pyright 0 errors;奇偶 36/36;冒烟 10/10。
This commit is contained in:
snowy-yang committed 2026-09-26 10:20:46 +08:00
1 parent 9df0028195
commit cd0f1f78a3
13 files changed
+274 -339

No files matched your search

+111 -38
View File
@@ -17,7 +17,7 @@
import asyncio
import os
import time
from typing import Annotated, Any
from typing import Annotated
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
@@ -28,7 +28,12 @@ from core import db, repo
from core import session as cs
from web import ratelimit
from web.deps import SiteUser, current_user
from web.request_utils import (
request_data as _request_data,
)
from web.response import error, success
from web.serializers import format_credits as _format_credits
from web.serializers import user_public as _user_public
router = APIRouter()
@@ -36,45 +41,8 @@ SESSION_COOKIE = 'session'
_SESSION_MAX_AGE = 7 * 86400
def _format_credits(count: int) -> str:
if count < 0:
return '不限次数'
if count <= 0:
return '已用完'
return f'{count} 次'
def _user_public(row: dict) -> dict:
return {
'id': row['id'],
'username': row['username'],
'email': row.get('email'),
'role': row['role'],
'duration_seconds': row['duration_seconds'],
'created_at': row.get('created_at'),
'last_login': row.get('last_login'),
'ann_seen': row.get('ann_seen'),
}
async def _request_data(request: Request) -> dict[str, Any]:
data: dict[str, Any] = {}
if request.method == 'GET':
data.update(dict(request.query_params))
return data
try:
body = await request.json()
if isinstance(body, dict):
data.update(body)
except Exception:
pass
if not data:
try:
form = await request.form()
data.update(dict(form.items()))
except Exception:
pass
return data
def _cookie_kwargs() -> dict:
@@ -224,3 +192,108 @@ async def login(request: Request):
}, '登录成功', uid, seq)
except Exception:
return error('登录失败,请稍后重试', 500)
# ============ 管理员两步验证 Step2 / Step3 ============
@router.post('/auth/admin_login/email')
async def admin_login_email(request: Request):
"""管理员 2FA Step2:比对绑定邮箱 → 发送 admin2fa 验证码。"""
import hmac as _hmac
from auth_routes import (
_ADMIN2FA_LAST_SEND,
_ADMIN2FA_SEND_GAP,
_ADMIN_2FA,
_ADMIN_2FA_MAX_ATTEMPTS,
_admin2fa_mask,
_admin2fa_take,
)
data = await _request_data(request)
ip = ratelimit.client_ip(request)
ticket, v = _admin2fa_take(str(data.get('ticket') or ''))
if not v:
return error('登录会话已过期,请重新开始登录', 401, error_code='admin_2fa_expired')
email_input = auth._normalize_email(str(data.get('email') or ''))
# 第二因子比对走常时比较
if (not email_input or not v.get('email')
or not _hmac.compare_digest(email_input, v['email'])):
v['attempts'] += 1
await asyncio.to_thread(auth.add_log, 'fail', v['username'], ip, '管理员登录', '绑定邮箱不匹配')
if v['attempts'] >= _ADMIN_2FA_MAX_ATTEMPTS:
_ADMIN_2FA.pop(ticket, None)
return error('错误次数过多,请重新开始登录')
return error(f'绑定邮箱不正确,还可尝试 {_ADMIN_2FA_MAX_ATTEMPTS - v["attempts"]} 次')
last_send = _ADMIN2FA_LAST_SEND.get(v['username'], 0)
if time.time() - last_send < _ADMIN2FA_SEND_GAP:
return error('验证码发送过于频繁,请 1 分钟后再试')
try:
await asyncio.to_thread(auth.send_verify_code, v['email'], 'admin2fa')
_ADMIN2FA_LAST_SEND[v['username']] = time.time()
await asyncio.to_thread(auth.add_log, 'success', v['username'], ip, '管理员登录',
f'绑定邮箱验证通过,验证码已发送({_admin2fa_mask(v["email"])})')
return success(message='验证码已发送至管理员邮箱,请查收')
except (ValueError, RuntimeError) as e:
return error(str(e))
except Exception:
return error('验证码发送失败,请稍后重试', 500)
@router.post('/auth/admin_login/verify')
async def admin_login_verify(request: Request):
"""管理员 2FA Step3:验证码原子消费 → 建立管理员会话。"""
from auth_routes import (
_ADMIN_2FA,
_ADMIN_2FA_MAX_ATTEMPTS,
_admin2fa_take,
)
data = await _request_data(request)
ip = ratelimit.client_ip(request)
ticket, v = _admin2fa_take(str(data.get('ticket') or ''))
if not v:
return error('登录会话已过期,请重新开始登录', 401, error_code='admin_2fa_expired')
code = str(data.get('code') or '').strip()
if not await asyncio.to_thread(auth.check_verify_code, v['email'], code, 'admin2fa'):
v['attempts'] += 1
if v['attempts'] >= _ADMIN_2FA_MAX_ATTEMPTS:
_ADMIN_2FA.pop(ticket, None)
return error('错误次数过多,请重新开始登录')
await asyncio.to_thread(auth.add_log, 'fail', v['username'], ip, '管理员登录', '验证码错误')
return error('验证码错误或已过期')
_ADMIN_2FA.pop(ticket, None) # 一次性
user = await asyncio.to_thread(auth.get_user_by_id, v['user_id'])
if not user or user['role'] != 'admin':
return error('登录会话已过期,请重新开始登录', 401, error_code='admin_2fa_expired')
keys = user.keys()
status = user['status'] if 'status' in keys else 1
if status == 2:
await asyncio.to_thread(auth.add_log, 'fail', v['username'], ip, '管理员登录', '封禁账号尝试登录')
return error('账号已被封禁,请联系管理员')
if status == 0:
return error('账号已被禁用,请联系管理员')
uid = int(user['id'])
now = int(time.time())
await db.execute('UPDATE users SET last_active=?, last_login=?, '
'login_seq=COALESCE(login_seq,0)+1 WHERE id=?', (now, now, uid))
seq_row = await repo.get_user_by_id(uid)
seq = int((seq_row or {}).get('login_seq') or 1)
banned, _info = await asyncio.to_thread(auth.record_login_location, user, ip)
if banned:
await db.execute('UPDATE users SET login_seq = COALESCE(login_seq, 0) + 1 WHERE id = ?', (uid,))
return error('检测到账号在多个省份异常登录,已自动封禁,请联系管理员')
fresh = await repo.get_user_by_id(uid) or {}
await asyncio.to_thread(auth.add_log, 'success', v['username'], ip, '管理员登录', '两步验证通过')
return _login_response({
'user': _user_public(fresh),
'duration_text': _format_credits(int(fresh.get('duration_seconds') or 0)),
'redirect': 'admin',
}, '登录成功', uid, seq)