feat: 优化上游认证复用与 wangwang888 分组接口

## 上游认证优化

### 核心改进
- login_password 类型上游优先复用已保存 token,过期后自动 refresh,失败再重新登录
- 新增 ensure_authenticated() 方法替代直接调用 login(),减少不必要的登录请求
- 初始化时从 auth_config 自动加载已保存的 token 和 user_id
- 请求遇到 401 时自动尝试 refresh 或 login 并重试一次

### 实现细节
- UpstreamClient.__init__: 初始化时加载 auth_config 中的 token/new_api_user
- _is_login_password_with_refresh(): 判断是否支持 refresh
- _token_is_expired(): 检查 token 是否过期(提前 60 秒)
- _refresh_login_password_token(): 刷新 login_password 类型的 token
- ensure_authenticated(): 优先复用 token,过期后 refresh,失败再 login
- _send_request(): 401 时针对 login_password 类型先 refresh 再 login 并重试

### 调用点更新
- scheduler.py: _check_upstream, _sync_upstream_keys
- website_sync.py: reconcile_upstream_keys_full
- upstreams.py: list_generated_keys, generate_keys_by_groups, test_all, check_now

## wangwang888 分组接口优化

- 提供数据库更新脚本 update_wangwang888_groups_endpoint.py
- 将 wangwang888 的 groups_endpoint 从 /groups 改为 /groups/all
- 减少不必要的 /api/v1/admin/groups 统计开销
- website_client 已有 fallback 逻辑保证兼容性

## 测试
- 新增 test_upstream_login_password_refresh.py(7 个测试用例)
- 验证 token 复用、refresh、401 重试等逻辑
- 更新 test_upstream_key_sync.py 的 FakeClient 增加 ensure_authenticated
- 所有现有测试保持通过(87 passed)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
SmartUp Developer
2026-07-02 09:26:19 +08:00
co-authored by Claude Sonnet 4.6
parent 9c9a4b3423
commit c96d55665d
7 changed files with 447 additions and 17 deletions
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""更新 wangwang888 网站的 groups_endpoint 为 /groups/all
使用方法:
python backend/update_wangwang888_groups_endpoint.py
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from app.database import SessionLocal
from app.models.website import Website
def update_wangwang888_endpoint():
db = SessionLocal()
try:
# 查找 wangwang888 网站(通过名称或 base_url 匹配)
websites = db.query(Website).filter(
(Website.name.like('%wangwang888%')) |
(Website.name.like('%旺旺888%')) |
(Website.base_url.like('%wangwang888%'))
).all()
if not websites:
print("未找到 wangwang888 网站配置")
return
for website in websites:
old_endpoint = website.groups_endpoint
if old_endpoint == "/groups/all":
print(f"网站 {website.name} (ID={website.id}) 已配置为 /groups/all,无需更新")
continue
website.groups_endpoint = "/groups/all"
print(f"更新网站 {website.name} (ID={website.id}):")
print(f" groups_endpoint: {old_endpoint} -> /groups/all")
db.commit()
print("\n更新完成")
except Exception as e:
db.rollback()
print(f"更新失败: {e}")
raise
finally:
db.close()
if __name__ == "__main__":
update_wangwang888_endpoint()