refactor: login 端点拆解(90 行 / 圈 26 / 嵌套 2 → 39 行 / 圈 10 / 嵌套 1)

为什么:登录是全部拒绝路径最密的端点(超长密码/锁定/密码错/封禁/
禁用/管理员无邮箱/异地封禁七道闸),90 行单函数把「身份解析、锁定
计数、状态闸、2FA 转票据、会话建立」五件事揉在一个 try 里,改任何
一道闸都要在嵌套分支里核对上下文。

拆出五个成员(顺序 = 原执行顺序,逐条语义对应):
- _resolve_login_identity:邮箱→账号解析 + 锁定键(保留两处判定
  差异:锁定键用真值判断,verify_name 用 is not None——历史口径,
  契约测试分别钉住)
- _allow_login_attempt:锁定闸 + 一次性审计日志(锁定周期内不重复落)
- _check_account_status:封禁(原因落日志)/禁用,通过返回 None
- _admin_two_factor_response:2FA 转票据,未绑定邮箱 fail-closed
- _user_session_response:login_seq 顶号 + 异地多省封禁闸(封禁时
  再递增一次顶掉在途会话)+ Cookie 签发

先写测试后动代码:新增 tests/test_login_flow.py 9 例,在未改动实现上
一次跑绿,覆盖此前零测试的路径——超长密码不碰 PBKDF2(monkeypatch
verify_login 断言不被调用)、邮箱登录按归一化地址锁定、锁定日志幂等、
封禁/禁用文案、管理员 fail-closed、异地封禁双递增、非预期异常 500。

门禁:ruff 全过 · pyright 0/0 · pytest 348 passed(339→348)。
This commit is contained in:
snowy-yang committed 2026-09-27 10:13:36 +08:00
1 parent 5ad2152acc
commit f0de0b65b1
2 files changed
+254 -62

No files matched your search

