登录鉴权:新增用户名口令门 + token 换登录两种模式
- config 新增 auth_login 段(login_config.py): - username_login.require_password 开启后,用户名直登必须带 ?password=,口令留空默认 123ewq - token_login 用上游 token 调 getTokenInfo 换用户名再登录,用户名不在库自动注册;含 verify_ssl/ca_cert_path 处理 HTTPS 自签证书 - auth.py:口令门、/login/token 端点、共享 _get_or_create_user_by_username 与 _fetch_username_from_token;登录类报错文案改中文 - auth_middleware:/login/token 加入免鉴权白名单 - 前端 api.ts/LoginPage:透传 ?password=、?authToken=;修复错误体为对象时显示 [object Object] 的问题 - 文档:backend/CLAUDE.md + docs/AUTH_LOGIN.md 接口说明 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
5aa1fdca04
commit
c484481964
10 files changed
+531
-56
No files matched your search
@@ -41,6 +41,7 @@ _PUBLIC_EXACT_PATHS: frozenset[str] = frozenset(
|
||||
{
|
||||
"/api/v1/auth/login/local",
|
||||
"/api/v1/auth/login/username",
|
||||
"/api/v1/auth/login/token",
|
||||
"/api/v1/auth/register",
|
||||
"/api/v1/auth/logout",
|
||||
"/api/v1/auth/setup-status",
|
||||
|
||||
@@ -6,10 +6,12 @@ import time
|
||||
from ipaddress import ip_address, ip_network
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel, EmailStr, Field, field_validator
|
||||
|
||||
from deerflow.config import get_app_config
|
||||
from deerflow.persistence.agents.base import AgentStore
|
||||
from deerflow.persistence.skills.base import SkillStore
|
||||
|
||||
@@ -174,12 +176,12 @@ def _normalize_username_local_part(username: str) -> str | None:
|
||||
"""
|
||||
raw = username.strip()
|
||||
if not raw:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="username cannot be empty")
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="用户名不能为空")
|
||||
if "@" in raw:
|
||||
return None
|
||||
normalized = "".join(ch if (ch.isalnum() or ch in "._-") else "-" for ch in raw.lower()).strip("._-")
|
||||
if not normalized:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="username is invalid")
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="用户名不合法")
|
||||
return normalized
|
||||
|
||||
|
||||
@@ -200,6 +202,118 @@ def _username_to_email(username: str) -> str:
|
||||
return f"{local}@{domain}"
|
||||
|
||||
|
||||
async def _get_or_create_user_by_username(username: str):
|
||||
"""Resolve a username to a local user, auto-registering when absent.
|
||||
|
||||
Shared by ``/login/username`` and ``/login/token`` — both turn an
|
||||
externally-supplied username into a local account and sign it in. Returns
|
||||
``(user, created)`` where ``created`` is True only when this call inserted
|
||||
the row. Mirrors the legacy domain-agnostic fallback and the canonical
|
||||
``admin`` promotion so both entry points behave identically.
|
||||
"""
|
||||
provider = get_local_provider()
|
||||
email = _username_to_email(username)
|
||||
local_part = _normalize_username_local_part(username)
|
||||
|
||||
created = False
|
||||
user = await provider.get_user_by_email(email)
|
||||
# Domain-agnostic fallback: if no row exists at the canonical
|
||||
# ``<username>@<current-default-domain>``, look for an existing user with
|
||||
# the same local part under any domain. This is the safety net that keeps
|
||||
# usernames globally unique when the default email domain changes (e.g.
|
||||
# ``local.deerflow`` → ``cm.com``) — without it, switching the default
|
||||
# would let the same username log into two different accounts.
|
||||
if user is None and local_part is not None:
|
||||
legacy = await provider.find_user_by_email_local_part(local_part)
|
||||
if legacy is not None:
|
||||
user = legacy
|
||||
logger.info("Matched username %r to legacy account %s", username, legacy.email)
|
||||
if user is None:
|
||||
try:
|
||||
role = "admin" if username == "admin" else "user"
|
||||
user = await provider.create_user(email=email, password=None, system_role=role, needs_setup=False)
|
||||
created = True
|
||||
logger.info("Auto-registered passwordless user: %s", email)
|
||||
except ValueError:
|
||||
# Concurrent first login may create the same user in parallel.
|
||||
user = await provider.get_user_by_email(email)
|
||||
if user is None and local_part is not None:
|
||||
user = await provider.find_user_by_email_local_part(local_part)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="创建或加载用户失败")
|
||||
elif username == "admin" and user.system_role != "admin":
|
||||
# Historical accounts created before the username-based role assignment
|
||||
# may still have system_role="user" — promote the canonical admin user
|
||||
# so /login/admin behaves consistently.
|
||||
user.system_role = "admin"
|
||||
user = await provider.update_user(user)
|
||||
logger.info("Promoted historical 'admin' account to system_role=admin: %s", email)
|
||||
|
||||
return user, created
|
||||
|
||||
|
||||
async def _fetch_username_from_token(token: str) -> str:
|
||||
"""Resolve an upstream access token to a username via the configured endpoint.
|
||||
|
||||
Calls ``auth_login.token_login.token_info_url`` exactly like the documented
|
||||
curl: a POST carrying ``Authorization: <service_authorization>`` plus the
|
||||
token as the ``access_token`` cookie. Expects ``{"state": "200", "data":
|
||||
{"username": ...}}`` and returns ``data.username``. Any upstream failure,
|
||||
non-200 ``state``, or missing username raises HTTP 401.
|
||||
"""
|
||||
config = get_app_config().auth_login.token_login
|
||||
if not config.token_info_url:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="token 登录未配置(token_info_url 为空)")
|
||||
|
||||
# TLS verification for the (HTTPS) upstream. A custom CA bundle wins; else
|
||||
# the boolean toggle. UAT/internal hosts often need verify_ssl=false because
|
||||
# they serve self-signed or private-CA certs — without this the call dies
|
||||
# with an SSLError and every token login silently 401s.
|
||||
verify: bool | str = config.ca_cert_path if config.ca_cert_path else config.verify_ssl
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=config.timeout_seconds, verify=verify) as client:
|
||||
upstream = await client.post(
|
||||
config.token_info_url,
|
||||
headers={
|
||||
"Authorization": config.service_authorization,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
# Surface the concrete failure (SSL handshake, DNS, timeout, ...) in logs
|
||||
# so HTTPS/cert misconfiguration is diagnosable; client still sees 401.
|
||||
logger.warning(
|
||||
"Token login: upstream call to %s failed (verify=%r): %s: %s",
|
||||
config.token_info_url,
|
||||
verify,
|
||||
type(exc).__name__,
|
||||
exc,
|
||||
)
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="token 校验失败").model_dump())
|
||||
|
||||
if upstream.status_code != 200:
|
||||
logger.warning("Token login: upstream returned HTTP %s", upstream.status_code)
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="token 无效").model_dump())
|
||||
|
||||
try:
|
||||
payload = upstream.json()
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="token 接口返回格式异常").model_dump())
|
||||
|
||||
# Upstream signals success with the string state "200" (see API docs).
|
||||
if str(payload.get("state")) != "200":
|
||||
logger.warning("Token login: upstream state=%r msg=%r", payload.get("state"), payload.get("msg"))
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="token 无效或已过期").model_dump())
|
||||
|
||||
username = (payload.get("data") or {}).get("username")
|
||||
if not username or not str(username).strip():
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="未能从 token 解析出用户名").model_dump())
|
||||
|
||||
return str(username).strip()
|
||||
|
||||
|
||||
def _set_session_cookie(response: Response, token: str, request: Request) -> None:
|
||||
"""Set the access_token HttpOnly cookie on the response."""
|
||||
config = get_auth_config()
|
||||
@@ -301,7 +415,7 @@ def _check_rate_limit(ip: str) -> None:
|
||||
if time.time() < lock_until:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail="Too many login attempts. Try again later.",
|
||||
detail="登录尝试次数过多,请稍后再试",
|
||||
)
|
||||
del _login_attempts[ip]
|
||||
|
||||
@@ -357,7 +471,7 @@ async def login_local(
|
||||
_record_login_failure(client_ip)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="Incorrect email or password").model_dump(),
|
||||
detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="邮箱或密码错误").model_dump(),
|
||||
)
|
||||
|
||||
_record_login_success(client_ip)
|
||||
@@ -371,53 +485,39 @@ async def login_local(
|
||||
|
||||
|
||||
@router.post("/login/username", response_model=UsernameLoginResponse)
|
||||
async def login_by_username(request: Request, response: Response, body: UsernameLoginRequest):
|
||||
async def login_by_username(
|
||||
request: Request,
|
||||
response: Response,
|
||||
body: UsernameLoginRequest,
|
||||
password: str | None = Query(default=None, description="Shared gate secret; required only when auth_login.username_login.require_password is on."),
|
||||
):
|
||||
"""Passwordless username login with auto-registration.
|
||||
|
||||
Rules:
|
||||
- If mapped account exists, sign in directly (no password required).
|
||||
- If account does not exist, create a regular user and sign in.
|
||||
|
||||
Password gate: when ``auth_login.username_login.require_password`` is
|
||||
enabled, callers must additionally pass ``?password=`` matching the
|
||||
configured shared secret (default ``123ewq`` when unset). The gate is a
|
||||
single shared password — it does not change which account is logged in.
|
||||
|
||||
Returns the JWT access token in the response body and also sets it as
|
||||
a session cookie for browser callers.
|
||||
"""
|
||||
provider = get_local_provider()
|
||||
email = _username_to_email(body.username)
|
||||
local_part = _normalize_username_local_part(body.username)
|
||||
username_login_config = get_app_config().auth_login.username_login
|
||||
if username_login_config.require_password:
|
||||
client_ip = _get_client_ip(request)
|
||||
_check_rate_limit(client_ip)
|
||||
if password != username_login_config.effective_password:
|
||||
_record_login_failure(client_ip)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="口令错误").model_dump(),
|
||||
)
|
||||
_record_login_success(client_ip)
|
||||
|
||||
created = False
|
||||
user = await provider.get_user_by_email(email)
|
||||
# Domain-agnostic fallback: if no row exists at the canonical
|
||||
# ``<username>@<current-default-domain>``, look for an existing user with
|
||||
# the same local part under any domain. This is the safety net that keeps
|
||||
# usernames globally unique when the default email domain changes (e.g.
|
||||
# ``local.deerflow`` → ``cm.com``) — without it, switching the default
|
||||
# would let the same username log into two different accounts.
|
||||
if user is None and local_part is not None:
|
||||
legacy = await provider.find_user_by_email_local_part(local_part)
|
||||
if legacy is not None:
|
||||
user = legacy
|
||||
logger.info("Matched username %r to legacy account %s", body.username, legacy.email)
|
||||
if user is None:
|
||||
try:
|
||||
role = "admin" if body.username == "admin" else "user"
|
||||
user = await provider.create_user(email=email, password=None, system_role=role, needs_setup=False)
|
||||
created = True
|
||||
logger.info("Auto-registered passwordless user: %s", email)
|
||||
except ValueError:
|
||||
# Concurrent first login may create the same user in parallel.
|
||||
user = await provider.get_user_by_email(email)
|
||||
if user is None and local_part is not None:
|
||||
user = await provider.find_user_by_email_local_part(local_part)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to create or load user")
|
||||
elif body.username == "admin" and user.system_role != "admin":
|
||||
# Historical accounts created before the username-based role assignment
|
||||
# may still have system_role="user" — promote the canonical admin user
|
||||
# so /login/admin behaves consistently.
|
||||
user.system_role = "admin"
|
||||
user = await provider.update_user(user)
|
||||
logger.info("Promoted historical 'admin' account to system_role=admin: %s", email)
|
||||
user, created = await _get_or_create_user_by_username(body.username)
|
||||
|
||||
token = create_access_token(str(user.id), token_version=user.token_version)
|
||||
_set_session_cookie(response, token, request)
|
||||
@@ -434,6 +534,56 @@ async def login_by_username(request: Request, response: Response, body: Username
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login/token", response_model=UsernameLoginResponse)
|
||||
async def login_by_token(
|
||||
request: Request,
|
||||
response: Response,
|
||||
token: str = Query(..., min_length=1, description="Upstream access token to exchange for a username."),
|
||||
):
|
||||
"""Token-exchange login.
|
||||
|
||||
Verifies an upstream access token by calling the configured
|
||||
``token_info_url`` (see ``auth_login.token_login``), reads the resolved
|
||||
username, then signs the matching local account in — auto-registering it
|
||||
when the username is not yet in the database. Gated by
|
||||
``auth_login.token_login.enabled``.
|
||||
|
||||
Returns the JWT access token in the response body and also sets it as a
|
||||
session cookie for browser callers.
|
||||
"""
|
||||
config = get_app_config().auth_login.token_login
|
||||
if not config.enabled:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="token 登录未开启")
|
||||
|
||||
client_ip = _get_client_ip(request)
|
||||
_check_rate_limit(client_ip)
|
||||
|
||||
try:
|
||||
username = await _fetch_username_from_token(token)
|
||||
except HTTPException as exc:
|
||||
if exc.status_code == status.HTTP_401_UNAUTHORIZED:
|
||||
_record_login_failure(client_ip)
|
||||
raise
|
||||
|
||||
_record_login_success(client_ip)
|
||||
|
||||
user, created = await _get_or_create_user_by_username(username)
|
||||
|
||||
access_token = create_access_token(str(user.id), token_version=user.token_version)
|
||||
_set_session_cookie(response, access_token, request)
|
||||
|
||||
return UsernameLoginResponse(
|
||||
access_token=access_token,
|
||||
token_type="bearer",
|
||||
expires_in=get_auth_config().token_expiry_days * 24 * 3600,
|
||||
user_id=str(user.id),
|
||||
email=user.email,
|
||||
system_role=user.system_role,
|
||||
needs_setup=user.needs_setup,
|
||||
created=created,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def register(request: Request, response: Response, body: RegisterRequest):
|
||||
"""Register a new user account (always 'user' role).
|
||||
|
||||
Reference in new issue
Block a user