This repository has been archived on 2026-10-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
NeteaseUrl/web/routers/register.py
T
snowy-yang 22b263f547 refactor: SMTP 发信改 aiosmtplib,最后一个阻塞网络调用从 to_thread 里取出来
为什么:smtplib 是同步栈,原先靠 asyncio.to_thread 卸载——线程池里躺着的仍是一次
完整的 TCP + TLS 握手加多轮 SMTP 交互,属于「同步网络 IO 藏在 to_thread 里」:既
占着线程,也不产生并发收益。这是本系列最后一条此类遗留(aria2p 那条已在 C2 清零)。

改动:
- auth_system/mail.py:_smtp_connect / _smtp_send 两个同步函数合成一个原生异步
  _smtp_send,底层换 aiosmtplib.SMTP。TLS 口径与原实现一一对应:465 用 use_tls
  (隐式 TLS),其余端口用 start_tls(显式 STARTTLS,先握手再 LOGIN);两条路都传
  显式构造的 ssl.create_default_context(),不依赖运行时默认校验口径。finally 里
  quit 失败只吞连接关闭错误,sendmail 的真实异常原样上抛——send_verify_code 依赖
  它决定「不写库、不烧 24h 额度」。
- auth_system/mail.py:send_email 改直接 await;移除 import asyncio / import smtplib。
- auth_system/__init__.py:撤掉 _smtp_connect 的再导出——它是同步时代的辅助函数,
  全仓无消费方,新实现里也不存在对应物。
- web/routers/register.py:更新过时的模块说明(原文仍写「smtplib 阻塞发送已卸载」)。
- pyproject.toml / uv.lock:新增 aiosmtplib>=5.1.3,<6.0。
- tests/test_mail_smtp.py(新增 5 条):SMTP 路径此前零覆盖,而「端口 → TLS 方式」
  的映射属「授权码会不会明文过网」级别的差异,一旦被改反不会有任何地方报警。用假
  SMTP 替身记录构造参数与调用序、全程不触网:587 必须 start_tls 且 LOGIN 在 connect
  之后、465 必须 use_tls 且不得再叠 STARTTLS、端口缺省回落 587、quit 失败不掩盖结果、
  sendmail 失败原样上抛且仍关连接。

验证:
- uv run ruff check .  → All checks passed!
- uv run pyright       → 0 errors, 0 warnings, 0 informations
  (aiosmtplib 自带 py.typed,故对它的调用是有效类型校验;另用 inspect 逐一核对了
   5.1.3 的 SMTP / connect / login / sendmail / quit 参数名)
- uv run pytest        → 397 项,0 失败 / 0 error / 0 skipped(C3 后 392,新增 5)
- data/site.db sha256 前后一致(a19f5dbf…6487),无 -wal/-shm 残留
2026-09-29 15:28:13 +08:00

