feat(auth): 接入 auth-hub 统一登录,网页登录与 Garmin 同步彻底分离

网页身份改由 auth-hub 做 OAuth2 + PKCE 单点登录,本地邮箱/密码登录与注册整条链路删除
(routes/auth.py、auth.py 的密码哈希、config.py 的 ALLOW_REGISTRATION)。Garmin 账号绑定/
同步保持完全独立、可选:routes/garmin.py 不再直接查 users 表,Garmin 邮箱回退统一走新增
的 services/garmin.py::get_remembered_email()(优先读 garmin_tokens 当前绑定,兼容早期账号
落在 users.garmin_email 的历史值),彻底把「你是谁」和「你绑没绑 Garmin」两件事拆开。

- db.py: users 表新增 auth_hub_sub/auth_hub_username,MIGRATIONS 补上这两列(此前遗漏导致
  已存在的生产 MariaDB 表永远不会自动加列);同时把历史遗留的 garmin_email/
  garmin_password_hash NOT NULL 约束在线迁移为可空,因为新账号不再在注册时收集这些字段。
- routes/auth.py: 修掉 /callback 路由重复拼接 /api/auth 前缀导致 404 的 bug。
- client: LoginPage 去掉本地登录/注册标签页,只保留 auth-hub 统一登录;登录成功/失败后都
  用 history.replaceState 清理地址栏,修掉 Framework7 browserHistory 读取
  /auth/callback?code=... 导致「找不到页面」的问题。
- 新增 test_auth_hub_client.py 锁定 find_or_create_user 按 auth_hub_sub 幂等——生产上曾经因为
  这个函数在没有该测试保护时被测试触发,误建过一个空账号,靠手工核对 health_data 计数才发现。
- 生产 auth-hub 侧另行为该项目注册了正式 client(未随本次提交变更,凭证只存在服务器 .env)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ericwyuan
2026-08-31 23:12:17 +08:00
parent 7e51223eb9
commit 9503fca370
24 changed files with 592 additions and 1007 deletions

View File

@@ -1,21 +1,8 @@
"""
Authentication helpers: password hashing, JWT signing/verification,
and the require_auth decorator used by route blueprints.
Hashes are stored in a self-describing format so the algorithm can be
migrated later without invalidating existing rows:
pbkdf2_sha256$<iterations>$<salt_hex>$<hash_hex>
PBKDF2-HMAC-SHA256 is used because it is available in every CPython build.
`hashlib.scrypt` is NOT: builds linked against LibreSSL (notably the system
Python on macOS) omit it, which made registration fail with a 500.
Legacy `<salt_hex>:<hash_hex>` scrypt hashes are still verified when the
running interpreter supports scrypt.
JWT signing/verification and the require_auth decorator used by route
blueprints. Accounts come from auth-hub (see services/auth_hub_client.py);
this module only handles this app's own session token.
"""
import hashlib
import hmac
import os
import datetime
import jwt
@@ -24,64 +11,6 @@ from functools import wraps
from config import JWT_SECRET, JWT_EXPIRY_DAYS
PBKDF2_ITERATIONS = 200_000
PBKDF2_PREFIX = "pbkdf2_sha256"
_SALT_BYTES = 16
_DK_LEN = 64
class AuthError(Exception):
def __init__(self, code, message):
super().__init__(message)
self.code = code
self.message = message
def _pbkdf2(password: str, salt: bytes, iterations: int) -> str:
return hashlib.pbkdf2_hmac(
"sha256", password.encode("utf-8"), salt, iterations, dklen=_DK_LEN
).hex()
def hash_password(password: str) -> str:
salt = os.urandom(_SALT_BYTES)
derived = _pbkdf2(password, salt, PBKDF2_ITERATIONS)
return f"{PBKDF2_PREFIX}${PBKDF2_ITERATIONS}${salt.hex()}${derived}"
def _verify_legacy_scrypt(password: str, stored: str) -> bool:
"""Verify a pre-migration `salt_hex:hash_hex` scrypt hash, if supported."""
if not hasattr(hashlib, "scrypt"):
return False
salt_hex, hash_hex = stored.split(":", 1)
try:
salt = bytes.fromhex(salt_hex)
except ValueError:
return False
derived = hashlib.scrypt(
password.encode("utf-8"), salt=salt, n=16384, r=8, p=1, dklen=_DK_LEN
).hex()
return hmac.compare_digest(derived, hash_hex)
def verify_password(password: str, stored: str) -> bool:
if not stored:
return False
if stored.startswith(PBKDF2_PREFIX + "$"):
try:
_, iterations, salt_hex, hash_hex = stored.split("$", 3)
salt = bytes.fromhex(salt_hex)
derived = _pbkdf2(password, salt, int(iterations))
except (ValueError, TypeError):
return False
return hmac.compare_digest(derived, hash_hex)
if ":" in stored:
return _verify_legacy_scrypt(password, stored)
return False
def sign_token(user_id: str) -> str:
now = datetime.datetime.utcnow()