2241 lines
80 KiB
Markdown
2241 lines
80 KiB
Markdown
# Sakura 项目 — 登录与认证状态验证 完整文档
|
||||
|
|
|
|||
|
|
> 本文档汇总项目所有模块(桌面端、云端、手机端、管理后台)中**登录相关**和**验证登录状态**的代码。
|
|||
|
|
> 不包括:下载器、画廊、插件系统、代理池等非认证逻辑。
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 目录
|
|||
|
|
|
|||
|
|
1. [架构总览](#1-架构总览)
|
|||
|
|
2. [桌面端 (pixiv_app) — Pixiv 登录 & Cookie 管理](#2-桌面端-pixiv_app--pixiv-登录--cookie-管理)
|
|||
|
|
3. [桌面端 (pixiv_app) — Sakura Cloud Token 管理](#3-桌面端-pixiv_app--sakura-cloud-token-管理)
|
|||
|
|
4. [桌面端 (pixiv_app) — X (Twitter) 登录检测](#4-桌面端-pixiv_app--x-twitter-登录检测)
|
|||
|
|
5. [桌面端 (pixiv_app) — 关注同步中的认证](#5-桌面端-pixiv_app--关注同步中的认证)
|
|||
|
|
6. [桌面端 (pixiv_app) — Gallery API 中的认证接口](#6-桌面端-pixiv_app--gallery-api-中的认证接口)
|
|||
|
|
7. [云端 (sakura_cloud) — JWT 安全核心](#7-云端-sakura_cloud--jwt-安全核心)
|
|||
|
|
8. [云端 (sakura_cloud) — 认证依赖注入](#8-云端-sakura_cloud--认证依赖注入)
|
|||
|
|
9. [云端 (sakura_cloud) — 认证 API 端点](#9-云端-sakura_cloud--认证-api-端点)
|
|||
|
|
10. [云端 (sakura_cloud) — 管理员登录](#10-云端-sakura_cloud--管理员登录)
|
|||
|
|
11. [云端 (sakura_cloud) — 数据模型 & 请求模型](#11-云端-sakura_cloud--数据模型--请求模型)
|
|||
|
|
12. [手机端 (sakura_mobile) — Flutter 认证](#12-手机端-sakura_mobile--flutter-认证)
|
|||
|
|
13. [管理后台 (sakura_admin_web) — Vue 认证](#13-管理后台-sakura_admin_web--vue-认证)
|
|||
|
|
14. [认证流程总结](#14-认证流程总结)
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 1. 架构总览
|
|||
|
|
|
|||
|
|
```
|
|||
|
|
┌──────────────────────────────────────────────────────────────┐
|
|||
|
|
│ 认证体系架构 │
|
|||
|
|
├──────────────┬──────────────────┬────────────────────────────┤
|
|||
|
|
│ 桌面端 │ 云端 API │ 手机端 / 管理后台 │
|
|||
|
|
│ (Python) │ (FastAPI) │ (Flutter / Vue) │
|
|||
|
|
├──────────────┼──────────────────┼────────────────────────────┤
|
|||
|
|
│ Pixiv Cookie │ JWT Bearer │ JWT Bearer Token │
|
|||
|
|
│ + 密码登录 │ access+refresh │ SharedPreferences 持久化 │
|
|||
|
|
│ │ token_version │ sessionStorage 持久化 │
|
|||
|
|
│ Sakura Cloud │ 即时吊销 │ Axios 拦截器自动刷新 │
|
|||
|
|
│ JWT Token │ HS256 签名 │ Router Guard 路由守卫 │
|
|||
|
|
│ X Playwright │ pbkdf2/bcrypt │ │
|
|||
|
|
│ 持久化会话 │ 密码哈希 │ │
|
|||
|
|
└──────────────┴──────────────────┴────────────────────────────┘
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 2. 桌面端 (pixiv_app) — Pixiv 登录 & Cookie 管理
|
|||
|
|
|
|||
|
|
### 2.1 核心认证客户端
|
|||
|
|
|
|||
|
|
**文件:** `pixiv_app/core/auth.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import html
|
|||
|
|
import json
|
|||
|
|
import re
|
|||
|
|
from dataclasses import dataclass
|
|||
|
|
from pathlib import Path
|
|||
|
|
from typing import Any
|
|||
|
|
from urllib.parse import urlencode
|
|||
|
|
|
|||
|
|
import requests
|
|||
|
|
|
|||
|
|
from pixiv_app.core.downloader import USER_AGENT, build_headers
|
|||
|
|
|
|||
|
|
|
|||
|
|
LOGIN_PAGE_URL = "https://accounts.pixiv.net/login"
|
|||
|
|
LOGIN_AJAX_URL = "https://accounts.pixiv.net/ajax/login?lang=zh"
|
|||
|
|
VALIDATE_URL = "https://www.pixiv.net/setting_user.php"
|
|||
|
|
|
|||
|
|
|
|||
|
|
@dataclass
|
|||
|
|
class AuthResult:
|
|||
|
|
success: bool
|
|||
|
|
message: str
|
|||
|
|
cookie: str = ""
|
|||
|
|
requires_verification: bool = False
|
|||
|
|
user_name: str = ""
|
|||
|
|
user_id: str = ""
|
|||
|
|
|
|||
|
|
|
|||
|
|
class SessionStore:
|
|||
|
|
"""本地 JSON 文件持久化会话(Cookie、云同步 Token 等)。"""
|
|||
|
|
|
|||
|
|
def __init__(self, path: str | Path = "pixiv_app_session.json") -> None:
|
|||
|
|
self.path = Path(path)
|
|||
|
|
|
|||
|
|
def load(self) -> dict[str, Any]:
|
|||
|
|
if not self.path.exists():
|
|||
|
|
return {}
|
|||
|
|
try:
|
|||
|
|
return json.loads(self.path.read_text(encoding="utf-8"))
|
|||
|
|
except Exception:
|
|||
|
|
return {}
|
|||
|
|
|
|||
|
|
def save(self, payload: dict[str, Any]) -> None:
|
|||
|
|
self.path.write_text(
|
|||
|
|
json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class PixivAuthClient:
|
|||
|
|
"""Pixiv 认证客户端:Cookie 验证 + 账号密码登录。"""
|
|||
|
|
|
|||
|
|
def __init__(self) -> None:
|
|||
|
|
self.timeout = 20
|
|||
|
|
|
|||
|
|
# ── Cookie 验证 ──────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def validate_cookie(self, cookie: str) -> AuthResult:
|
|||
|
|
"""
|
|||
|
|
验证 Cookie 是否有效。
|
|||
|
|
原理:用 Cookie 访问 Pixiv 设置页,若被重定向到登录页则失效。
|
|||
|
|
"""
|
|||
|
|
cookie = cookie.strip()
|
|||
|
|
if not cookie:
|
|||
|
|
return AuthResult(False, "Cookie 为空,请先填写或登录。")
|
|||
|
|
|
|||
|
|
session = requests.Session()
|
|||
|
|
session.headers.update(
|
|||
|
|
build_headers(cookie=cookie, referer="https://www.pixiv.net/")
|
|||
|
|
)
|
|||
|
|
try:
|
|||
|
|
response = session.get(
|
|||
|
|
VALIDATE_URL, allow_redirects=True, timeout=self.timeout
|
|||
|
|
)
|
|||
|
|
final_url = response.url
|
|||
|
|
# 被重定向到登录页 = Cookie 失效
|
|||
|
|
if "return_to=" in final_url or "accounts.pixiv.net" in final_url:
|
|||
|
|
return AuthResult(False, "当前 Cookie 已失效或未登录,请更新会话。")
|
|||
|
|
user_id, user_name = self._extract_user_info(response.text)
|
|||
|
|
return AuthResult(
|
|||
|
|
True, "Cookie 有效,可直接开始抓取。",
|
|||
|
|
cookie=cookie, user_name=user_name, user_id=user_id,
|
|||
|
|
)
|
|||
|
|
except Exception as exc:
|
|||
|
|
return AuthResult(False, f"Cookie 检测失败: {exc}")
|
|||
|
|
|
|||
|
|
# ── 账号密码登录 ──────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def login_with_password(self, login_id: str, password: str) -> AuthResult:
|
|||
|
|
"""
|
|||
|
|
Pixiv 账号密码登录。
|
|||
|
|
流程:获取 CSRF Token → POST 登录 → 提取 Cookie → 验证 Cookie。
|
|||
|
|
"""
|
|||
|
|
login_id = login_id.strip()
|
|||
|
|
password = password.strip()
|
|||
|
|
if not login_id or not password:
|
|||
|
|
return AuthResult(False, "账号和密码都不能为空。")
|
|||
|
|
|
|||
|
|
session = requests.Session()
|
|||
|
|
session.headers.update({
|
|||
|
|
"User-Agent": USER_AGENT,
|
|||
|
|
"Accept": "application/json, text/plain, */*",
|
|||
|
|
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
|||
|
|
"Origin": "https://accounts.pixiv.net",
|
|||
|
|
"Referer": LOGIN_PAGE_URL,
|
|||
|
|
"X-Requested-With": "XMLHttpRequest",
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
# 1. 获取 CSRF token
|
|||
|
|
login_page = session.get(LOGIN_PAGE_URL, timeout=self.timeout)
|
|||
|
|
login_page.raise_for_status()
|
|||
|
|
tt = self._extract_tt(login_page.text)
|
|||
|
|
|
|||
|
|
# 2. 构造登录请求
|
|||
|
|
payload = {
|
|||
|
|
"login_id": login_id,
|
|||
|
|
"password": password,
|
|||
|
|
"source": "accounts",
|
|||
|
|
"app_ios": "0",
|
|||
|
|
"ref": "",
|
|||
|
|
"return_to": "https://www.pixiv.net/",
|
|||
|
|
"g_recaptcha_response": "",
|
|||
|
|
"recaptcha_enterprise_score_token": "",
|
|||
|
|
}
|
|||
|
|
headers = dict(session.headers)
|
|||
|
|
if tt:
|
|||
|
|
headers["X-CSRF-Token"] = tt
|
|||
|
|
|
|||
|
|
response = session.post(
|
|||
|
|
LOGIN_AJAX_URL,
|
|||
|
|
data=urlencode(payload),
|
|||
|
|
headers={**headers, "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"},
|
|||
|
|
timeout=self.timeout,
|
|||
|
|
)
|
|||
|
|
response.raise_for_status()
|
|||
|
|
body = response.json()
|
|||
|
|
|
|||
|
|
# 3. 检查登录结果
|
|||
|
|
if isinstance(body, dict) and body.get("body", {}).get("success"):
|
|||
|
|
cookie = self._cookies_to_header(session.cookies)
|
|||
|
|
validation = self.validate_cookie(cookie)
|
|||
|
|
if validation.success:
|
|||
|
|
validation.message = "账号密码登录成功,会话已可用。"
|
|||
|
|
return validation
|
|||
|
|
return AuthResult(
|
|||
|
|
True, "登录接口返回成功,但会话校验未完全通过,请手动检测。",
|
|||
|
|
cookie=cookie,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 4. 处理需要额外验证的情况
|
|||
|
|
body_payload = body.get("body", {}) if isinstance(body, dict) else {}
|
|||
|
|
errors = body_payload.get("errors", {}) if isinstance(body_payload, dict) else {}
|
|||
|
|
if (
|
|||
|
|
errors.get("recaptcha")
|
|||
|
|
or body_payload.get("requireExtraVerification")
|
|||
|
|
or body_payload.get("requireTwoFactorAuthentication")
|
|||
|
|
):
|
|||
|
|
return AuthResult(
|
|||
|
|
False,
|
|||
|
|
"Pixiv 要求额外验证或二步验证,程序无法静默完成。请改用 Cookie 登录。",
|
|||
|
|
requires_verification=True,
|
|||
|
|
)
|
|||
|
|
message = self._flatten_error_message(errors) or "账号密码登录失败"
|
|||
|
|
return AuthResult(False, message)
|
|||
|
|
except Exception as exc:
|
|||
|
|
return AuthResult(False, f"账号密码登录失败: {exc}")
|
|||
|
|
|
|||
|
|
# ── CSRF Token 提取 ──────────────────────────────────────
|
|||
|
|
|
|||
|
|
def _extract_tt(self, html_text: str) -> str:
|
|||
|
|
"""从 Pixiv 登录页提取 CSRF token (pixivAccount.tt)。"""
|
|||
|
|
match = re.search(r'"pixivAccount\.tt":"([^"]+)"', html_text)
|
|||
|
|
return match.group(1) if match else ""
|
|||
|
|
|
|||
|
|
# ── 用户信息提取 ──────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def _extract_user_info(self, html_text: str) -> tuple[str, str]:
|
|||
|
|
"""从页面 HTML 中正则提取 user_id 和 user_name。"""
|
|||
|
|
user_id = ""
|
|||
|
|
user_name = ""
|
|||
|
|
patterns = [
|
|||
|
|
r'"userData":\{"id":"(\d+)","pixivId":"[^"]*","name":"([^"]+)"',
|
|||
|
|
r'"user_id":"(\d+)".*?"name":"([^"]+)"',
|
|||
|
|
]
|
|||
|
|
for pattern in patterns:
|
|||
|
|
match = re.search(pattern, html_text)
|
|||
|
|
if match:
|
|||
|
|
user_id = match.group(1)
|
|||
|
|
user_name = html.unescape(match.group(2))
|
|||
|
|
break
|
|||
|
|
return user_id, user_name
|
|||
|
|
|
|||
|
|
# ── 工具方法 ──────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def _flatten_error_message(self, errors: dict[str, Any]) -> str:
|
|||
|
|
messages: list[str] = []
|
|||
|
|
for key, value in errors.items():
|
|||
|
|
if isinstance(value, str) and value.strip():
|
|||
|
|
messages.append(f"{key}: {value}")
|
|||
|
|
elif isinstance(value, list):
|
|||
|
|
text_items = [str(item).strip() for item in value if str(item).strip()]
|
|||
|
|
if text_items:
|
|||
|
|
messages.append(f"{key}: {'; '.join(text_items)}")
|
|||
|
|
return " | ".join(messages)
|
|||
|
|
|
|||
|
|
def _cookies_to_header(self, jar: requests.cookies.RequestsCookieJar) -> str:
|
|||
|
|
parts = [f"{cookie.name}={cookie.value}" for cookie in jar]
|
|||
|
|
return "; ".join(parts)
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 2.2 GUI 中的 Pixiv 登录与会话管理
|
|||
|
|
|
|||
|
|
**文件:** `pixiv_app/gui/app.py`(关键方法摘录)
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
# ── 类成员变量(__init__ 中初始化) ─────────────────────────────
|
|||
|
|
|
|||
|
|
LOGIN_MODE_MAP = {
|
|||
|
|
"Cookie 登录": "cookie",
|
|||
|
|
"账号密码登录": "password",
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
self.login_mode_var = ctk.StringVar(value="Cookie 登录")
|
|||
|
|
self.auth_status_var = ctk.StringVar(
|
|||
|
|
value="未登录,推荐导入 cookies.txt;也可尝试账号密码登录。"
|
|||
|
|
)
|
|||
|
|
self.cookie_json: list[dict] = []
|
|||
|
|
self.cookie_header = ""
|
|||
|
|
self.auth_client = PixivAuthClient()
|
|||
|
|
self.session_store = SessionStore(app_session_file())
|
|||
|
|
|
|||
|
|
# ── Cookie 获取(优先级:JSON → Header → 磁盘) ─────────────────
|
|||
|
|
|
|||
|
|
def get_active_cookie(self) -> str:
|
|||
|
|
payload = self.session_store.load()
|
|||
|
|
cookies = self.cookie_json or payload.get("cookie_json") or []
|
|||
|
|
if cookies:
|
|||
|
|
try:
|
|||
|
|
return cookies_to_header(list(cookies), ("pixiv.net",))
|
|||
|
|
except Exception:
|
|||
|
|
pass
|
|||
|
|
if self.cookie_header:
|
|||
|
|
return self.cookie_header
|
|||
|
|
return str(payload.get("cookie", "")).strip()
|
|||
|
|
|
|||
|
|
# ── Cookie 导入 ────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def import_cookie_txt(self) -> None:
|
|||
|
|
"""文件对话框导入 cookies.txt / JSON,按域名分类保存"""
|
|||
|
|
path = filedialog.askopenfilename(
|
|||
|
|
title="导入 Cookie txt",
|
|||
|
|
filetypes=[("Cookie files", "*.txt *.json"), ...],
|
|||
|
|
)
|
|||
|
|
if not path:
|
|||
|
|
return
|
|||
|
|
try:
|
|||
|
|
text = Path(path).read_text(encoding="utf-8-sig")
|
|||
|
|
except UnicodeDecodeError:
|
|||
|
|
text = Path(path).read_text(encoding="utf-8", errors="replace")
|
|||
|
|
cookies = parse_cookie_text(text)
|
|||
|
|
|
|||
|
|
# 按平台分类
|
|||
|
|
pixiv_cookies = (
|
|||
|
|
cookies_to_playwright(cookies, ("pixiv.net",))
|
|||
|
|
if has_cookie_domain(cookies, ("pixiv.net,")) else []
|
|||
|
|
)
|
|||
|
|
x_cookies = (
|
|||
|
|
cookies_to_playwright(cookies, ("x.com", "twitter.com"))
|
|||
|
|
if has_cookie_domain(cookies, ("x.com", "twitter.com")) else []
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
self.cookie_json = cookies
|
|||
|
|
self.cookie_header = (
|
|||
|
|
cookies_to_header(pixiv_cookies, ("pixiv.net",)) if pixiv_cookies else ""
|
|||
|
|
)
|
|||
|
|
self.login_mode_var.set("Cookie 登录")
|
|||
|
|
self.update_login_mode_ui("Cookie 登录")
|
|||
|
|
|
|||
|
|
if x_cookies:
|
|||
|
|
save_playwright_cookies(x_cookies, runtime_path("x_cookies.json"))
|
|||
|
|
self.save_session()
|
|||
|
|
|
|||
|
|
# ── 会话持久化 ─────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def save_session(self) -> None:
|
|||
|
|
cookie = self.get_active_cookie()
|
|||
|
|
cloud_config = self.get_cloud_sync_config()
|
|||
|
|
payload = {
|
|||
|
|
"login_mode": self.LOGIN_MODE_MAP.get(self.login_mode_var.get(), "cookie"),
|
|||
|
|
"cookie": cookie,
|
|||
|
|
"cookie_json": self.cookie_json,
|
|||
|
|
"login_id": self.login_id_entry.get().strip(),
|
|||
|
|
"cloud_sync": cloud_config,
|
|||
|
|
"saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
|||
|
|
}
|
|||
|
|
self.session_store.save(payload)
|
|||
|
|
|
|||
|
|
def load_saved_session(self, silent: bool = False) -> None:
|
|||
|
|
"""启动时从磁盘恢复会话(Pixiv Cookie + Cloud Token)"""
|
|||
|
|
payload = self.session_store.load()
|
|||
|
|
if not payload:
|
|||
|
|
return
|
|||
|
|
# 恢复 Pixiv 会话
|
|||
|
|
self.cookie_json = list(payload.get("cookie_json") or [])
|
|||
|
|
self.cookie_header = str(payload.get("cookie", "") or "")
|
|||
|
|
self.login_id_entry.insert(0, str(payload.get("login_id", "")))
|
|||
|
|
|
|||
|
|
# 恢复 Cloud 会话
|
|||
|
|
cloud = payload.get("cloud_sync") if isinstance(payload.get("cloud_sync"), dict) else {}
|
|||
|
|
self.cloud_base_url = str(cloud.get("base_url") or DEFAULT_CLOUD_API)
|
|||
|
|
self.cloud_access_token = str(cloud.get("access_token") or "")
|
|||
|
|
self.cloud_refresh_token = str(cloud.get("refresh_token") or "")
|
|||
|
|
CloudSession().configure(
|
|||
|
|
base_url=self.cloud_base_url,
|
|||
|
|
access_token=self.cloud_access_token,
|
|||
|
|
refresh_token=self.cloud_refresh_token,
|
|||
|
|
enabled=bool(cloud.get("enabled", False)),
|
|||
|
|
)
|
|||
|
|
CloudSession().add_listener(self._on_cloud_token_refreshed)
|
|||
|
|
|
|||
|
|
# ── Cookie 验证 ────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def validate_session(self) -> None:
|
|||
|
|
"""线程中调用 auth_client.validate_cookie()"""
|
|||
|
|
cookie = self.get_active_cookie()
|
|||
|
|
if not cookie:
|
|||
|
|
messagebox.showerror("检测失败", "当前没有 Cookie 可检测。")
|
|||
|
|
return
|
|||
|
|
self.auth_status_var.set("正在检测当前会话...")
|
|||
|
|
|
|||
|
|
def worker() -> None:
|
|||
|
|
result = self.auth_client.validate_cookie(cookie)
|
|||
|
|
self.enqueue_ui(self.apply_auth_result, result, False)
|
|||
|
|
|
|||
|
|
threading.Thread(target=worker, daemon=True).start()
|
|||
|
|
|
|||
|
|
# ── 密码登录 ───────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def login_with_password(self) -> None:
|
|||
|
|
login_id = self.login_id_entry.get().strip()
|
|||
|
|
password = self.password_entry.get().strip()
|
|||
|
|
if not login_id or not password:
|
|||
|
|
messagebox.showerror("登录失败", "请先填写账号和密码。")
|
|||
|
|
return
|
|||
|
|
self.auth_status_var.set("正在尝试账号密码登录...")
|
|||
|
|
|
|||
|
|
def worker() -> None:
|
|||
|
|
result = self.auth_client.login_with_password(login_id, password)
|
|||
|
|
self.enqueue_ui(self.apply_auth_result, result, True)
|
|||
|
|
|
|||
|
|
threading.Thread(target=worker, daemon=True).start()
|
|||
|
|
|
|||
|
|
def apply_auth_result(self, result: AuthResult, from_password_login: bool) -> None:
|
|||
|
|
"""统一处理认证结果:更新 UI、保存会话"""
|
|||
|
|
self.auth_status_var.set(result.message)
|
|||
|
|
if result.success and result.cookie:
|
|||
|
|
self.cookie_json = []
|
|||
|
|
self.cookie_header = result.cookie
|
|||
|
|
self.set_cookie_indicator("账号密码登录已生成 Cookie header")
|
|||
|
|
if from_password_login:
|
|||
|
|
self.login_mode_var.set("Cookie 登录")
|
|||
|
|
self.update_login_mode_ui("Cookie 登录")
|
|||
|
|
self.save_session()
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 2.3 GUI 中的云同步登录对话框
|
|||
|
|
|
|||
|
|
**文件:** `pixiv_app/gui/app.py`(`open_cloud_auth_dialog` 方法摘要)
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
def open_cloud_auth_dialog(self) -> None:
|
|||
|
|
"""Sakura Cloud 账号管理窗口:登录 / 注册 / 获取 Token 三个标签页"""
|
|||
|
|
|
|||
|
|
# ── 登录标签页 ──────────────────────────────────────────
|
|||
|
|
def do_login() -> None:
|
|||
|
|
email = login_email.get().strip()
|
|||
|
|
password = login_password.get()
|
|||
|
|
# ...
|
|||
|
|
def worker() -> None:
|
|||
|
|
resp = requests.post(
|
|||
|
|
f"{api_addr}/api/v1/auth/login",
|
|||
|
|
json={"username_or_email": email, "password": password},
|
|||
|
|
timeout=15,
|
|||
|
|
)
|
|||
|
|
if resp.status_code == 200:
|
|||
|
|
data = resp.json()
|
|||
|
|
token = data.get("data", {}).get("access_token")
|
|||
|
|
if token:
|
|||
|
|
self.cloud_access_token = str(token).strip()
|
|||
|
|
refresh = (data.get("data", {}).get("refresh_token") or "")
|
|||
|
|
if refresh:
|
|||
|
|
self.cloud_refresh_token = str(refresh).strip()
|
|||
|
|
# 同步到全局单例
|
|||
|
|
CloudSession().configure(
|
|||
|
|
base_url=self.cloud_base_url,
|
|||
|
|
access_token=self.cloud_access_token,
|
|||
|
|
refresh_token=self.cloud_refresh_token,
|
|||
|
|
enabled=True,
|
|||
|
|
)
|
|||
|
|
self.cloud_sync_enabled_var.set(True)
|
|||
|
|
self.save_session()
|
|||
|
|
threading.Thread(target=worker, daemon=True).start()
|
|||
|
|
|
|||
|
|
# ── 注册标签页 ──────────────────────────────────────────
|
|||
|
|
def do_register() -> None:
|
|||
|
|
# POST /api/v1/auth/register
|
|||
|
|
resp = requests.post(
|
|||
|
|
f"{api_addr}/api/v1/auth/register",
|
|||
|
|
json={"username": username, "email": email, "password": password},
|
|||
|
|
timeout=15,
|
|||
|
|
)
|
|||
|
|
if resp.status_code == 201:
|
|||
|
|
# 注册成功,切换到登录页
|
|||
|
|
|
|||
|
|
def test_cloud_connection(self) -> None:
|
|||
|
|
"""测试云连接:GET /api/v1/users/me 验证 Token 有效性"""
|
|||
|
|
def worker() -> None:
|
|||
|
|
resp = requests.get(
|
|||
|
|
f"{api_url}/api/v1/users/me",
|
|||
|
|
headers={"Authorization": f"Bearer {token}"},
|
|||
|
|
timeout=10,
|
|||
|
|
)
|
|||
|
|
if resp.status_code == 200:
|
|||
|
|
user = resp.json().get("data", {})
|
|||
|
|
username = user.get("username", "未知")
|
|||
|
|
self.cloud_status_var.set(f"连接成功!用户:{username}")
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 3. 桌面端 (pixiv_app) — Sakura Cloud Token 管理
|
|||
|
|
|
|||
|
|
### 3.1 CloudSession 全局单例
|
|||
|
|
|
|||
|
|
**文件:** `pixiv_app/core/cloud_sync.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
import base64
|
|||
|
|
import json
|
|||
|
|
import logging
|
|||
|
|
import threading
|
|||
|
|
import time
|
|||
|
|
from collections.abc import Callable
|
|||
|
|
from typing import Any
|
|||
|
|
|
|||
|
|
import requests
|
|||
|
|
|
|||
|
|
logger = logging.getLogger(__name__)
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ── JWT exp 解码 ────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def _decode_jwt_exp(token: str) -> float:
|
|||
|
|
"""解码 JWT payload 中的 exp 字段,返回 Unix 时间戳。"""
|
|||
|
|
if not token or "." not in token:
|
|||
|
|
return 0.0
|
|||
|
|
try:
|
|||
|
|
payload = token.split(".")[1]
|
|||
|
|
payload += "=" * (4 - len(payload) % 4)
|
|||
|
|
decoded = json.loads(base64.urlsafe_b64decode(payload))
|
|||
|
|
return float(decoded.get("exp", 0))
|
|||
|
|
except Exception:
|
|||
|
|
return 0.0
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ── Token 持久化到磁盘 ──────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def persist_cloud_session_tokens(access_token: str, refresh_token: str = "") -> None:
|
|||
|
|
"""将刷新后的 Token 写回桌面会话文件。"""
|
|||
|
|
from pixiv_app.core.auth import SessionStore
|
|||
|
|
from pixiv_app.core.paths import app_session_file
|
|||
|
|
|
|||
|
|
store = SessionStore(app_session_file())
|
|||
|
|
payload = store.load()
|
|||
|
|
cloud = payload.get("cloud_sync") if isinstance(payload.get("cloud_sync"), dict) else {}
|
|||
|
|
cloud["access_token"] = access_token
|
|||
|
|
if refresh_token:
|
|||
|
|
cloud["refresh_token"] = refresh_token
|
|||
|
|
payload["cloud_sync"] = cloud
|
|||
|
|
store.save(payload)
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ── CloudSession 全局单例 ───────────────────────────────────────
|
|||
|
|
|
|||
|
|
class CloudSession:
|
|||
|
|
"""
|
|||
|
|
全局单例,统一管理云同步 Token 的读写、刷新与持久化。
|
|||
|
|
所有需要访问 Sakura Cloud API 的模块都通过此单例获取配置和创建客户端。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
_instance: CloudSession | None = None
|
|||
|
|
_instance_lock = threading.Lock()
|
|||
|
|
|
|||
|
|
def __new__(cls) -> CloudSession:
|
|||
|
|
if cls._instance is None:
|
|||
|
|
with cls._instance_lock:
|
|||
|
|
if cls._instance is None:
|
|||
|
|
instance = super().__new__(cls)
|
|||
|
|
instance._base_url = ""
|
|||
|
|
instance._access_token = ""
|
|||
|
|
instance._refresh_token = ""
|
|||
|
|
instance._enabled = False
|
|||
|
|
instance._refresh_lock = threading.Lock()
|
|||
|
|
instance._listeners: list[Callable[[str, str], None]] = []
|
|||
|
|
instance._last_refresh_time = 0.0
|
|||
|
|
cls._instance = instance
|
|||
|
|
return cls._instance
|
|||
|
|
|
|||
|
|
# ── 配置入口 ────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def configure(self, *, base_url="", access_token="", refresh_token="", enabled=False):
|
|||
|
|
"""GUI 启动/登录/保存会话时调用,同步最新 token 到全局单例。"""
|
|||
|
|
self._base_url = (base_url or "").strip()
|
|||
|
|
self._access_token = (access_token or "").strip()
|
|||
|
|
self._refresh_token = (refresh_token or "").strip()
|
|||
|
|
self._enabled = bool(enabled)
|
|||
|
|
|
|||
|
|
def load_from_disk(self) -> dict[str, Any]:
|
|||
|
|
"""从磁盘会话文件读取云端配置并应用到单例。"""
|
|||
|
|
from pixiv_app.core.auth import SessionStore
|
|||
|
|
from pixiv_app.core.paths import app_session_file
|
|||
|
|
|
|||
|
|
store = SessionStore(app_session_file())
|
|||
|
|
payload = store.load()
|
|||
|
|
cloud = payload.get("cloud_sync") if isinstance(payload.get("cloud_sync"), dict) else {}
|
|||
|
|
self.configure(
|
|||
|
|
base_url=str(cloud.get("base_url") or ""),
|
|||
|
|
access_token=str(cloud.get("access_token") or ""),
|
|||
|
|
refresh_token=str(cloud.get("refresh_token") or ""),
|
|||
|
|
enabled=bool(cloud.get("enabled", False)),
|
|||
|
|
)
|
|||
|
|
return payload
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def enabled(self) -> bool:
|
|||
|
|
"""云同步是否完全可用(启用 + 有 base_url + 有 access_token)。"""
|
|||
|
|
return self._enabled and bool(self._base_url) and bool(self._access_token)
|
|||
|
|
|
|||
|
|
# ── Config 快照 ─────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def get_config(self) -> CloudSyncConfig:
|
|||
|
|
"""
|
|||
|
|
返回当前 token 的 CloudSyncConfig 快照。
|
|||
|
|
若 access_token 即将过期(< 5 分钟),主动触发刷新。
|
|||
|
|
"""
|
|||
|
|
if self._access_token and self._is_expired_or_near(threshold_seconds=300):
|
|||
|
|
self.try_refresh()
|
|||
|
|
return CloudSyncConfig(
|
|||
|
|
base_url=self._base_url,
|
|||
|
|
access_token=self._access_token,
|
|||
|
|
refresh_token=self._refresh_token,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# ── 监听者管理 ──────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def add_listener(self, callback: Callable[[str, str], None]) -> None:
|
|||
|
|
"""注册 token 刷新回调(如 GUI 的 _on_cloud_token_refreshed)。"""
|
|||
|
|
if callback not in self._listeners:
|
|||
|
|
self._listeners.append(callback)
|
|||
|
|
|
|||
|
|
def remove_listener(self, callback: Callable[[str, str], None]) -> None:
|
|||
|
|
try:
|
|||
|
|
self._listeners.remove(callback)
|
|||
|
|
except ValueError:
|
|||
|
|
pass
|
|||
|
|
|
|||
|
|
def notify_listeners(self, access_token: str, refresh_token: str) -> None:
|
|||
|
|
"""通知所有监听者 token 已更新。"""
|
|||
|
|
for callback in self._listeners:
|
|||
|
|
try:
|
|||
|
|
callback(access_token, refresh_token)
|
|||
|
|
except Exception:
|
|||
|
|
logger.exception("CloudSession listener failed")
|
|||
|
|
|
|||
|
|
# ── Token 刷新(核心) ──────────────────────────────────
|
|||
|
|
|
|||
|
|
def try_refresh(self) -> bool:
|
|||
|
|
"""
|
|||
|
|
统一刷新入口。使用全局锁防止并发重复刷新。
|
|||
|
|
Returns: True=成功, False=失败(token 已清空并通知监听者)
|
|||
|
|
"""
|
|||
|
|
refresh = self._refresh_token
|
|||
|
|
if not refresh:
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
with self._refresh_lock:
|
|||
|
|
refresh = self._refresh_token
|
|||
|
|
if not refresh:
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
# 距上次刷新不足 5 秒,跳过(防抖)
|
|||
|
|
elapsed = time.time() - self._last_refresh_time
|
|||
|
|
if elapsed < 5.0 and self._access_token:
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
resp = requests.post(
|
|||
|
|
f"{self._base_url}/api/v1/auth/refresh",
|
|||
|
|
json={"refresh_token": refresh},
|
|||
|
|
timeout=30.0,
|
|||
|
|
)
|
|||
|
|
if resp.status_code != 200:
|
|||
|
|
self._on_refresh_failed()
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
body = resp.json()
|
|||
|
|
data = body.get("data", body) if isinstance(body, dict) else {}
|
|||
|
|
new_access = (data.get("access_token") or "").strip()
|
|||
|
|
new_refresh = (data.get("refresh_token") or "").strip()
|
|||
|
|
|
|||
|
|
if not new_access:
|
|||
|
|
self._on_refresh_failed()
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
self._access_token = new_access
|
|||
|
|
if new_refresh:
|
|||
|
|
self._refresh_token = new_refresh
|
|||
|
|
self._last_refresh_time = time.time()
|
|||
|
|
self._persist()
|
|||
|
|
self.notify_listeners(self._access_token, self._refresh_token)
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
except Exception:
|
|||
|
|
logger.exception("CloudSession refresh error")
|
|||
|
|
self._on_refresh_failed()
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
def _on_refresh_failed(self) -> None:
|
|||
|
|
"""刷新失败:清空 token + 写盘 + 通知监听者。"""
|
|||
|
|
self._access_token = ""
|
|||
|
|
self._refresh_token = ""
|
|||
|
|
self._last_refresh_time = time.time()
|
|||
|
|
self._persist()
|
|||
|
|
self.notify_listeners("", "")
|
|||
|
|
|
|||
|
|
def _persist(self) -> None:
|
|||
|
|
try:
|
|||
|
|
persist_cloud_session_tokens(self._access_token, self._refresh_token)
|
|||
|
|
except Exception:
|
|||
|
|
logger.exception("CloudSession persist to disk failed")
|
|||
|
|
|
|||
|
|
# ── JWT 过期判断 ────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def _is_expired_or_near(self, threshold_seconds: int = 300) -> bool:
|
|||
|
|
exp = _decode_jwt_exp(self._access_token)
|
|||
|
|
if exp <= 0:
|
|||
|
|
return False
|
|||
|
|
return (exp - threshold_seconds) <= time.time()
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 3.2 SakuraCloudClient 的 401 自动重试
|
|||
|
|
|
|||
|
|
**文件:** `pixiv_app/core/cloud_sync.py`(`SakuraCloudClient` 类关键方法)
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
class SakuraCloudClient:
|
|||
|
|
def __init__(self, config: CloudSyncConfig, *, cloud_session=None):
|
|||
|
|
self.config = config
|
|||
|
|
self.base_url = config.base_url.rstrip("/")
|
|||
|
|
self.session = requests.Session()
|
|||
|
|
self.session.headers.update({"Authorization": f"Bearer {config.access_token}"})
|
|||
|
|
self._cloud_session = cloud_session
|
|||
|
|
|
|||
|
|
def _request(self, method, path, *, json=None, data=None,
|
|||
|
|
files=None, _retry_on_401=True) -> requests.Response:
|
|||
|
|
url = f"{self.base_url}{path}"
|
|||
|
|
response = self.session.request(
|
|||
|
|
method, url, json=json, data=data, files=files,
|
|||
|
|
timeout=self.config.timeout,
|
|||
|
|
)
|
|||
|
|
# 401 自动刷新 token 并重试一次
|
|||
|
|
if response.status_code == 401 and _retry_on_401 and self._try_refresh_token():
|
|||
|
|
response = self.session.request(
|
|||
|
|
method, url, json=json, data=data, files=files,
|
|||
|
|
timeout=self.config.timeout,
|
|||
|
|
)
|
|||
|
|
return response
|
|||
|
|
|
|||
|
|
def _try_refresh_token(self) -> bool:
|
|||
|
|
"""委托给全局 CloudSession 或本地处理 token 刷新。"""
|
|||
|
|
if self._cloud_session is not None:
|
|||
|
|
ok = self._cloud_session.try_refresh()
|
|||
|
|
if ok:
|
|||
|
|
new_config = self._cloud_session.get_config()
|
|||
|
|
self.config.access_token = new_config.access_token
|
|||
|
|
self.config.refresh_token = new_config.refresh_token
|
|||
|
|
self.session.headers.update(
|
|||
|
|
{"Authorization": f"Bearer {new_config.access_token}"}
|
|||
|
|
)
|
|||
|
|
return ok
|
|||
|
|
|
|||
|
|
# 旧路径(向后兼容)
|
|||
|
|
refresh = self.config.refresh_token.strip()
|
|||
|
|
if not refresh:
|
|||
|
|
return False
|
|||
|
|
# ... POST /api/v1/auth/refresh 并更新本地 config ...
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 3.3 GUI Token 刷新回调
|
|||
|
|
|
|||
|
|
**文件:** `pixiv_app/gui/app.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
def _on_cloud_token_refreshed(self, new_access: str, new_refresh: str) -> None:
|
|||
|
|
"""
|
|||
|
|
Token 刷新回调(注册为 CloudSession 监听者)。
|
|||
|
|
成功:更新 GUI 字段 + 持久化到磁盘。
|
|||
|
|
失败(空 token):清除状态并提示过期。
|
|||
|
|
"""
|
|||
|
|
if not new_access:
|
|||
|
|
self.cloud_access_token = ""
|
|||
|
|
self.cloud_refresh_token = ""
|
|||
|
|
self.cloud_sync_enabled_var.set(False)
|
|||
|
|
self.cloud_status_var.set("云同步会话已过期,请重新登录云端账号")
|
|||
|
|
return
|
|||
|
|
|
|||
|
|
self.cloud_access_token = new_access
|
|||
|
|
if new_refresh:
|
|||
|
|
self.cloud_refresh_token = new_refresh
|
|||
|
|
self.cloud_status_var.set("云同步 Token 已自动续期")
|
|||
|
|
|
|||
|
|
# 写回磁盘
|
|||
|
|
try:
|
|||
|
|
payload = self.session_store.load()
|
|||
|
|
cloud = payload.get("cloud_sync") if isinstance(payload.get("cloud_sync"), dict) else {}
|
|||
|
|
cloud["access_token"] = new_access
|
|||
|
|
if new_refresh:
|
|||
|
|
cloud["refresh_token"] = new_refresh
|
|||
|
|
payload["cloud_sync"] = cloud
|
|||
|
|
self.session_store.save(payload)
|
|||
|
|
except Exception:
|
|||
|
|
self.save_session()
|
|||
|
|
|
|||
|
|
def cloud_sync_active(self) -> bool:
|
|||
|
|
"""判断云同步是否已完全配置。"""
|
|||
|
|
config = self.get_cloud_sync_config()
|
|||
|
|
return bool(config.get("enabled") and config.get("base_url") and config.get("access_token"))
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 4. 桌面端 (pixiv_app) — X (Twitter) 登录检测
|
|||
|
|
|
|||
|
|
### 4.1 XAuthManager 登录状态检测
|
|||
|
|
|
|||
|
|
**文件:** `pixiv_app/services/x_auth_manager.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
class XAuthManager:
|
|||
|
|
"""
|
|||
|
|
基于 Playwright 持久化 Chromium Profile 的 X (Twitter) 会话管理。
|
|||
|
|
会话自动从磁盘恢复(user_data_dir),登录检测通过 DOM 启发式判断。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
HOME_URL = "https://x.com/home"
|
|||
|
|
LOGIN_FLOW_HINT = "https://x.com/i/flow/login"
|
|||
|
|
|
|||
|
|
async def is_logged_in(self, *, page=None, navigate=True) -> bool:
|
|||
|
|
"""
|
|||
|
|
启发式登录检测(DOM + URL):
|
|||
|
|
- 访问首页,检查 URL 是否被重定向到登录/注册页
|
|||
|
|
- 检查已登录特有的 DOM 元素
|
|||
|
|
- 检查 "Sign in to X" 访客墙文本
|
|||
|
|
"""
|
|||
|
|
p = page if page is not None else await self.get_page()
|
|||
|
|
|
|||
|
|
if navigate:
|
|||
|
|
await p.goto(self.HOME_URL, wait_until="domcontentloaded", timeout=45_000)
|
|||
|
|
await asyncio.sleep(0.6)
|
|||
|
|
|
|||
|
|
# 1. URL 检查:在登录/注册页 = 未登录
|
|||
|
|
url = (p.url or "").lower()
|
|||
|
|
if any(x in url for x in ("/i/flow/login", "/i/flow/signup", "/login")):
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
# 2. 已登录 DOM 元素检查
|
|||
|
|
logged_in_selectors = (
|
|||
|
|
'[data-testid="SideNav_AccountSwitcher_Button"]',
|
|||
|
|
'[data-testid="AppTabBar_Home_Link"]',
|
|||
|
|
'[data-testid="primaryColumn"]',
|
|||
|
|
'[data-testid="tweet"]',
|
|||
|
|
)
|
|||
|
|
for sel in logged_in_selectors:
|
|||
|
|
try:
|
|||
|
|
el = await p.wait_for_selector(sel, timeout=2500, state="visible")
|
|||
|
|
if el:
|
|||
|
|
return True
|
|||
|
|
except Exception:
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
# 3. 访客墙检查
|
|||
|
|
try:
|
|||
|
|
guest = p.get_by_text("Sign in to X", exact=False)
|
|||
|
|
if await guest.count() and await guest.first.is_visible(timeout=800):
|
|||
|
|
return False
|
|||
|
|
except Exception:
|
|||
|
|
pass
|
|||
|
|
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
async def session_healthy(self) -> bool:
|
|||
|
|
"""带重试的登录状态检测。"""
|
|||
|
|
for attempt in range(self._max_health_retries):
|
|||
|
|
try:
|
|||
|
|
return await self.is_logged_in()
|
|||
|
|
except Exception:
|
|||
|
|
if attempt == self._max_health_retries - 1:
|
|||
|
|
raise
|
|||
|
|
return False
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 5. 桌面端 (pixiv_app) — 关注同步中的认证
|
|||
|
|
|
|||
|
|
### 5.1 Pixiv 关注同步使用 Cookie 验证身份
|
|||
|
|
|
|||
|
|
**文件:** `pixiv_app/core/origin_follow_sync.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
def sync_pixiv(self, *, progress=None) -> OriginFollowSyncResult:
|
|||
|
|
"""同步 Pixiv 关注列表到本地和云端。"""
|
|||
|
|
# 从磁盘读取 Pixiv Cookie
|
|||
|
|
cookie = str(
|
|||
|
|
SessionStore(app_session_file()).load().get("cookie", "")
|
|||
|
|
).strip()
|
|||
|
|
if not cookie:
|
|||
|
|
raise ValueError("Pixiv Cookie 不存在,请先导入或保存 Pixiv 登录态。")
|
|||
|
|
|
|||
|
|
result = OriginFollowSyncResult(platform="pixiv")
|
|||
|
|
session = create_session(cookie)
|
|||
|
|
try:
|
|||
|
|
# 用 Cookie 识别当前登录用户
|
|||
|
|
user_id = self._fetch_pixiv_current_user_id(session, cookie)
|
|||
|
|
follows = self._fetch_pixiv_following(session, cookie, user_id, result)
|
|||
|
|
finally:
|
|||
|
|
session.close()
|
|||
|
|
self._upsert_pixiv_local(follows, result)
|
|||
|
|
self._sync_cloud(follows, result) # 使用 CloudSession Token
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
def _fetch_pixiv_current_user_id(self, session, cookie: str) -> str:
|
|||
|
|
"""通过 AJAX API 或首页 HTML 提取当前登录用户 ID。"""
|
|||
|
|
# 尝试 AJAX 接口
|
|||
|
|
for url in (
|
|||
|
|
"https://www.pixiv.net/ajax/user/self?lang=zh",
|
|||
|
|
"https://www.pixiv.net/ajax/user/self",
|
|||
|
|
):
|
|||
|
|
try:
|
|||
|
|
payload = request_json(session, url, cookie=cookie)
|
|||
|
|
body = payload.get("body") if isinstance(payload, dict) else {}
|
|||
|
|
user_id = _first_text(body, "userId", "id")
|
|||
|
|
if user_id:
|
|||
|
|
return user_id
|
|||
|
|
except Exception:
|
|||
|
|
continue
|
|||
|
|
# Fallback: 从首页 HTML 提取
|
|||
|
|
try:
|
|||
|
|
response = session.get("https://www.pixiv.net/", timeout=30)
|
|||
|
|
response.raise_for_status()
|
|||
|
|
match = re.search(
|
|||
|
|
r'"userData"\s*:\s*\{[^}]*"id"\s*:\s*"?(?P<id>\d+)"?',
|
|||
|
|
response.text,
|
|||
|
|
)
|
|||
|
|
if match:
|
|||
|
|
return match.group("id")
|
|||
|
|
except Exception:
|
|||
|
|
pass
|
|||
|
|
raise ValueError("Pixiv Cookie 可能已失效:无法识别当前登录账号。")
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 6. 桌面端 (pixiv_app) — Gallery API 中的认证接口
|
|||
|
|
|
|||
|
|
### 6.1 WebUI 的 Cookie 导入 & 会话状态 API
|
|||
|
|
|
|||
|
|
**文件:** `pixiv_app/services/gallery_api.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
def _handle_cookie_import(self, payload: dict) -> dict:
|
|||
|
|
"""POST /api/cookies/import — WebUI 导入 Cookie"""
|
|||
|
|
platform = str(payload.get("platform", "")).strip().lower()
|
|||
|
|
text = str(payload.get("text", ""))
|
|||
|
|
|
|||
|
|
if platform in {"pixiv", "px"}:
|
|||
|
|
cookies = parse_cookie_text(text)
|
|||
|
|
pixiv_cookies = cookies_to_playwright(cookies, ("pixiv.net",))
|
|||
|
|
header = cookies_to_header(pixiv_cookies, ("pixiv.net",))
|
|||
|
|
store = SessionStore(app_session_file())
|
|||
|
|
session_payload = store.load()
|
|||
|
|
session_payload.update({
|
|||
|
|
"login_mode": "cookie",
|
|||
|
|
"cookie": header,
|
|||
|
|
"cookie_json": pixiv_cookies,
|
|||
|
|
"login_id": "",
|
|||
|
|
"saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
|||
|
|
})
|
|||
|
|
store.save(session_payload)
|
|||
|
|
return {"platform": "pixiv", "count": len(pixiv_cookies), ...}
|
|||
|
|
|
|||
|
|
if platform in {"x", "twitter"}:
|
|||
|
|
result = self.x_media_service.import_cookie_text(text)
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
def _handle_session_status(self) -> dict:
|
|||
|
|
"""GET /api/session/status — 返回当前登录状态"""
|
|||
|
|
payload = SessionStore(app_session_file()).load()
|
|||
|
|
cloud = payload.get("cloud_sync") if isinstance(payload.get("cloud_sync"), dict) else {}
|
|||
|
|
return {
|
|||
|
|
"pixiv": {
|
|||
|
|
"has_cookie": bool(pixiv_cookie or cookie_json),
|
|||
|
|
"saved_at": str(payload.get("saved_at") or ""),
|
|||
|
|
"login_mode": str(payload.get("login_mode") or ""),
|
|||
|
|
},
|
|||
|
|
"cloud": {
|
|||
|
|
"enabled": bool(cloud.get("enabled")),
|
|||
|
|
"has_token": bool(str(cloud.get("access_token") or "").strip()),
|
|||
|
|
"base_url": str(cloud.get("base_url") or "").strip(),
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 7. 云端 (sakura_cloud) — JWT 安全核心
|
|||
|
|
|
|||
|
|
### 7.1 JWT 创建与验证 + 密码哈希
|
|||
|
|
|
|||
|
|
**文件:** `sakura_cloud/core/security.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
from datetime import datetime, timedelta, timezone
|
|||
|
|
from typing import Any
|
|||
|
|
|
|||
|
|
from jose import JWTError, jwt
|
|||
|
|
from passlib.context import CryptContext
|
|||
|
|
|
|||
|
|
from sakura_cloud.core.config import settings
|
|||
|
|
|
|||
|
|
# ── 密码哈希 ────────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
pwd_context = CryptContext(schemes=["pbkdf2_sha256", "bcrypt"], deprecated="auto")
|
|||
|
|
|
|||
|
|
def hash_password(password: str) -> str:
|
|||
|
|
return pwd_context.hash(password)
|
|||
|
|
|
|||
|
|
def verify_password(password: str, password_hash: str) -> bool:
|
|||
|
|
return pwd_context.verify(password, password_hash)
|
|||
|
|
|
|||
|
|
# ── JWT 创建 ────────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def create_token(
|
|||
|
|
subject: str, *, token_type: str, expires_delta: timedelta, token_version: int = 0
|
|||
|
|
) -> str:
|
|||
|
|
"""
|
|||
|
|
创建 JWT Token。
|
|||
|
|
payload: sub(用户ID), type(access/refresh), tv(token_version 用于即时吊销),
|
|||
|
|
iss, aud, iat, exp
|
|||
|
|
"""
|
|||
|
|
now = datetime.now(timezone.utc)
|
|||
|
|
payload: dict[str, Any] = {
|
|||
|
|
"sub": subject,
|
|||
|
|
"type": token_type,
|
|||
|
|
"tv": token_version,
|
|||
|
|
"iss": settings.jwt_issuer,
|
|||
|
|
"aud": settings.jwt_audience,
|
|||
|
|
"iat": int(now.timestamp()),
|
|||
|
|
"exp": int((now + expires_delta).timestamp()),
|
|||
|
|
}
|
|||
|
|
return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
|
|||
|
|
|
|||
|
|
def create_access_token(subject: str, token_version: int = 0) -> str:
|
|||
|
|
"""Access Token: 24 小时有效期"""
|
|||
|
|
return create_token(
|
|||
|
|
subject, token_type="access",
|
|||
|
|
expires_delta=timedelta(hours=settings.jwt_access_token_expire_hours),
|
|||
|
|
token_version=token_version,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def create_refresh_token(subject: str, token_version: int = 0) -> str:
|
|||
|
|
"""Refresh Token: 30 天有效期"""
|
|||
|
|
return create_token(
|
|||
|
|
subject, token_type="refresh",
|
|||
|
|
expires_delta=timedelta(days=settings.jwt_refresh_token_expire_days),
|
|||
|
|
token_version=token_version,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# ── JWT 解码与验证 ──────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def decode_token(token: str) -> dict[str, Any]:
|
|||
|
|
"""
|
|||
|
|
解码并验证 JWT。
|
|||
|
|
验证:签名、audience、issuer、exp、type 字段存在且合法。
|
|||
|
|
"""
|
|||
|
|
try:
|
|||
|
|
payload = jwt.decode(
|
|||
|
|
token,
|
|||
|
|
settings.jwt_secret_key,
|
|||
|
|
algorithms=[settings.jwt_algorithm],
|
|||
|
|
audience=settings.jwt_audience,
|
|||
|
|
issuer=settings.jwt_issuer,
|
|||
|
|
)
|
|||
|
|
except JWTError as exc:
|
|||
|
|
raise ValueError("Invalid token") from exc
|
|||
|
|
if "exp" not in payload:
|
|||
|
|
raise ValueError("Invalid token")
|
|||
|
|
if payload.get("type") not in {"access", "refresh"}:
|
|||
|
|
raise ValueError("Invalid token")
|
|||
|
|
return payload
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 8. 云端 (sakura_cloud) — 认证依赖注入
|
|||
|
|
|
|||
|
|
### 8.1 get_current_user 认证守卫
|
|||
|
|
|
|||
|
|
**文件:** `sakura_cloud/api/deps.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
from typing import Annotated
|
|||
|
|
from fastapi import Depends, HTTPException, status
|
|||
|
|
from fastapi.security import OAuth2PasswordBearer
|
|||
|
|
from sqlalchemy.orm import Session
|
|||
|
|
|
|||
|
|
from sakura_cloud.core.config import settings
|
|||
|
|
from sakura_cloud.core.security import decode_token
|
|||
|
|
from sakura_cloud.db.session import get_db
|
|||
|
|
from sakura_cloud.models.user import User, UserRole
|
|||
|
|
|
|||
|
|
# OAuth2 方案:Bearer Token 从 Authorization header 提取
|
|||
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.api_prefix}/auth/login")
|
|||
|
|
DbSession = Annotated[Session, Depends(get_db)]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def get_current_user(token: Annotated[str, Depends(oauth2_scheme)], db: DbSession) -> User:
|
|||
|
|
"""
|
|||
|
|
核心认证守卫。验证链:
|
|||
|
|
1. 解码 JWT → 2. 验证 type=="access" → 3. 验证 sub 存在
|
|||
|
|
→ 4. 查用户存在 → 5. 验证 is_active → 6. 验证 token_version 匹配
|
|||
|
|
"""
|
|||
|
|
try:
|
|||
|
|
payload = decode_token(token)
|
|||
|
|
except ValueError as exc:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token"
|
|||
|
|
) from exc
|
|||
|
|
|
|||
|
|
if payload.get("type") != "access":
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token type"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
user_id = payload.get("sub")
|
|||
|
|
if not user_id:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token subject"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
user = db.get(User, str(user_id))
|
|||
|
|
if user is None:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found"
|
|||
|
|
)
|
|||
|
|
if not user.is_active:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="User is disabled"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# token_version 不匹配 = Token 已被吊销
|
|||
|
|
if int(payload.get("tv") or 0) != int(user.token_version or 0):
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has been revoked"
|
|||
|
|
)
|
|||
|
|
return user
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 类型别名
|
|||
|
|
CurrentUser = Annotated[User, Depends(get_current_user)]
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ── 角色守卫 ────────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def require_admin_user(current_user: CurrentUser) -> User:
|
|||
|
|
if current_user.role not in {UserRole.ADMIN, UserRole.SUPER_ADMIN}:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_403_FORBIDDEN, detail="Admin privileges required"
|
|||
|
|
)
|
|||
|
|
return current_user
|
|||
|
|
|
|||
|
|
AdminUser = Annotated[User, Depends(require_admin_user)]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def require_super_admin_user(current_user: CurrentUser) -> User:
|
|||
|
|
if current_user.role != UserRole.SUPER_ADMIN:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|||
|
|
detail="Super admin privileges required",
|
|||
|
|
)
|
|||
|
|
return current_user
|
|||
|
|
|
|||
|
|
SuperAdminUser = Annotated[User, Depends(require_super_admin_user)]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def assert_owner_or_admin(resource_user_id: str, current_user: User) -> None:
|
|||
|
|
"""资源所有者或管理员可访问。"""
|
|||
|
|
if resource_user_id == current_user.id:
|
|||
|
|
return
|
|||
|
|
if current_user.role in {UserRole.ADMIN, UserRole.SUPER_ADMIN}:
|
|||
|
|
return
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_404_NOT_FOUND, detail="Resource not found"
|
|||
|
|
)
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 9. 云端 (sakura_cloud) — 认证 API 端点
|
|||
|
|
|
|||
|
|
### 9.1 注册 / 登录 / 登出 / 刷新
|
|||
|
|
|
|||
|
|
**文件:** `sakura_cloud/api/v1/endpoints/auth.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
from time import monotonic
|
|||
|
|
from fastapi import APIRouter, HTTPException, Request, status
|
|||
|
|
from sqlalchemy import func, or_, select
|
|||
|
|
|
|||
|
|
from sakura_cloud.api.deps import CurrentUser, DbSession
|
|||
|
|
from sakura_cloud.core.security import (
|
|||
|
|
create_access_token, create_refresh_token,
|
|||
|
|
decode_token, hash_password, verify_password,
|
|||
|
|
)
|
|||
|
|
from sakura_cloud.models.user import User
|
|||
|
|
from sakura_cloud.schemas.auth import (
|
|||
|
|
LoginRequest, RefreshRequest, RegisterRequest, TokenPair,
|
|||
|
|
)
|
|||
|
|
from sakura_cloud.schemas.common import ApiResponse
|
|||
|
|
from sakura_cloud.schemas.user import UserOut
|
|||
|
|
|
|||
|
|
router = APIRouter()
|
|||
|
|
_rate_buckets: dict[str, list[float]] = {}
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ── 简易内存速率限制 ─────────────────────────────────────────
|
|||
|
|
|
|||
|
|
def _rate_limit(request: Request, scope: str, *, limit=5, window_seconds=60) -> None:
|
|||
|
|
client_ip = request.client.host if request.client else "unknown"
|
|||
|
|
key = f"{scope}:{client_ip}"
|
|||
|
|
now = monotonic()
|
|||
|
|
bucket = [t for t in _rate_buckets.get(key, []) if now - t < window_seconds]
|
|||
|
|
if len(bucket) >= limit:
|
|||
|
|
_rate_buckets[key] = bucket
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|||
|
|
detail="Too many requests",
|
|||
|
|
)
|
|||
|
|
bucket.append(now)
|
|||
|
|
_rate_buckets[key] = bucket
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ── POST /auth/register ─────────────────────────────────────
|
|||
|
|
|
|||
|
|
@router.post("/register", response_model=ApiResponse[UserOut],
|
|||
|
|
status_code=status.HTTP_201_CREATED)
|
|||
|
|
def register(payload: RegisterRequest, request: Request, db: DbSession):
|
|||
|
|
"""注册新用户。无需认证。速率限制:5次/60秒。"""
|
|||
|
|
_rate_limit(request, "register")
|
|||
|
|
username = payload.username.strip()
|
|||
|
|
email = str(payload.email).strip().lower()
|
|||
|
|
|
|||
|
|
# 检查用户名 / 邮箱唯一性
|
|||
|
|
exists = db.scalar(
|
|||
|
|
select(User).where(
|
|||
|
|
or_(
|
|||
|
|
func.lower(User.username) == username.lower(),
|
|||
|
|
func.lower(User.email) == email,
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
if exists is not None:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_409_CONFLICT, detail="注册失败,请检查输入"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
user = User(
|
|||
|
|
username=username, email=email,
|
|||
|
|
password_hash=hash_password(payload.password),
|
|||
|
|
)
|
|||
|
|
db.add(user)
|
|||
|
|
db.commit()
|
|||
|
|
db.refresh(user)
|
|||
|
|
return ApiResponse(code=201, message="created", data=UserOut.model_validate(user))
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ── POST /auth/login ────────────────────────────────────────
|
|||
|
|
|
|||
|
|
@router.post("/login", response_model=ApiResponse[TokenPair])
|
|||
|
|
def login(payload: LoginRequest, request: Request, db: DbSession):
|
|||
|
|
"""
|
|||
|
|
用户登录。无需认证。速率限制:5次/60秒。
|
|||
|
|
成功登录会递增 token_version,使所有旧 Token 立即失效。
|
|||
|
|
"""
|
|||
|
|
_rate_limit(request, "login")
|
|||
|
|
login_id = payload.username_or_email.strip()
|
|||
|
|
|
|||
|
|
# 支持用户名或邮箱登录
|
|||
|
|
user = db.scalar(
|
|||
|
|
select(User).where(
|
|||
|
|
or_(
|
|||
|
|
func.lower(User.username) == login_id.lower(),
|
|||
|
|
func.lower(User.email) == login_id.lower(),
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
if user is None or not verify_password(payload.password, user.password_hash):
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 递增 token_version → 吊销所有旧 Token
|
|||
|
|
user.token_version += 1
|
|||
|
|
db.commit()
|
|||
|
|
db.refresh(user)
|
|||
|
|
|
|||
|
|
tokens = TokenPair(
|
|||
|
|
access_token=create_access_token(user.id, user.token_version),
|
|||
|
|
refresh_token=create_refresh_token(user.id, user.token_version),
|
|||
|
|
)
|
|||
|
|
return ApiResponse(data=tokens)
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ── POST /auth/logout ───────────────────────────────────────
|
|||
|
|
|
|||
|
|
@router.post("/logout", response_model=ApiResponse[dict[str, bool]])
|
|||
|
|
def logout(current_user: CurrentUser, db: DbSession):
|
|||
|
|
"""
|
|||
|
|
登出。需要认证。
|
|||
|
|
递增 token_version → 使所有 Token 立即失效。
|
|||
|
|
"""
|
|||
|
|
current_user.token_version += 1
|
|||
|
|
db.commit()
|
|||
|
|
return ApiResponse(data={"ok": True})
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ── POST /auth/refresh ──────────────────────────────────────
|
|||
|
|
|
|||
|
|
@router.post("/refresh", response_model=ApiResponse[TokenPair])
|
|||
|
|
def refresh(payload: RefreshRequest, request: Request, db: DbSession):
|
|||
|
|
"""
|
|||
|
|
Token 刷新。无需 Access Token,使用 Refresh Token。
|
|||
|
|
成功刷新会旋转 Token(递增 token_version),旧 Refresh Token 一次性失效。
|
|||
|
|
"""
|
|||
|
|
_rate_limit(request, "refresh")
|
|||
|
|
|
|||
|
|
# 1. 解码并验证 Refresh Token
|
|||
|
|
try:
|
|||
|
|
token_payload = decode_token(payload.refresh_token)
|
|||
|
|
except ValueError as exc:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token"
|
|||
|
|
) from exc
|
|||
|
|
|
|||
|
|
if token_payload.get("type") != "refresh":
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token type"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 2. 验证用户
|
|||
|
|
user_id = token_payload.get("sub")
|
|||
|
|
user = db.get(User, str(user_id)) if user_id else None
|
|||
|
|
if user is None:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found"
|
|||
|
|
)
|
|||
|
|
if not user.is_active:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="User is disabled"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 3. 验证 token_version(Refresh Token 是否已被吊销)
|
|||
|
|
if int(token_payload.get("tv") or 0) != int(user.token_version or 0):
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has been revoked"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 4. 旋转 Token
|
|||
|
|
user.token_version += 1
|
|||
|
|
db.commit()
|
|||
|
|
db.refresh(user)
|
|||
|
|
|
|||
|
|
tokens = TokenPair(
|
|||
|
|
access_token=create_access_token(user.id, user.token_version),
|
|||
|
|
refresh_token=create_refresh_token(user.id, user.token_version),
|
|||
|
|
)
|
|||
|
|
return ApiResponse(data=tokens)
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 10. 云端 (sakura_cloud) — 管理员登录
|
|||
|
|
|
|||
|
|
### 10.1 POST /admin/login
|
|||
|
|
|
|||
|
|
**文件:** `sakura_cloud/api/v1/endpoints/admin.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
from collections import defaultdict, deque
|
|||
|
|
|
|||
|
|
router = APIRouter()
|
|||
|
|
_login_attempts: dict[str, deque[float]] = defaultdict(deque)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _check_login_rate_limit(request: Request) -> None:
|
|||
|
|
"""管理员登录速率限制。"""
|
|||
|
|
key = request.client.host if request.client is not None else "unknown"
|
|||
|
|
now = time.time()
|
|||
|
|
attempts = _login_attempts[key]
|
|||
|
|
while attempts and now - attempts[0] > 60:
|
|||
|
|
attempts.popleft()
|
|||
|
|
if len(attempts) >= settings.admin_login_rate_limit_per_minute:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|||
|
|
detail="Too many requests",
|
|||
|
|
)
|
|||
|
|
attempts.append(now)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/login", response_model=ApiResponse[TokenPair])
|
|||
|
|
def admin_login(payload: AdminLoginRequest, request: Request, db: DbSession):
|
|||
|
|
"""
|
|||
|
|
管理员登录。无需认证。
|
|||
|
|
额外检查:用户角色必须是 ADMIN 或 SUPER_ADMIN。
|
|||
|
|
"""
|
|||
|
|
_check_login_rate_limit(request)
|
|||
|
|
login_id = payload.username_or_email.strip()
|
|||
|
|
user = db.scalar(
|
|||
|
|
select(User).where(
|
|||
|
|
or_(
|
|||
|
|
func.lower(User.username) == login_id.lower(),
|
|||
|
|
func.lower(User.email) == login_id.lower(),
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
# 四项校验:用户存在 + 是管理员 + 账号启用 + 密码正确
|
|||
|
|
if (
|
|||
|
|
user is None
|
|||
|
|
or user.role not in {UserRole.ADMIN, UserRole.SUPER_ADMIN}
|
|||
|
|
or not user.is_active
|
|||
|
|
or not verify_password(payload.password, user.password_hash)
|
|||
|
|
):
|
|||
|
|
raise HTTPException(
|
|||
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid admin credentials"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 吊销旧 Token + 签发新 Token
|
|||
|
|
user.token_version += 1
|
|||
|
|
db.commit()
|
|||
|
|
db.refresh(user)
|
|||
|
|
|
|||
|
|
# 记录审计日志
|
|||
|
|
write_admin_audit_log(
|
|||
|
|
db, user, action="admin_login", target_type="user",
|
|||
|
|
target_id=user.id, request=request,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
return ApiResponse(data=TokenPair(
|
|||
|
|
access_token=create_access_token(user.id, user.token_version),
|
|||
|
|
refresh_token=create_refresh_token(user.id, user.token_version),
|
|||
|
|
))
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 11. 云端 (sakura_cloud) — 数据模型 & 请求模型
|
|||
|
|
|
|||
|
|
### 11.1 User 模型(认证相关字段)
|
|||
|
|
|
|||
|
|
**文件:** `sakura_cloud/models/user.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
class UserRole(str, Enum):
|
|||
|
|
ADMIN = "admin"
|
|||
|
|
SUPER_ADMIN = "super_admin"
|
|||
|
|
USER = "user"
|
|||
|
|
|
|||
|
|
class User(UUIDPrimaryKeyMixin, TimestampMixin, Base):
|
|||
|
|
__tablename__ = "users"
|
|||
|
|
|
|||
|
|
username: Mapped[str] # 用户名 (unique)
|
|||
|
|
email: Mapped[str] # 邮箱 (unique)
|
|||
|
|
password_hash: Mapped[str] # 密码哈希
|
|||
|
|
role: Mapped[UserRole] # 角色 (USER/ADMIN/SUPER_ADMIN)
|
|||
|
|
is_active: Mapped[bool] # 账号启用状态 (默认 True)
|
|||
|
|
token_version: Mapped[int] # Token 版本号 (用于即时吊销, 默认 0)
|
|||
|
|
# ... 其他字段省略
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 11.2 认证请求/响应 Schema
|
|||
|
|
|
|||
|
|
**文件:** `sakura_cloud/schemas/auth.py`
|
|||
|
|
|
|||
|
|
```python
|
|||
|
|
from pydantic import BaseModel, EmailStr, Field, field_validator
|
|||
|
|
|
|||
|
|
class RegisterRequest(BaseModel):
|
|||
|
|
username: str = Field(min_length=3, max_length=50)
|
|||
|
|
email: EmailStr
|
|||
|
|
password: str = Field(min_length=8, max_length=128)
|
|||
|
|
|
|||
|
|
@field_validator("username", mode="before")
|
|||
|
|
@classmethod
|
|||
|
|
def normalize_username(cls, value: str) -> str:
|
|||
|
|
return value.strip() if isinstance(value, str) else value
|
|||
|
|
|
|||
|
|
@field_validator("email", mode="before")
|
|||
|
|
@classmethod
|
|||
|
|
def normalize_email(cls, value: object) -> object:
|
|||
|
|
return value.strip().lower() if isinstance(value, str) else value
|
|||
|
|
|
|||
|
|
|
|||
|
|
class LoginRequest(BaseModel):
|
|||
|
|
username_or_email: str
|
|||
|
|
password: str
|
|||
|
|
|
|||
|
|
@field_validator("username_or_email", mode="before")
|
|||
|
|
@classmethod
|
|||
|
|
def normalize_login_id(cls, value: str) -> str:
|
|||
|
|
return value.strip() if isinstance(value, str) else value
|
|||
|
|
|
|||
|
|
|
|||
|
|
class RefreshRequest(BaseModel):
|
|||
|
|
refresh_token: str
|
|||
|
|
|
|||
|
|
|
|||
|
|
class TokenPair(BaseModel):
|
|||
|
|
access_token: str
|
|||
|
|
refresh_token: str
|
|||
|
|
token_type: str = "bearer"
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 12. 手机端 (sakura_mobile) — Flutter 认证
|
|||
|
|
|
|||
|
|
### 12.1 会话状态与控制器
|
|||
|
|
|
|||
|
|
**文件:** `sakura_mobile/lib/src/core/session.dart`
|
|||
|
|
|
|||
|
|
```dart
|
|||
|
|
import 'package:dio/dio.dart';
|
|||
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|||
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|||
|
|
|
|||
|
|
import 'api_client.dart';
|
|||
|
|
import 'push_notifications.dart';
|
|||
|
|
|
|||
|
|
// ── 会话状态 ──────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
class SessionState {
|
|||
|
|
final String baseUrl;
|
|||
|
|
final String accessToken;
|
|||
|
|
final String username;
|
|||
|
|
final bool loading;
|
|||
|
|
final String? error;
|
|||
|
|
|
|||
|
|
const SessionState({
|
|||
|
|
required this.baseUrl,
|
|||
|
|
required this.accessToken,
|
|||
|
|
this.username = '',
|
|||
|
|
this.loading = false,
|
|||
|
|
this.error,
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
/// 核心登录状态判断:accessToken 非空即视为已登录
|
|||
|
|
bool get signedIn => accessToken.isNotEmpty;
|
|||
|
|
|
|||
|
|
SessionState copyWith({...}) { ... }
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ── 会话控制器 ────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
class SessionController extends StateNotifier<SessionState> {
|
|||
|
|
SessionController()
|
|||
|
|
: super(const SessionState(
|
|||
|
|
baseUrl: defaultCloudApi, accessToken: '', loading: true)) {
|
|||
|
|
_load();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// SharedPreferences 存储键
|
|||
|
|
static const _baseUrlKey = 'sakura.baseUrl';
|
|||
|
|
static const _accessTokenKey = 'sakura.accessToken';
|
|||
|
|
static const _usernameKey = 'sakura.username';
|
|||
|
|
|
|||
|
|
// ── 启动时加载会话 ───────────────────────────────────────
|
|||
|
|
|
|||
|
|
Future<void> _load() async {
|
|||
|
|
final prefs = await SharedPreferences.getInstance();
|
|||
|
|
final baseUrl = prefs.getString(_baseUrlKey) ?? defaultCloudApi;
|
|||
|
|
final accessToken = prefs.getString(_accessTokenKey) ?? '';
|
|||
|
|
final username = prefs.getString(_usernameKey) ?? '';
|
|||
|
|
|
|||
|
|
// 验证存储的 Token 是否仍然有效
|
|||
|
|
final validatedUsername = await _validateStoredSession(
|
|||
|
|
baseUrl: baseUrl, accessToken: accessToken, username: username,
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
state = SessionState(
|
|||
|
|
baseUrl: baseUrl,
|
|||
|
|
accessToken: validatedUsername == null ? '' : accessToken,
|
|||
|
|
username: validatedUsername ?? '',
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
if (state.signedIn) {
|
|||
|
|
await PushNotifications.registerWithSession(
|
|||
|
|
baseUrl: state.baseUrl, accessToken: state.accessToken,
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
SakuraApiClient client() =>
|
|||
|
|
SakuraApiClient(baseUrl: state.baseUrl, token: state.accessToken);
|
|||
|
|
|
|||
|
|
// ── 登录 ─────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
Future<void> login(String usernameOrEmail, String password) async {
|
|||
|
|
state = state.copyWith(loading: true, error: null);
|
|||
|
|
try {
|
|||
|
|
// 1. 调用登录 API
|
|||
|
|
final api = SakuraApiClient(baseUrl: state.baseUrl);
|
|||
|
|
final tokens = await api.login(usernameOrEmail, password);
|
|||
|
|
final accessToken = tokens['access_token']?.toString() ?? '';
|
|||
|
|
|
|||
|
|
// 2. 清除旧认证信息
|
|||
|
|
final prefs = await SharedPreferences.getInstance();
|
|||
|
|
await _clearAuthPrefs(prefs);
|
|||
|
|
|
|||
|
|
// 3. 用新 Token 获取当前用户信息
|
|||
|
|
final authedApi = SakuraApiClient(
|
|||
|
|
baseUrl: state.baseUrl, token: accessToken);
|
|||
|
|
final me = await authedApi.me();
|
|||
|
|
final username = me['username']?.toString() ?? '';
|
|||
|
|
|
|||
|
|
if (username.isEmpty) {
|
|||
|
|
throw Exception('登录成功但无法获取用户身份信息。');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 4. 持久化到 SharedPreferences
|
|||
|
|
await prefs.setString(_accessTokenKey, accessToken);
|
|||
|
|
await prefs.setString(_usernameKey, username);
|
|||
|
|
|
|||
|
|
state = state.copyWith(
|
|||
|
|
accessToken: accessToken, username: username,
|
|||
|
|
loading: false, error: null,
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
// 5. 注册推送通知
|
|||
|
|
await PushNotifications.registerWithSession(
|
|||
|
|
baseUrl: state.baseUrl, accessToken: accessToken,
|
|||
|
|
);
|
|||
|
|
} catch (error) {
|
|||
|
|
state = state.copyWith(loading: false, error: _friendlyError(error));
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ── 注册 ─────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
Future<void> register(String username, String email, String password) async {
|
|||
|
|
state = state.copyWith(loading: true, error: null);
|
|||
|
|
try {
|
|||
|
|
final api = SakuraApiClient(baseUrl: state.baseUrl);
|
|||
|
|
await api.register(username, email, password);
|
|||
|
|
state = state.copyWith(loading: false, error: null);
|
|||
|
|
} catch (error) {
|
|||
|
|
state = state.copyWith(loading: false, error: _friendlyError(error));
|
|||
|
|
rethrow;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ── 登出 ─────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
Future<void> logout() async {
|
|||
|
|
await PushNotifications.unregisterWithSession(
|
|||
|
|
baseUrl: state.baseUrl, accessToken: state.accessToken,
|
|||
|
|
);
|
|||
|
|
final prefs = await SharedPreferences.getInstance();
|
|||
|
|
await _clearAuthPrefs(prefs);
|
|||
|
|
state = state.copyWith(accessToken: '', username: '', error: null);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ── 验证存储的会话(启动时调用) ──────────────────────────
|
|||
|
|
|
|||
|
|
Future<String?> _validateStoredSession({
|
|||
|
|
required String baseUrl,
|
|||
|
|
required String accessToken,
|
|||
|
|
required String username,
|
|||
|
|
}) async {
|
|||
|
|
if (accessToken.isEmpty) return null;
|
|||
|
|
|
|||
|
|
final prefs = await SharedPreferences.getInstance();
|
|||
|
|
if (username.isEmpty) {
|
|||
|
|
await _clearAuthPrefs(prefs);
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
// 调用 /api/v1/users/me 验证 Token 是否仍然有效
|
|||
|
|
final api = SakuraApiClient(baseUrl: baseUrl, token: accessToken);
|
|||
|
|
final me = await api.me();
|
|||
|
|
final actualUsername = me['username']?.toString() ?? '';
|
|||
|
|
|
|||
|
|
if (actualUsername.isEmpty || actualUsername != username) {
|
|||
|
|
await _clearAuthPrefs(prefs);
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
return actualUsername;
|
|||
|
|
} catch (_) {
|
|||
|
|
// 任何异常(网络错误、401 等)都清除认证状态
|
|||
|
|
await _clearAuthPrefs(prefs);
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Future<void> _clearAuthPrefs(SharedPreferences prefs) async {
|
|||
|
|
await prefs.remove(_accessTokenKey);
|
|||
|
|
await prefs.remove(_usernameKey);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 12.2 API 客户端(Token 管理与登录接口)
|
|||
|
|
|
|||
|
|
**文件:** `sakura_mobile/lib/src/core/api_client.dart`
|
|||
|
|
|
|||
|
|
```dart
|
|||
|
|
import 'package:dio/dio.dart';
|
|||
|
|
|
|||
|
|
const defaultCloudApi = 'http://api.kunkunxiaomao.top:8000';
|
|||
|
|
|
|||
|
|
class SakuraApiClient {
|
|||
|
|
SakuraApiClient({String baseUrl = defaultCloudApi, String token = ''})
|
|||
|
|
: dio = Dio(BaseOptions(
|
|||
|
|
baseUrl: baseUrl,
|
|||
|
|
connectTimeout: const Duration(seconds: 12),
|
|||
|
|
receiveTimeout: const Duration(seconds: 30),
|
|||
|
|
)) {
|
|||
|
|
if (token.isNotEmpty) {
|
|||
|
|
setToken(token);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
final Dio dio;
|
|||
|
|
|
|||
|
|
// ── Token 管理 ─────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
String get token {
|
|||
|
|
final value = dio.options.headers['Authorization']?.toString() ?? '';
|
|||
|
|
return value.startsWith('Bearer ') ? value.substring(7) : '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
void setToken(String token) {
|
|||
|
|
if (token.isEmpty) {
|
|||
|
|
dio.options.headers.remove('Authorization');
|
|||
|
|
} else {
|
|||
|
|
dio.options.headers['Authorization'] = 'Bearer $token';
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Map<String, String> authHeaders() {
|
|||
|
|
final value = dio.options.headers['Authorization']?.toString();
|
|||
|
|
return value == null || value.isEmpty
|
|||
|
|
? const {}
|
|||
|
|
: {'Authorization': value};
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ── 认证 API ────────────────────────────────────────────────
|
|||
|
|
|
|||
|
|
/// POST /api/v1/auth/login
|
|||
|
|
Future<Map<String, dynamic>> login(
|
|||
|
|
String usernameOrEmail, String password) async {
|
|||
|
|
final response = await dio.post(
|
|||
|
|
'/api/v1/auth/login',
|
|||
|
|
data: {'username_or_email': usernameOrEmail, 'password': password},
|
|||
|
|
);
|
|||
|
|
return response.data['data'] as Map<String, dynamic>;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// POST /api/v1/auth/register
|
|||
|
|
Future<Map<String, dynamic>> register(
|
|||
|
|
String username, String email, String password) async {
|
|||
|
|
final response = await dio.post(
|
|||
|
|
'/api/v1/auth/register',
|
|||
|
|
data: {'username': username, 'email': email, 'password': password},
|
|||
|
|
);
|
|||
|
|
return response.data['data'] as Map<String, dynamic>;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// GET /api/v1/users/me — 获取当前用户信息
|
|||
|
|
Future<Map<String, dynamic>> me() async { ... }
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 12.3 Riverpod 依赖注入
|
|||
|
|
|
|||
|
|
**文件:** `sakura_mobile/lib/src/core/providers.dart`
|
|||
|
|
|
|||
|
|
```dart
|
|||
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|||
|
|
import 'api_client.dart';
|
|||
|
|
import 'session.dart';
|
|||
|
|
|
|||
|
|
// 全局会话状态
|
|||
|
|
final sessionProvider =
|
|||
|
|
StateNotifierProvider<SessionController, SessionState>(
|
|||
|
|
(ref) => SessionController());
|
|||
|
|
|
|||
|
|
// API 客户端(随 sessionProvider 变化自动重建)
|
|||
|
|
final apiClientProvider = Provider<SakuraApiClient>((ref) {
|
|||
|
|
ref.watch(sessionProvider);
|
|||
|
|
return ref.read(sessionProvider.notifier).client();
|
|||
|
|
});
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 12.4 登录页面
|
|||
|
|
|
|||
|
|
**文件:** `sakura_mobile/lib/src/pages/login_page.dart`
|
|||
|
|
|
|||
|
|
```dart
|
|||
|
|
class LoginPage extends ConsumerStatefulWidget { ... }
|
|||
|
|
|
|||
|
|
class _LoginPageState extends ConsumerState<LoginPage>
|
|||
|
|
with SingleTickerProviderStateMixin {
|
|||
|
|
// 登录/注册表单提交
|
|||
|
|
Future<void> _submitLogin() async {
|
|||
|
|
final loginId = account.text.trim();
|
|||
|
|
final pwd = password.text;
|
|||
|
|
if (loginId.isEmpty || pwd.isEmpty) {
|
|||
|
|
_showMessage('请输入账号和密码。', isError: true);
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
final notifier = ref.read(sessionProvider.notifier);
|
|||
|
|
notifier.clearError();
|
|||
|
|
await notifier.login(loginId, pwd);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Future<void> _submitRegister() async {
|
|||
|
|
// ... 校验用户名/邮箱/密码 ...
|
|||
|
|
await notifier.register(username, email, pwd);
|
|||
|
|
// 注册成功 → 切换到登录标签页
|
|||
|
|
_tabController.animateTo(0);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 12.5 首页认证守卫
|
|||
|
|
|
|||
|
|
**文件:** `sakura_mobile/lib/src/pages/home_page.dart`
|
|||
|
|
|
|||
|
|
```dart
|
|||
|
|
@override
|
|||
|
|
Widget build(BuildContext context) {
|
|||
|
|
final session = ref.watch(sessionProvider);
|
|||
|
|
|
|||
|
|
// 加载中 → 显示加载指示器
|
|||
|
|
if (session.loading) {
|
|||
|
|
return const Scaffold(
|
|||
|
|
body: Center(child: CircularProgressIndicator()));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 未登录 → 显示登录页
|
|||
|
|
if (!session.signedIn) {
|
|||
|
|
return const LoginPage();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 已登录 → 显示主界面
|
|||
|
|
return Scaffold(body: SafeArea(child: AnimatedSwitcher(...)));
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 13. 管理后台 (sakura_admin_web) — Vue 认证
|
|||
|
|
|
|||
|
|
### 13.1 会话状态管理
|
|||
|
|
|
|||
|
|
**文件:** `sakura_admin_web/src/stores/session.ts`
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import { reactive } from "vue";
|
|||
|
|
|
|||
|
|
export type Role = "user" | "admin" | "super_admin";
|
|||
|
|
|
|||
|
|
export interface CurrentUser {
|
|||
|
|
id: string;
|
|||
|
|
username: string;
|
|||
|
|
email: string;
|
|||
|
|
role: Role;
|
|||
|
|
is_active: boolean;
|
|||
|
|
storage_used: number;
|
|||
|
|
storage_limit: number;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const ACCESS_KEY = "sakura_access_token";
|
|||
|
|
const REFRESH_KEY = "sakura_refresh_token";
|
|||
|
|
|
|||
|
|
// 响应式认证状态(初始值从 sessionStorage 读取)
|
|||
|
|
export const authState = reactive({
|
|||
|
|
accessToken: sessionStorage.getItem(ACCESS_KEY) || "",
|
|||
|
|
refreshToken: sessionStorage.getItem(REFRESH_KEY) || "",
|
|||
|
|
user: null as CurrentUser | null,
|
|||
|
|
loading: false,
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
export function saveSession(accessToken: string, refreshToken: string) {
|
|||
|
|
authState.accessToken = accessToken;
|
|||
|
|
authState.refreshToken = refreshToken;
|
|||
|
|
sessionStorage.setItem(ACCESS_KEY, accessToken);
|
|||
|
|
sessionStorage.setItem(REFRESH_KEY, refreshToken);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export function clearSession() {
|
|||
|
|
authState.accessToken = "";
|
|||
|
|
authState.refreshToken = "";
|
|||
|
|
authState.user = null;
|
|||
|
|
sessionStorage.removeItem(ACCESS_KEY);
|
|||
|
|
sessionStorage.removeItem(REFRESH_KEY);
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 13.2 认证操作(登录/注册/登出/加载用户)
|
|||
|
|
|
|||
|
|
**文件:** `sakura_admin_web/src/stores/auth.ts`
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import { apiData, http } from "../api/http";
|
|||
|
|
import { authState, clearSession, saveSession,
|
|||
|
|
type CurrentUser, type Role } from "./session";
|
|||
|
|
|
|||
|
|
export { authState, clearSession, saveSession };
|
|||
|
|
|
|||
|
|
/** 登录(普通用户 / 管理员) */
|
|||
|
|
export async function login(
|
|||
|
|
usernameOrEmail: string, password: string, admin = false) {
|
|||
|
|
const path = admin ? "/admin/login" : "/auth/login";
|
|||
|
|
const response = await http.post(path, {
|
|||
|
|
username_or_email: usernameOrEmail, password,
|
|||
|
|
});
|
|||
|
|
const tokens = apiData<{ access_token: string; refresh_token: string }>(response);
|
|||
|
|
saveSession(tokens.access_token, tokens.refresh_token);
|
|||
|
|
await loadMe();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 注册后自动登录 */
|
|||
|
|
export async function register(
|
|||
|
|
username: string, email: string, password: string) {
|
|||
|
|
await http.post("/auth/register", { username, email, password });
|
|||
|
|
await login(username, password);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 加载当前用户信息(GET /me) */
|
|||
|
|
export async function loadMe(force = false) {
|
|||
|
|
if (authState.user && !force) return authState.user;
|
|||
|
|
if (!authState.accessToken) return null;
|
|||
|
|
authState.loading = true;
|
|||
|
|
try {
|
|||
|
|
const response = await http.get("/me");
|
|||
|
|
authState.user = apiData<CurrentUser>(response);
|
|||
|
|
return authState.user;
|
|||
|
|
} finally {
|
|||
|
|
authState.loading = false;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 登出 */
|
|||
|
|
export async function logout() {
|
|||
|
|
try {
|
|||
|
|
await http.post("/auth/logout");
|
|||
|
|
} finally {
|
|||
|
|
clearSession();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export function isAdmin(role?: Role | null) {
|
|||
|
|
return role === "admin" || role === "super_admin";
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 13.3 HTTP 拦截器(自动 Bearer Token + 401 刷新)
|
|||
|
|
|
|||
|
|
**文件:** `sakura_admin_web/src/api/http.ts`
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import axios, { type AxiosError } from "axios";
|
|||
|
|
import { authState, clearSession, saveSession } from "../stores/session";
|
|||
|
|
|
|||
|
|
const API_BASE = import.meta.env.VITE_API_BASE_URL || "/api/v1";
|
|||
|
|
|
|||
|
|
export const http = axios.create({
|
|||
|
|
baseURL: API_BASE,
|
|||
|
|
timeout: 15000,
|
|||
|
|
withCredentials: false,
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// ── 请求拦截器:自动附加 Bearer Token ──────────────────────────
|
|||
|
|
|
|||
|
|
http.interceptors.request.use((config) => {
|
|||
|
|
if (authState.accessToken) {
|
|||
|
|
config.headers.Authorization = `Bearer ${authState.accessToken}`;
|
|||
|
|
}
|
|||
|
|
return config;
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// ── 响应拦截器:401 自动刷新 Token 并重试 ─────────────────────
|
|||
|
|
|
|||
|
|
let refreshing: Promise<void> | null = null;
|
|||
|
|
|
|||
|
|
http.interceptors.response.use(
|
|||
|
|
(response) => response,
|
|||
|
|
async (error: AxiosError) => {
|
|||
|
|
const original = error.config;
|
|||
|
|
if (
|
|||
|
|
!original ||
|
|||
|
|
error.response?.status !== 401 ||
|
|||
|
|
!authState.refreshToken ||
|
|||
|
|
original.headers?.["X-Retry"]
|
|||
|
|
) {
|
|||
|
|
throw error; // 不满足刷新条件,直接抛出
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 防止并发重复刷新
|
|||
|
|
refreshing ||= http
|
|||
|
|
.post("/auth/refresh",
|
|||
|
|
{ refresh_token: authState.refreshToken },
|
|||
|
|
{ headers: { "X-Retry": "1" } }
|
|||
|
|
)
|
|||
|
|
.then((response) => {
|
|||
|
|
const tokens = response.data?.data;
|
|||
|
|
saveSession(tokens.access_token, tokens.refresh_token);
|
|||
|
|
})
|
|||
|
|
.catch((refreshError) => {
|
|||
|
|
clearSession(); // 刷新失败 → 清除登录态
|
|||
|
|
throw refreshError;
|
|||
|
|
})
|
|||
|
|
.finally(() => {
|
|||
|
|
refreshing = null;
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
await refreshing;
|
|||
|
|
|
|||
|
|
// 用新 Token 重试原始请求
|
|||
|
|
original.headers = {
|
|||
|
|
...(original.headers as Record<string, string>),
|
|||
|
|
Authorization: `Bearer ${authState.accessToken}`,
|
|||
|
|
"X-Retry": "1",
|
|||
|
|
} as any;
|
|||
|
|
return http(original);
|
|||
|
|
}
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
export function apiData<T>(response: { data: { data: T } }): T {
|
|||
|
|
return response.data.data;
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 13.4 路由守卫
|
|||
|
|
|
|||
|
|
**文件:** `sakura_admin_web/src/router/index.ts`
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import { createRouter, createWebHistory } from "vue-router";
|
|||
|
|
import { authState, isAdmin, loadMe } from "../stores/auth";
|
|||
|
|
|
|||
|
|
const PUBLIC_PATHS = new Set([
|
|||
|
|
"/login", "/register", "/forgot-password", "/403", "/404",
|
|||
|
|
]);
|
|||
|
|
|
|||
|
|
function isPublicPath(path: string) {
|
|||
|
|
return PUBLIC_PATHS.has(path);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
router.beforeEach(async (to) => {
|
|||
|
|
// 公开页面:如果已有 Token,尝试加载用户后重定向
|
|||
|
|
if (isPublicPath(to.path)) {
|
|||
|
|
if ((to.path === "/login" || to.path === "/register")
|
|||
|
|
&& authState.accessToken) {
|
|||
|
|
const user = await loadMe().catch(() => null);
|
|||
|
|
if (user) return isAdmin(user.role) ? "/admin" : "/app";
|
|||
|
|
}
|
|||
|
|
return true;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 非公开页面:不需要认证则放行
|
|||
|
|
if (!to.meta.requiresAuth) return true;
|
|||
|
|
|
|||
|
|
// 需要认证:加载用户信息
|
|||
|
|
const user = await loadMe().catch(() => null);
|
|||
|
|
if (!user) {
|
|||
|
|
// 未认证 → 重定向到登录页
|
|||
|
|
return { path: "/login", query: { redirect: to.fullPath } };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 需要管理员权限
|
|||
|
|
if (to.meta.requiresAdmin && !isAdmin(authState.user?.role)) {
|
|||
|
|
return "/403";
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return true;
|
|||
|
|
});
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 13.5 登录页面
|
|||
|
|
|
|||
|
|
**文件:** `sakura_admin_web/src/views/public/LoginPage.vue`
|
|||
|
|
|
|||
|
|
```vue
|
|||
|
|
<template>
|
|||
|
|
<main class="auth-shell">
|
|||
|
|
<section class="auth-panel">
|
|||
|
|
<p class="eyebrow">Sakura Cloud</p>
|
|||
|
|
<h1>登录</h1>
|
|||
|
|
<form @submit.prevent="submit">
|
|||
|
|
<label>
|
|||
|
|
账号或邮箱
|
|||
|
|
<input v-model.trim="form.username" autocomplete="username" required />
|
|||
|
|
</label>
|
|||
|
|
<label>
|
|||
|
|
密码
|
|||
|
|
<input v-model="form.password" type="password"
|
|||
|
|
autocomplete="current-password" required />
|
|||
|
|
</label>
|
|||
|
|
<label class="row small">
|
|||
|
|
<input v-model="form.admin" type="checkbox" />
|
|||
|
|
管理员登录
|
|||
|
|
</label>
|
|||
|
|
<button class="primary" :disabled="loading">
|
|||
|
|
{{ loading ? "登录中..." : "登录" }}
|
|||
|
|
</button>
|
|||
|
|
</form>
|
|||
|
|
<p v-if="error" class="error">{{ error }}</p>
|
|||
|
|
<nav class="auth-links">
|
|||
|
|
<RouterLink to="/register">注册账号</RouterLink>
|
|||
|
|
<RouterLink to="/forgot-password">忘记密码</RouterLink>
|
|||
|
|
</nav>
|
|||
|
|
</section>
|
|||
|
|
</main>
|
|||
|
|
</template>
|
|||
|
|
|
|||
|
|
<script setup lang="ts">
|
|||
|
|
import { reactive, ref } from "vue";
|
|||
|
|
import { useRoute, useRouter } from "vue-router";
|
|||
|
|
import { authState, isAdmin, login } from "../../stores/auth";
|
|||
|
|
|
|||
|
|
const router = useRouter();
|
|||
|
|
const route = useRoute();
|
|||
|
|
const loading = ref(false);
|
|||
|
|
const error = ref("");
|
|||
|
|
const form = reactive({ username: "", password: "", admin: false });
|
|||
|
|
|
|||
|
|
async function submit() {
|
|||
|
|
error.value = "";
|
|||
|
|
loading.value = true;
|
|||
|
|
try {
|
|||
|
|
await login(form.username, form.password, form.admin);
|
|||
|
|
const redirect = String(route.query.redirect || "");
|
|||
|
|
await router.push(
|
|||
|
|
redirect || (isAdmin(authState.user?.role) ? "/admin" : "/app")
|
|||
|
|
);
|
|||
|
|
} catch {
|
|||
|
|
error.value = "账号、密码或权限不正确";
|
|||
|
|
} finally {
|
|||
|
|
loading.value = false;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
</script>
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 14. 认证流程总结
|
|||
|
|
|
|||
|
|
### 14.1 Pixiv 认证(桌面端)
|
|||
|
|
|
|||
|
|
```
|
|||
|
|
┌──────────────┐ ┌─────────────────┐ ┌──────────────────┐
|
|||
|
|
│ Cookie 导入 │────▶│ validate_cookie │────▶│ 访问设置页验证 │
|
|||
|
|
│ (cookies.txt) │ │ (AuthClient) │ │ 是否被重定向 │
|
|||
|
|
└──────────────┘ └─────────────────┘ └──────────────────┘
|
|||
|
|
│ │
|
|||
|
|
┌───────┴───────┐ ┌──────┴──────┐
|
|||
|
|
│ 有效 → 保存 │ │ 失效 → 提示 │
|
|||
|
|
│ SessionStore │ │ 重新导入 │
|
|||
|
|
└───────────────┘ └─────────────┘
|
|||
|
|
|
|||
|
|
┌──────────────┐ ┌─────────────────┐ ┌──────────────────┐
|
|||
|
|
│ 密码登录 │────▶│ 提取 CSRF Token │────▶│ POST 登录 AJAX │
|
|||
|
|
│ │ │ (_extract_tt) │ │ + 提取 Cookie │
|
|||
|
|
└──────────────┘ └─────────────────┘ └──────────────────┘
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 14.2 Sakura Cloud JWT 认证(全平台)
|
|||
|
|
|
|||
|
|
```
|
|||
|
|
┌─────────────────────────────────────────────────────────────────┐
|
|||
|
|
│ Token 生命周期 │
|
|||
|
|
├─────────────────────────────────────────────────────────────────┤
|
|||
|
|
│ │
|
|||
|
|
│ 注册 登录 使用 │
|
|||
|
|
│ POST /register ──▶ POST /login ──▶ 返回 TokenPair │
|
|||
|
|
│ token_version++ access_token (24h) │
|
|||
|
|
│ refresh_token (30d) │
|
|||
|
|
│ │ │
|
|||
|
|
│ ┌───────────────────────────┘ │
|
|||
|
|
│ ▼ │
|
|||
|
|
│ 每次 API 请求 │
|
|||
|
|
│ Authorization: Bearer <access_token> │
|
|||
|
|
│ │ │
|
|||
|
|
│ ▼ │
|
|||
|
|
│ get_current_user() │
|
|||
|
|
│ 1. decode_token() — 验证签名/过期 │
|
|||
|
|
│ 2. type == "access" — 验证 Token 类型 │
|
|||
|
|
│ 3. user exists — 验证用户存在 │
|
|||
|
|
│ 4. user.is_active — 验证账号启用 │
|
|||
|
|
│ 5. tv == user.token_version — 验证未吊销 │
|
|||
|
|
│ │ │
|
|||
|
|
│ ┌────────┴────────┐ │
|
|||
|
|
│ ▼ ▼ │
|
|||
|
|
│ 通过 401/过期 │
|
|||
|
|
│ │ │
|
|||
|
|
│ ▼ │
|
|||
|
|
│ POST /refresh │
|
|||
|
|
│ token_version++ │
|
|||
|
|
│ 返回新 TokenPair │
|
|||
|
|
│ │
|
|||
|
|
│ 登出 / 改密码 / 管理员操作 → token_version++ → 所有旧 Token 失效 │
|
|||
|
|
│ │
|
|||
|
|
└─────────────────────────────────────────────────────────────────┘
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 14.3 桌面端 Cloud Token 管理流程
|
|||
|
|
|
|||
|
|
```
|
|||
|
|
GUI 启动
|
|||
|
|
│
|
|||
|
|
▼
|
|||
|
|
load_saved_session() ← 从 pixiv_app_session.json 读取
|
|||
|
|
│
|
|||
|
|
▼
|
|||
|
|
CloudSession().configure(...) ← 同步到全局单例
|
|||
|
|
│
|
|||
|
|
▼
|
|||
|
|
CloudSession().add_listener(_on_cloud_token_refreshed)
|
|||
|
|
│
|
|||
|
|
▼
|
|||
|
|
每次创建 SakuraCloudClient 时:
|
|||
|
|
│
|
|||
|
|
├─ CloudSession.get_config()
|
|||
|
|
│ └─ access_token 临近过期 (< 5min)?
|
|||
|
|
│ └─ YES → try_refresh()
|
|||
|
|
│
|
|||
|
|
├─ API 请求返回 401?
|
|||
|
|
│ └─ YES → SakuraCloudClient._try_refresh_token()
|
|||
|
|
│ └─ 委托给 CloudSession.try_refresh()
|
|||
|
|
│ ├─ 成功 → 更新内存 + 写盘 + 通知 GUI
|
|||
|
|
│ └─ 失败 → 清空 token + 通知 GUI "已过期"
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 14.4 各平台 Token 存储方式
|
|||
|
|
|
|||
|
|
| 平台 | 存储方式 | 存储内容 |
|
|||
|
|
|------|---------|---------|
|
|||
|
|
| 桌面端 (Python) | `pixiv_app_session.json` | Pixiv Cookie + Cloud JWT Token Pair + 登录模式 |
|
|||
|
|
| 云端 (FastAPI) | 无状态(JWT 自包含) | Token 内嵌 user_id, token_version, exp |
|
|||
|
|
| 手机端 (Flutter) | `SharedPreferences` | `sakura.accessToken` + `sakura.username` |
|
|||
|
|
| 管理后台 (Vue) | `sessionStorage` | `sakura_access_token` + `sakura_refresh_token` |
|
|||
|
|
|
|||
|
|
### 14.5 Token 刷新机制对比
|
|||
|
|
|
|||
|
|
| 平台 | 刷新方式 | 触发条件 |
|
|||
|
|
|------|---------|---------|
|
|||
|
|
| 桌面端 CloudSession | 主动检查 JWT exp | 即将过期(< 5min)或 API 返回 401 |
|
|||
|
|
| 桌面端 SakuraCloudClient | 被动响应 401 | API 返回 401 |
|
|||
|
|
| 手机端 (Flutter) | **无自动刷新** | 启动时验证,失败则跳转登录页 |
|
|||
|
|
| 管理后台 (Vue) | Axios 响应拦截器 | API 返回 401 + 有 refreshToken |
|
|||
|
|
| 云端 API | POST /auth/refresh | 客户端主动调用 |
|