Archived
feat(routes): 迁移认证端点(login/logout/heartbeat/ann_seen)
- web/routers/auth.py
· login:邮箱/用户名登录、超长密码短路、失败锁定、封禁/禁用分支、
管理员转 2FA 票据;成功签发 core.session 会话 Cookie(与 Flask 同格式)
· logout:递增 login_seq 顶号 + 删 Cookie
· heartbeat:次数校验(401/expired 语义同 Flask)
· ann_seen:记录已读公告版本
· 失败锁定与 2FA 票据表复用 auth_routes 模块级状态(跨栈共享,防绕锁定)
· PBKDF2 与库操作走 asyncio.to_thread,不阻塞事件循环
测试:tests/test_auth_routes.py 5 项,全部使用**沙箱库**(pytest tmp_path +
monkeypatch auth_system/core.db 路径),不触碰生产 data/site.db。
全套:pytest 56/56;ruff All checks passed;pyright 0 errors;奇偶校验 28/28。
This commit is contained in:
1 parent
18c77296c2
commit
91c032a1c3
3 files changed
+339
No files matched your search
@@ -0,0 +1,112 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""登录/会话端点测试(沙箱库,不触碰生产 data/site.db)。
|
||||||
|
|
||||||
|
覆盖:密码错误、正常用户登录签发可用 Cookie、管理员转 2FA 票据、
|
||||||
|
退出登录递增 login_seq、heartbeat 次数校验。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
import auth_system as auth
|
||||||
|
import core.db as db
|
||||||
|
|
||||||
|
SECRET = 'auth-test-secret'
|
||||||
|
USER_PW = 'UserPass123'
|
||||||
|
ADMIN_PW = 'AdminPass123'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def app_env(tmp_path, monkeypatch):
|
||||||
|
"""沙箱站点库 + 独立密钥,隔离生产数据。"""
|
||||||
|
db_path = tmp_path / 'site.db'
|
||||||
|
monkeypatch.setattr(auth, 'DATA_DIR', tmp_path)
|
||||||
|
monkeypatch.setattr(auth, 'DB_PATH', db_path)
|
||||||
|
monkeypatch.setattr(auth, 'BACKUP_DIR', tmp_path / 'backups')
|
||||||
|
monkeypatch.setattr(auth, 'SECRET_KEY_PATH', tmp_path / 'secret.key')
|
||||||
|
monkeypatch.setattr(db, 'DATA_DIR', tmp_path)
|
||||||
|
monkeypatch.setattr(db, 'DB_PATH', db_path)
|
||||||
|
auth.init_db()
|
||||||
|
|
||||||
|
conn = auth.get_conn()
|
||||||
|
conn.execute('INSERT INTO users (username, password_hash, salt, role, duration_seconds, '
|
||||||
|
'status, login_seq, created_at) VALUES (?,?,?,?,?,1,0,?)',
|
||||||
|
('normaluser', auth._hash_new(USER_PW), '', 'user', 97, 1730000000))
|
||||||
|
conn.execute('INSERT INTO users (username, password_hash, salt, role, duration_seconds, '
|
||||||
|
'status, login_seq, created_at, email) VALUES (?,?,?,?,?,1,0,?,?)',
|
||||||
|
('bossuser', auth._hash_new(ADMIN_PW), '', 'admin', -1, 1730000000,
|
||||||
|
'boss@example.com'))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
monkeypatch.setattr('web.deps.secret_key', lambda: SECRET)
|
||||||
|
monkeypatch.setattr('web.routers.auth.secret_key', lambda: SECRET)
|
||||||
|
|
||||||
|
# 清空登录失败锁定/2FA 的模块级内存态,避免测试间串扰
|
||||||
|
import auth_routes
|
||||||
|
auth_routes._LOGIN_FAILS.clear()
|
||||||
|
auth_routes._LOGIN_FAIL_LOGGED.clear()
|
||||||
|
auth_routes._ADMIN_2FA.clear()
|
||||||
|
|
||||||
|
from web.app import create_app
|
||||||
|
return TestClient(create_app())
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrong_password(app_env):
|
||||||
|
r = app_env.post('/api/v1/auth/login', json={'username': 'normaluser', 'password': 'nope'})
|
||||||
|
assert r.status_code == 400
|
||||||
|
assert r.json()['success'] is False
|
||||||
|
assert 'session' not in r.cookies
|
||||||
|
|
||||||
|
|
||||||
|
def test_user_login_issues_working_cookie(app_env):
|
||||||
|
r = app_env.post('/api/v1/auth/login', json={'username': 'normaluser', 'password': USER_PW})
|
||||||
|
assert r.status_code == 200
|
||||||
|
body = r.json()
|
||||||
|
assert body['success'] is True
|
||||||
|
assert body['data']['redirect'] == 'user'
|
||||||
|
assert 'session' in r.cookies
|
||||||
|
|
||||||
|
# 用签发的 Cookie 访问受保护端点,应放行
|
||||||
|
r2 = app_env.post('/api/v1/auth/heartbeat', json={})
|
||||||
|
assert r2.status_code == 200
|
||||||
|
assert r2.json()['data']['duration_text'] == '97 次'
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_login_returns_2fa_ticket(app_env):
|
||||||
|
r = app_env.post('/api/v1/auth/login', json={'username': 'bossuser', 'password': ADMIN_PW})
|
||||||
|
assert r.status_code == 200
|
||||||
|
data = r.json()['data']
|
||||||
|
assert data['admin_2fa'] is True
|
||||||
|
assert data['ticket']
|
||||||
|
assert 'session' not in r.cookies # 管理员不在此建立会话
|
||||||
|
|
||||||
|
|
||||||
|
def test_logout_bumps_login_seq_and_clears(app_env):
|
||||||
|
app_env.post('/api/v1/auth/login', json={'username': 'normaluser', 'password': USER_PW})
|
||||||
|
conn = auth.get_conn()
|
||||||
|
seq_before = conn.execute(
|
||||||
|
"SELECT login_seq FROM users WHERE username='normaluser'").fetchone()[0]
|
||||||
|
conn.close()
|
||||||
|
r = app_env.post('/api/v1/auth/logout', json={})
|
||||||
|
assert r.status_code == 200
|
||||||
|
conn = auth.get_conn()
|
||||||
|
seq_after = conn.execute(
|
||||||
|
"SELECT login_seq FROM users WHERE username='normaluser'").fetchone()[0]
|
||||||
|
conn.close()
|
||||||
|
assert seq_after == seq_before + 1
|
||||||
|
# 旧 Cookie 失效
|
||||||
|
r2 = app_env.post('/api/v1/auth/heartbeat', json={})
|
||||||
|
assert r2.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_heartbeat_expired_credits(app_env):
|
||||||
|
conn = auth.get_conn()
|
||||||
|
conn.execute("UPDATE users SET duration_seconds=0 WHERE username='normaluser'")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
r = app_env.post('/api/v1/auth/login', json={'username': 'normaluser', 'password': USER_PW})
|
||||||
|
assert r.status_code == 200
|
||||||
|
r2 = app_env.post('/api/v1/auth/heartbeat', json={})
|
||||||
|
assert r2.status_code == 401
|
||||||
|
assert r2.json().get('error_code') == 'expired'
|
||||||
@@ -24,6 +24,7 @@ from core.security import init_secret_key
|
|||||||
from web.errors import install_error_handlers
|
from web.errors import install_error_handlers
|
||||||
from web.middleware import ResponseHygieneMiddleware
|
from web.middleware import ResponseHygieneMiddleware
|
||||||
from web.routers import account as account_router
|
from web.routers import account as account_router
|
||||||
|
from web.routers import auth as auth_router
|
||||||
from web.routers import auth_status as auth_status_router
|
from web.routers import auth_status as auth_status_router
|
||||||
from web.routers import delivery as delivery_router
|
from web.routers import delivery as delivery_router
|
||||||
from web.routers import index as index_router
|
from web.routers import index as index_router
|
||||||
@@ -89,6 +90,7 @@ def create_app(serve_flask_fallback: bool = False) -> FastAPI:
|
|||||||
app.include_router(delivery_router.router, prefix='/api/v1', tags=['delivery'])
|
app.include_router(delivery_router.router, prefix='/api/v1', tags=['delivery'])
|
||||||
app.include_router(stream_router.router, prefix='/api/v1', tags=['stream'])
|
app.include_router(stream_router.router, prefix='/api/v1', tags=['stream'])
|
||||||
app.include_router(auth_status_router.router, prefix='/api/v1', tags=['auth'])
|
app.include_router(auth_status_router.router, prefix='/api/v1', tags=['auth'])
|
||||||
|
app.include_router(auth_router.router, prefix='/api/v1', tags=['auth'])
|
||||||
# 首页与静态资源(迁移完成形态;fallback 模式下同路径也能由 Flask 提供)
|
# 首页与静态资源(迁移完成形态;fallback 模式下同路径也能由 Flask 提供)
|
||||||
app.include_router(index_router.router, tags=['index'])
|
app.include_router(index_router.router, tags=['index'])
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,225 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""认证操作端点(FastAPI 栈)——与 Flask 侧同名端点响应契约逐字段对齐。
|
||||||
|
|
||||||
|
已迁移:
|
||||||
|
- POST /api/v1/auth/logout ↔ Flask /auth/logout(顶号:递增 login_seq + 删 Cookie)
|
||||||
|
- POST /api/v1/auth/heartbeat ↔ Flask /auth/heartbeat
|
||||||
|
- POST /api/v1/auth/ann_seen ↔ Flask /auth/ann_seen
|
||||||
|
- POST /api/v1/auth/login ↔ Flask /auth/login(密码校验 + 失败锁定 + 管理员 2FA 转票据)
|
||||||
|
|
||||||
|
设计:
|
||||||
|
- 登录失败锁定与管理员 2FA 票据表**复用 auth_routes 的模块级状态**,两栈共享同一份
|
||||||
|
计数/票据,避免「换个框架打就绕过锁定」。
|
||||||
|
- 密码校验(PBKDF2,10 万次迭代,CPU 密集)与库操作经 asyncio.to_thread 执行,
|
||||||
|
不阻塞事件循环。
|
||||||
|
- 会话 Cookie 由 core.session 签发(与 Flask 同格式同密钥),删 Cookie 亦同口径。
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from typing import Annotated, Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
import auth_system as auth
|
||||||
|
from core import db, repo
|
||||||
|
from core import session as cs
|
||||||
|
from web import ratelimit
|
||||||
|
from web.deps import SiteUser, current_user, secret_key
|
||||||
|
from web.response import error, success
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
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:
|
||||||
|
secure = os.environ.get('ENABLE_SECURE_COOKIE', '').strip().lower() in ('1', 'true', 'yes')
|
||||||
|
return {'max_age': _SESSION_MAX_AGE, 'httponly': True, 'samesite': 'lax',
|
||||||
|
'path': '/', 'secure': secure}
|
||||||
|
|
||||||
|
|
||||||
|
def _login_response(payload: dict, message: str, uid: int, seq: int) -> JSONResponse:
|
||||||
|
"""构造带会话 Cookie 的成功响应(Cookie 格式与 Flask 一致)。"""
|
||||||
|
resp = JSONResponse(content={'status': 200, 'success': True, 'message': message, 'data': payload})
|
||||||
|
cookie = cs.dumps(secret_key(), {
|
||||||
|
'site_uid': uid, 'site_uid_seq': seq, 'site_uid_ts': int(time.time()),
|
||||||
|
})
|
||||||
|
resp.set_cookie(SESSION_COOKIE, cookie, **_cookie_kwargs())
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/auth/logout')
|
||||||
|
async def logout(user: Annotated[SiteUser | None, Depends(current_user)]):
|
||||||
|
"""退出登录:递增 login_seq 使本账号全部已签发会话失效,并删除本机 Cookie。"""
|
||||||
|
if user is not None:
|
||||||
|
try:
|
||||||
|
await db.execute(
|
||||||
|
'UPDATE users SET login_seq = COALESCE(login_seq, 0) + 1 WHERE id = ?',
|
||||||
|
(user.id,))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
resp = JSONResponse(content={'status': 200, 'success': True, 'message': '已退出登录'})
|
||||||
|
resp.delete_cookie(SESSION_COOKIE)
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/auth/heartbeat')
|
||||||
|
async def heartbeat(user: Annotated[SiteUser | None, Depends(current_user)]):
|
||||||
|
"""会话保活:返回最新次数;超限/失效给 401(expired 语义与 Flask 同)。"""
|
||||||
|
if user is None:
|
||||||
|
return error('登录已失效', 401, error_code='unauthorized')
|
||||||
|
row = await repo.get_user_by_id(user.id)
|
||||||
|
if row is None:
|
||||||
|
return error('登录已失效', 401, error_code='unauthorized')
|
||||||
|
credits = int(row.get('duration_seconds') or 0)
|
||||||
|
if row.get('role') != 'admin' and credits != -1 and credits <= 0:
|
||||||
|
return error('剩余次数已用完', 401, error_code='expired')
|
||||||
|
return success({'duration_seconds': row.get('duration_seconds'),
|
||||||
|
'duration_text': _format_credits(credits)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/auth/ann_seen')
|
||||||
|
async def ann_seen(user: Annotated[SiteUser | None, Depends(current_user)]):
|
||||||
|
"""标记公告已读(记录当前公告版本)。"""
|
||||||
|
if user is not None:
|
||||||
|
ann = await repo.get_announcement()
|
||||||
|
await db.execute('UPDATE users SET ann_seen = ? WHERE id = ?',
|
||||||
|
(ann.get('updated_at', ''), user.id))
|
||||||
|
return success()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/auth/login')
|
||||||
|
async def login(request: Request):
|
||||||
|
"""登录:密码校验(含邮箱登录)、失败锁定、管理员两步验证转票据。"""
|
||||||
|
from auth_routes import (
|
||||||
|
_admin2fa_issue,
|
||||||
|
_admin2fa_mask,
|
||||||
|
_login_fail_check,
|
||||||
|
_login_fail_clear,
|
||||||
|
_login_fail_locked_log_once,
|
||||||
|
_login_fail_record,
|
||||||
|
)
|
||||||
|
|
||||||
|
data = await _request_data(request)
|
||||||
|
username = str(data.get('username') or '').strip()
|
||||||
|
password = str(data.get('password') or '')
|
||||||
|
ip = ratelimit.client_ip(request)
|
||||||
|
|
||||||
|
if len(password) > 128:
|
||||||
|
# 超长密码不做 PBKDF2(CPU 放大器),直接按密码错误拒绝
|
||||||
|
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,
|
||||||
|
'登录', '失败次数过多,临时锁定')
|
||||||
|
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:
|
||||||
|
_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('账号已被禁用,请联系管理员')
|
||||||
|
|
||||||
|
_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)
|
||||||
|
except Exception:
|
||||||
|
return error('登录失败,请稍后重试', 500)
|
||||||
Reference in new issue
Block a user