255 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""注册 / 找回密码 / 卡密 / 验证码。
端点:
- POST /api/v1/auth/send_code ↔ Flask /auth/send_code
- POST /api/v1/auth/register ↔ Flask /auth/register
- POST /api/v1/auth/trial ↔ Flask /auth/trial
- POST /api/v1/auth/redeem ↔ Flask /auth/redeem
- POST /api/v1/auth/forgot_password ↔ Flask /auth/forgot_password
说明:
- auth_system 已迁移为**原生异步**(aiosqlite / aiosmtplib),此处直接 await,不再经
asyncio.to_thread 桥接;仅 PBKDF2 这类 CPU 密集且释放 GIL 的活仍在内部卸载到线程。
- 发码 IP 限流复用 web.auth_state 的模块级状态 `_SEND_CODE_IP`。
- 失败锁定/验证码消费等安全口径逐字保留。
"""
import os
import sqlite3
import time
from typing import Annotated
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
import auth_system as auth
import web.deps as deps
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 user_public as _user_public
router = APIRouter()
SESSION_COOKIE = cs.COOKIE_NAME
_SESSION_MAX_AGE = cs.SESSION_MAX_AGE
async def _login_cookie_response(payload: dict, message: str, uid: int, seq: int,
secure: bool) -> JSONResponse:
resp = JSONResponse(content={'status': 200, 'success': True, 'message': message, 'data': payload})
cookie = cs.dumps(await deps.secret_key(), {'site_uid': uid, 'site_uid_seq': seq,
'site_uid_ts': int(time.time())})
resp.set_cookie(SESSION_COOKIE, cookie, max_age=_SESSION_MAX_AGE, httponly=True,
samesite='lax', path='/', secure=secure)
return resp
async def _safe_register_credits() -> int:
try:
credits = int(await repo.get_setting('register_credits', str(auth.DEFAULT_REGISTER_CREDITS)) or 0)
except (TypeError, ValueError):
return auth.DEFAULT_REGISTER_CREDITS
return max(0, credits)
@router.post('/auth/send_code')
async def send_code(request: Request):
"""发送邮箱验证码(注册/找回用途隔离)。"""
from web.auth_state import _send_code_ip_check
ip = ratelimit.client_ip(request)
if not _send_code_ip_check(ip):
return error('验证码请求过于频繁,请稍后再试')
data = await _request_data(request)
email = str(data.get('email') or '').strip()
purpose = str(data.get('purpose') or 'register').strip()
if purpose not in ('register', 'reset'):
return error('验证码用途不正确')
try:
await auth.send_verify_code(email, purpose)
return success(message='验证码已发送,请查收邮箱')
except (ValueError, RuntimeError) as e:
return error(str(e))
except Exception:
return error('验证码发送失败,请稍后重试', 500)
@router.post('/auth/trial')
async def trial():
"""试用已并入注册:注册即送 N 次。"""
return error(f'注册即送 {await _safe_register_credits()} 次免费下载次数,请直接注册账号')
@router.post('/auth/redeem')
async def redeem(user: Annotated[SiteUser | None, Depends(current_user)], request: Request):
"""卡密充值。"""
if user is None:
return error('请先登录', 401, error_code='unauthorized')
ip = ratelimit.client_ip(request)
data = await _request_data(request)
code = str(data.get('code') or '')
try:
credits, remaining = await auth.redeem_card(code, user.username)
await auth.add_log('success', user.username, ip, '卡密充值',
f'{code[:4]}**** · +{credits} 次')
return success({'credits': credits, 'duration_seconds': remaining,
'duration_text': auth.format_credits(remaining)},
f'充值成功,+{credits} 次')
except ValueError as e:
await auth.add_log('fail', user.username, ip, '卡密充值', str(e))
return error(str(e))
except Exception:
return error('充值失败,请稍后重试', 500)
@router.post('/auth/forgot_password')
async def forgot_password(request: Request):
"""自助找回密码:邮箱验证码 → 重置密码并踢下全部会话(响应防枚举)。"""
data = await _request_data(request)
email = auth._normalize_email(str(data.get('email') or ''))
code = str(data.get('code') or '').strip()
newpwd = str(data.get('password') or '')
if len(newpwd) < 8 or len(newpwd) > 128:
return error('新密码长度需在 8-128 位之间')
if not email:
return error('缺少邮箱')
try:
if not await auth.check_verify_code(email, code, 'reset'):
return error('邮箱验证码错误或已过期')
user = await auth.get_user_by_email(email)
if not user:
return error('邮箱验证码错误或已过期')
if user['role'] == 'admin':
# 管理员不走自助找回(2FA 保护,统一防枚举文案)
return error('邮箱验证码错误或已过期')
await auth.reset_password(user['id'], newpwd)
await auth.add_log('success', user['username'],
ratelimit.client_ip(request), '自助找回密码', '邮箱验证码重置')
return success(message='密码已重置,请使用新密码登录(所有设备已下线)')
except Exception:
return error('重置失败,请稍后重试', 500)
def _validate_registration_input(username: str, password: str, email: str,
agree: str) -> str | None:
"""注册入参四道闸,按序返回第一条错误文案(None = 全部通过)。"""
from web.auth_state import re_username_ok
if agree.strip() != '1':
return '请先阅读并同意《用户协议》与《隐私政策》'
if not (3 <= len(username) <= 20 and re_username_ok(username)):
return '用户名需 3-20 位,仅支持中文、字母、数字、下划线,且不能纯下划线'
if len(password) < 8 or len(password) > 128:
return '密码长度需在 8-128 位之间'
if len(email) > 254:
return '邮箱格式不正确'
return None
async def _reject_registration(message: str, *, email: str, code: str, ttl: int,
username: str = '', ip: str = '',
log_detail: str | None = None) -> JSONResponse:
"""注册流程后续步骤失败的统一拒绝:还原已消费的验证码(可选失败日志)。
验证码在 check_verify_code 里已被 DELETE 原子消费,凡走到建号/查重/防刷
之后才失败的路径都必须还原,否则用户被迫重新收码。
"""
await auth.restore_verify_code(email, code, ttl, 'register')
if log_detail:
await auth.add_log('fail', username, ip, '注册', log_detail)
return error(message)
async def _register_credits(device_used: bool) -> int:
"""注册赠送次数:同设备重复注册账号照建,但不再赠送。"""
if device_used:
return 0
return await _safe_register_credits()
async def _issue_registration_session(user, credits: int, username: str,
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))
fresh = await repo.get_user_by_id(uid) or {}
seq = int(fresh.get('login_seq') or 1)
credits = min(credits, max(0, int(fresh.get('duration_seconds') or 0)))
await auth.add_log('success', username, ip, '注册账号',
f'赠送 {credits} 次' if credits else '未赠送次数')
secure = os.environ.get('ENABLE_SECURE_COOKIE', '').strip().lower() in ('1', 'true', 'yes')
return await _login_cookie_response({
'user': _user_public(fresh),
'duration_text': auth.format_credits(int(fresh.get('duration_seconds') or 0)),
'redirect': 'admin' if fresh.get('role') == 'admin' else 'user',
}, '注册成功' + (f',已赠送 {credits} 次下载次数' if credits else ''), uid, seq, secure)
@router.post('/auth/register')
async def register(request: Request):
"""注册:入参校验 → 验证码 → 查重/防刷 → 建号 → 会话。
五条「建号前失败」路径共用 _reject_registration(还原验证码),
顺序与历史实现逐条对应:用户名重名 / 邮箱重名 / IP 超限(+日志)/
建号 IntegrityError / 建号 ValueError(+日志)/ 读回 None(+日志)。
"""
data = await _request_data(request)
username = str(data.get('username') or '').strip()
password = str(data.get('password') or '')
email = auth._normalize_email(str(data.get('email') or ''))
code = str(data.get('code') or '').strip()
device_id = str(data.get('device_id') or '').strip()[:64]
ip = ratelimit.client_ip(request)
bad_input = _validate_registration_input(
username, password, email, str(data.get('agree') or ''))
if bad_input:
return error(bad_input)
try:
code_ttl = await auth.check_verify_code(email, code, 'register')
if not code_ttl:
return error('邮箱验证码错误或已过期')
rej = {'email': email, 'code': code, 'ttl': code_ttl}
if await auth.get_user_by_name(username):
return await _reject_registration('用户名已被注册', **rej)
if email and await auth.get_user_by_email(email):
return await _reject_registration('该邮箱已被注册,请更换邮箱或联系管理员', **rej)
device_used_flag = bool(device_id) and await auth.device_used(device_id)
if ip and await auth.register_ip_exceeded(ip):
return await _reject_registration(
'当前网络注册过于频繁,请 24 小时后再试或联系管理员',
username=username, ip=ip, log_detail='同 IP 24h 注册次数超限', **rej)
credits = await _register_credits(device_used_flag)
try:
user = await auth.create_user(username, password, email=email, credits=credits,
guard=auth.RegistrationGuard(
device_id=device_id, ip=ip,
ua=str(request.headers.get('user-agent') or ''),
ip_limit=3, device_once=True))
except sqlite3.IntegrityError:
return await _reject_registration('用户名或邮箱已被注册,请换一个再试', **rej)
except ValueError as e:
return await _reject_registration(str(e), username=username, ip=ip,
log_detail=str(e), **rej)
# 建号事务已提交却读不回(并发删除/库损坏):按注册失败处理
if user is None:
return await _reject_registration('注册失败,请稍后重试', username=username,
ip=ip, log_detail='建号后读取用户失败', **rej)
return await _issue_registration_session(user, credits, username, ip)
except Exception:
return error('注册失败,请稍后重试', 500)