+97 -62
View File
@@ -101,18 +101,99 @@ async def ann_seen(user: Annotated[SiteUser | None, Depends(current_user)]):
return success()
@router.post('/auth/login')
async def login(request: Request):
"""登录:密码校验(含邮箱登录)、失败锁定、管理员两步验证转票据。"""
async def _resolve_login_identity(username: str) -> tuple:
"""身份解析:含 @ 按归一化邮箱解析真实账号。
返回 (邮箱命中的用户或 None, 锁定计数键)。邮箱登录的锁定键用
真实用户名(命中时)或归一化邮箱(未命中时),防大小写变体绕过。
"""
if '@' not in username:
return None, username
iuser = await asyncio.to_thread(auth.get_user_by_email, username)
lock_name = iuser['username'] if iuser else (auth._normalize_email(username) or username)
return iuser, lock_name
async def _allow_login_attempt(lock_name: str, ip: str) -> bool:
"""失败锁定闸:允许尝试返回 True;锁定时落一条一次性审计日志并返回 False。"""
from web.auth_state import (
_login_fail_check,
_login_fail_locked_log_once,
)
if _login_fail_check(lock_name):
return True
if _login_fail_locked_log_once(lock_name):
await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip,
'登录', '失败次数过多,临时锁定')
return False
async def _check_account_status(user, lock_name: str, ip: str):
"""账号状态闸:封禁(原因落日志)/禁用;通过返回 None。"""
keys = user.keys()
status = user['status'] if 'status' in keys else 1
if status == 2:
reason = user['ban_reason'] if 'ban_reason' in keys else ''
await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip,
'登录', f'封禁账号尝试登录: {reason}')
return error('账号已被封禁' + (f':{reason}' if reason else '') + ',请联系管理员')
if status == 0:
return error('账号已被禁用,请联系管理员')
return None
async def _admin_two_factor_response(user, lock_name: str, ip: str) -> JSONResponse:
"""管理员登录一律转两步验证通道(密码正确才签发票据;未绑定邮箱 fail-closed)。"""
from web.auth_state import (
_admin2fa_issue,
_admin2fa_mask,
_login_fail_check,
_login_fail_clear,
_login_fail_locked_log_once,
_login_fail_record,
)
admin_email = user['email'] if 'email' in user.keys() else ''
if not admin_email:
await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip,
'管理员登录', '未绑定邮箱,两步验证不可用')
return error('管理员账号未绑定邮箱,请联系管理员先完成绑定')
ticket = _admin2fa_issue(user)
await asyncio.to_thread(auth.add_log, 'success', lock_name, ip,
'管理员登录', '密码验证通过,待邮箱验证')
return success({'ticket': ticket, 'email_masked': _admin2fa_mask(admin_email),
'username': user['username'], 'admin_2fa': True},
'密码验证通过,请完成邮箱验证')
async def _user_session_response(user, ip: str) -> JSONResponse:
"""普通用户建会话:login_seq 原子递增顶号 → 异地多省封禁闸 → 签发 Cookie。"""
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 {}
return _login_response({
'user': _user_public(fresh),
'duration_text': _format_credits(int(fresh.get('duration_seconds') or 0)),
'redirect': 'admin' if fresh.get('role') == 'admin' else 'user',
}, '登录成功', uid, seq)
@router.post('/auth/login')
async def login(request: Request):
"""登录:密码校验(含邮箱登录)、失败锁定、管理员两步验证转票据。
分支顺序:超长密码直拒 → 身份解析 → 失败锁定 → 密码校验 →
状态闸(封禁/禁用)→ 管理员转 2FA → 普通用户建会话(含异地封禁)。
"""
data = await _request_data(request)
username = str(data.get('username') or '').strip()
password = str(data.get('password') or '')
@@ -123,73 +204,27 @@ async def login(request: Request):
return error('用户名或密码错误')
try:
# 邮箱登录:含 @ 按归一化邮箱解析真实账号;锁定 key 用真实用户名
if '@' in username:
iuser = await asyncio.to_thread(auth.get_user_by_email, username)
lock_name = iuser['username'] if iuser else (auth._normalize_email(username) or username)
else:
iuser = None
lock_name = username
if not _login_fail_check(lock_name):
if _login_fail_locked_log_once(lock_name):
await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip,
'登录', '失败次数过多,临时锁定')
iuser, lock_name = await _resolve_login_identity(username)
if not await _allow_login_attempt(lock_name, ip):
return error('尝试过于频繁,该账号已临时锁定,请 10 分钟后再试')
verify_name = iuser['username'] if iuser is not None else username
user = await asyncio.to_thread(auth.verify_login, verify_name, password)
if not user:
from web.auth_state import _login_fail_record
_login_fail_record(lock_name)
return error('用户名或密码错误')
keys = user.keys()
status = user['status'] if 'status' in keys else 1
if status == 2:
reason = user['ban_reason'] if 'ban_reason' in keys else ''
await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip,
'登录', f'封禁账号尝试登录: {reason}')
return error('账号已被封禁' + (f':{reason}' if reason else '') + ',请联系管理员')
if status == 0:
return error('账号已被禁用,请联系管理员')
status_err = await _check_account_status(user, lock_name, ip)
if status_err is not None:
return status_err
from web.auth_state import _login_fail_clear
_login_fail_clear(lock_name)
if user['role'] == 'admin':
# 管理员一律转两步验证通道(密码正确才签发票据;未绑定邮箱 fail-closed)
admin_email = user['email'] if 'email' in keys else ''
if not admin_email:
await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip,
'管理员登录', '未绑定邮箱,两步验证不可用')
return error('管理员账号未绑定邮箱,请联系管理员先完成绑定')
ticket = _admin2fa_issue(user)
await asyncio.to_thread(auth.add_log, 'success', lock_name, ip,
'管理员登录', '密码验证通过,待邮箱验证')
return success({'ticket': ticket, 'email_masked': _admin2fa_mask(admin_email),
'username': user['username'], 'admin_2fa': True},
'密码验证通过,请完成邮箱验证')
# 普通用户:建立会话(原子递增 login_seq 顶号)
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 {}
return _login_response({
'user': _user_public(fresh),
'duration_text': _format_credits(int(fresh.get('duration_seconds') or 0)),
'redirect': 'admin' if fresh.get('role') == 'admin' else 'user',
}, '登录成功', uid, seq)
return await _admin_two_factor_response(user, lock_name, ip)
return await _user_session_response(user, ip)
except Exception:
return error('登录失败,请稍后重试', 500)