sync update from LAN repo (source dhk-1 @ 3b1ec5b4)

This commit is contained in:
gozeros committed 2026-11-05 10:56:34 +08:00
1 parent da6521b6cb
commit 264e2200d6
995 files changed
+148105 -13399

No files matched your search

@@ -1,5 +1,7 @@
"""Authentication endpoints."""
import asyncio
import json
import logging
import os
import time
@@ -9,8 +11,9 @@ from typing import Literal
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 pydantic import BaseModel, ConfigDict, EmailStr, Field, TypeAdapter, ValidationError, field_validator, model_validator
from app.gateway.admin_query_window import recent_admin_query_cutoff
from app.gateway.auth import (
UserResponse,
create_access_token,
@@ -18,16 +21,20 @@ from app.gateway.auth import (
from app.gateway.auth.config import get_auth_config
from app.gateway.auth.errors import AuthErrorCode, AuthErrorResponse
from app.gateway.auth.models import User
from app.gateway.auth.password import has_account_password, hash_password_async, is_password_hash, verify_account_password
from app.gateway.auth.repositories.base import CredentialConflictError
from app.gateway.csrf_middleware import is_secure_request
from app.gateway.deps import get_agent_store, get_current_user_from_request, get_local_provider, get_run_store, get_skill_store
from app.gateway.perf_logging import finish_trace, trace_request, trace_stage
from deerflow.config import get_app_config
from deerflow.config.system_settings import load_system_settings
from deerflow.config.system_settings import AuthenticationSettings, load_system_settings
from deerflow.persistence.agents.base import AgentStore
from deerflow.persistence.skills.base import SkillStore
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
_USER_NOT_LOOKED_UP = object()
# ── Request/Response Models ──────────────────────────────────────────────
@@ -106,18 +113,35 @@ def _validate_strong_password(value: str) -> str:
``@field_validator(field_name)`` without inheritance gymnastics.
"""
if _password_is_common(value):
raise ValueError("Password is too common; choose a stronger password.")
raise ValueError("密码过于常见,请设置更安全的密码")
if value != value.strip():
raise ValueError("密码首尾不能包含空格")
return value
class RegisterRequest(BaseModel):
"""Request model for user registration."""
email: EmailStr
password: str = Field(..., min_length=8)
username: str | None = Field(default=None, min_length=1, max_length=128)
email: EmailStr | None = None
password: str = Field(..., min_length=8, max_length=255)
model_config = ConfigDict(extra="forbid")
_strong_password = field_validator("password")(classmethod(lambda cls, v: _validate_strong_password(v)))
@model_validator(mode="after")
def validate_identity(self):
if bool(self.username) == bool(self.email):
raise ValueError("请填写用户名或邮箱(只需一项)")
if self.username is not None:
value = self.username.strip()
if "@" not in value and (not value or value[0] in "._-" or value[-1] in "._-" or any(not (ch.isalnum() or ch in "._-") for ch in value)):
raise ValueError("用户名仅支持字母、数字、点、下划线和短横线,首尾须为字母或数字")
self.username = value
if "@" in value:
TypeAdapter(EmailStr).validate_python(value)
return self
class UsernameLoginRequest(BaseModel):
"""Request model for passwordless username login.
@@ -160,8 +184,8 @@ class UsernameLoginResponse(BaseModel):
class ChangePasswordRequest(BaseModel):
"""Request model for password change (also handles setup flow)."""
current_password: str
new_password: str = Field(..., min_length=8)
current_password: str = Field(default="", max_length=255)
new_password: str = Field(..., min_length=8, max_length=255)
new_email: EmailStr | None = None
_strong_password = field_validator("new_password")(classmethod(lambda cls, v: _validate_strong_password(v)))
@@ -173,6 +197,12 @@ class MessageResponse(BaseModel):
message: str
class PasswordChangeResponse(MessageResponse):
access_token: str
token_type: str = "bearer"
expires_in: int
# ── Helpers ───────────────────────────────────────────────────────────────
@@ -212,39 +242,71 @@ def _username_to_email(username: str) -> str:
return f"{local}@{domain}"
async def _sync_user_position(request: Request, user_id: str) -> None:
"""Best-effort: materialize the user's 岗位 (position) grants on login.
# 后台岗位同步任务的强引用集合:防止 create_task 的任务被 GC 中途回收。
_position_sync_tasks: set = set()
_POSITION_SYNC_CACHE_SECONDS = 60.0
_MAX_POSITION_SYNC_CACHE_USERS = 10_000
_position_sync_completed_at: dict[str, float] = {}
_position_sync_inflight: dict[str, asyncio.Task[None]] = {}
def _sync_user_position(request: Request, user_id: str) -> None:
"""Best-effort: schedule the user's 岗位 (position) sync off the login path.
Ensures a user who has never been synced — e.g. a brand-new account that
inherits the ``is_default`` position — gets the default agents / tasks /
prompts loaded into their "我的" tables. Failures never block login.
prompts loaded into their "我的" tables. The sync is idempotent but touches
a dozen tables per user, so it runs as a fire-and-forget task instead of
blocking the login response; the materialized rows land a moment later and
failures are logged, never surfaced.
"""
normalized_user_id = str(user_id)
now = time.monotonic()
completed_at = _position_sync_completed_at.get(normalized_user_id)
if completed_at is not None and now - completed_at < _POSITION_SYNC_CACHE_SECONDS:
return
if normalized_user_id in _position_sync_inflight:
return
sync = getattr(request.app.state, "position_sync", None)
if sync is None:
return
async def _run() -> None:
try:
await sync.sync_user(normalized_user_id)
_position_sync_completed_at[normalized_user_id] = time.monotonic()
if len(_position_sync_completed_at) > _MAX_POSITION_SYNC_CACHE_USERS:
oldest = sorted(_position_sync_completed_at, key=_position_sync_completed_at.get)
for stale_user_id in oldest[: len(oldest) // 2]:
_position_sync_completed_at.pop(stale_user_id, None)
except Exception:
logger.debug("position sync on login failed for user %s", user_id, exc_info=True)
finally:
_position_sync_inflight.pop(normalized_user_id, None)
try:
sync = getattr(request.app.state, "position_sync", None)
if sync is not None:
await sync.sync_user(str(user_id))
except Exception:
logger.debug("position sync on login failed for user %s", user_id, exc_info=True)
task = asyncio.create_task(_run())
except RuntimeError:
# 防御:请求处理器内必有运行中的事件循环,这里理论上走不到。
logger.debug("position sync scheduling failed for user %s", user_id, exc_info=True)
return
_position_sync_tasks.add(task)
_position_sync_inflight[normalized_user_id] = task
task.add_done_callback(_position_sync_tasks.discard)
def _is_admin_username(username: str) -> bool:
"""内置管理员用户名判定:用户名包含 ``admin``(如 ``admin``、``b1admin``)。
命中的用户名首次自动注册时直接落 ``system_role="admin"``;历史已注册但仍是
普通用户的,登录时自动提升为管理员(与 ``admin`` 账号原有行为一致)。判定
不区分大小写;显式邮箱登录按整串匹配(邮箱本地部分含 admin 同样命中)。
"""
return "admin" in (username or "").lower()
async def _get_or_create_user_by_username(username: str):
async def _get_or_create_user_by_username(
username: str,
*,
existing_user: User | None | object = _USER_NOT_LOOKED_UP,
):
"""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 admin-username
promotion so both entry points behave identically.
the row. Roles are persisted authorization data, never inferred from names.
"""
provider = get_local_provider()
email = _username_to_email(username)
@@ -256,7 +318,12 @@ async def _get_or_create_user_by_username(username: str):
# also exists at today's canonical domain. Choosing the exact canonical
# row first made the same username alternate backend user_ids after a
# domain migration, which in turn made its existing threads inaccessible.
if local_part is not None:
if existing_user is not _USER_NOT_LOOKED_UP:
# /login/username already performed this lookup to validate the
# account-specific password. Reuse both hits and misses instead of
# issuing the same MySQL query twice during a login burst.
user = existing_user
elif local_part is not None:
user = await provider.find_user_by_email_local_part(local_part)
if user is not None and user.email != email:
logger.info("Matched username %r to stable legacy account %s", username, user.email)
@@ -265,10 +332,9 @@ async def _get_or_create_user_by_username(username: str):
user = await provider.get_user_by_email(email)
if user is None:
try:
role = "admin" if _is_admin_username(username) else "user"
# 黑名单模式:从未登录过的新用户(此处即首次自动注册)默认放行(approved=True)。
# 管理员可在白名单管理页对个别用户「取消放行」来封禁——仅当登录白名单开关打开时生效。
user = await provider.create_user(email=email, password=None, system_role=role, needs_setup=False, approved=True)
user = await provider.create_user(email=email, password=None, system_role="user", needs_setup=False, approved=True)
created = True
logger.info("Auto-registered passwordless user: %s", email)
except ValueError:
@@ -277,15 +343,7 @@ async def _get_or_create_user_by_username(username: str):
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 _is_admin_username(username) and user.system_role != "admin":
# Historical accounts created before the username-based role assignment
# may still have system_role="user" — promote admin-username accounts
# (admin / b1admin / …) so both login entry points behave consistently.
user.system_role = "admin"
user = await provider.update_user(user)
logger.info("Promoted historical admin-username account %r to system_role=admin: %s", username, email)
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="该用户名已存在,请使用原账号登录")
return user, created
@@ -550,100 +608,170 @@ def _record_login_success(ip: str) -> None:
# ── Endpoints ─────────────────────────────────────────────────────────────
@router.post("/login/local", response_model=LoginResponse)
def _require_login_method(method: str) -> None:
settings = load_system_settings().authentication
if not getattr(settings, method):
labels = {"password_login_enabled": "账号密码登录", "registration_enabled": "自助注册", "sso_enabled": "外部系统免登"}
raise HTTPException(status_code=403, detail=f"管理员尚未开启{labels[method]}")
def _login_response(user: User, token: str, *, username: str | None = None, created: bool = False) -> UsernameLoginResponse:
return UsernameLoginResponse(
access_token=token,
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,
username=username or user.email.split("@", 1)[0],
)
async def _prepare_login_session(user: User) -> User:
"""Apply the administrator's one-online-session policy after authentication."""
if not load_system_settings().authentication.single_session_enabled:
return user
try:
return await get_local_provider().start_login_session(user)
except CredentialConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
class AuthenticationOptions(AuthenticationSettings):
needs_setup: bool = False
@router.get("/options", response_model=AuthenticationOptions)
async def authentication_options(request: Request, response: Response) -> AuthenticationOptions:
"""Anonymous, non-secret capability discovery for the login page."""
response.headers["Cache-Control"] = "no-store"
trace = trace_request(request, "auth_options")
try:
stage_started = time.perf_counter()
authentication = load_system_settings().authentication.model_dump()
trace_stage(trace, "load_system_settings", stage_started)
stage_started = time.perf_counter()
needs_setup = await get_local_provider().count_admin_users() == 0
trace_stage(trace, "count_admin_users", stage_started)
return AuthenticationOptions(**authentication, needs_setup=needs_setup)
finally:
finish_trace(trace)
@router.post("/login/local", response_model=UsernameLoginResponse)
async def login_local(
request: Request,
response: Response,
form_data: OAuth2PasswordRequestForm = Depends(),
):
"""Local email/password login."""
"""Username or email login with the account's unified password/passphrase."""
_require_login_method("password_login_enabled")
client_ip = _get_client_ip(request)
_check_rate_limit(client_ip)
user = await get_local_provider().authenticate({"email": form_data.username, "password": form_data.password})
user = await _lookup_user_by_username(form_data.username)
if user is not None and not await verify_account_password(form_data.password, user):
user = None
if user is None:
_record_login_failure(client_ip)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="邮箱或密码错误").model_dump(),
detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="账号或密码错误").model_dump(),
)
_record_login_success(client_ip)
enforce_user_approved(user)
token = create_access_token(str(user.id), token_version=user.token_version)
user = await _prepare_login_session(user)
token = create_access_token(str(user.id), token_version=user.token_version, auth_method="password")
_set_session_cookie(response, token, request)
await _sync_user_position(request, user.id)
_sync_user_position(request, user.id)
return LoginResponse(
expires_in=get_auth_config().token_expiry_days * 24 * 3600,
needs_setup=user.needs_setup,
)
return _login_response(user, token, username=form_data.username.strip())
def _username_login_request(username: object) -> UsernameLoginRequest:
if not isinstance(username, str):
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="username is required")
try:
return UsernameLoginRequest(username=username)
except ValidationError as exc:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="username is required") from exc
async def _read_username_login(request: Request) -> UsernameLoginRequest:
"""Accept the historical JSON body and a form body.
``application/x-www-form-urlencoded`` is a CORS simple content type. Old
Firefox aborts a credentialed JSON login during preflight and reports
NS_BINDING_ABORTED, so the browser client sends a form body instead.
"""
media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if media_type == "application/x-www-form-urlencoded":
form = await request.form()
return _username_login_request(form.get("username"))
try:
payload = await request.json()
except json.JSONDecodeError as exc:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="username is required") from exc
username = payload.get("username") if isinstance(payload, dict) else None
return _username_login_request(username)
@router.post("/login/username", response_model=UsernameLoginResponse)
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."),
password: str | None = Query(default=None, description="Account password or shared passphrase; required when password login is enabled."),
):
"""Passwordless username login with auto-registration.
"""Compatibility username login, gated by the current credential policy.
Rules:
- If mapped account exists, sign in directly (no password required).
- If account does not exist, create a regular user and sign in.
Password gates (checked in this order):
1. **Per-account 登录口令** — if an admin assigned this specific account a
personal password (``users.login_password``, set on the 白名单管理 page),
the caller must pass ``?password=`` exactly matching it. This takes
precedence over the shared gate and is the「临时给某账号开通+设新口令」flow.
2. **Shared gate** — otherwise, when
``auth_login.username_login.require_password`` is enabled, callers must
pass ``?password=`` matching the configured shared secret (default
``123ewq`` when unset). A single shared password; 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.
Personal password/passphrase wins. With password login enabled, accounts
without personal credentials must supply the existing shared passphrase
(default 123ewq). Identity-only login is retained only while password login
is disabled and the historical shared-password gate is also disabled.
"""
body = await _read_username_login(request)
_require_login_method("sso_enabled")
username_login_config = get_app_config().auth_login.username_login
password_login_enabled = load_system_settings().authentication.password_login_enabled
# Per-account password takes precedence: look the account up (no create) and,
# if it carries a personal 登录口令, require an exact match — ignoring the
# shared gate entirely for that account.
existing = await _lookup_user_by_username(body.username)
personal_password = (getattr(existing, "login_password", None) or "").strip() if existing else ""
if personal_password:
credentials_verified = False
if has_account_password(existing) or password_login_enabled or username_login_config.require_password:
client_ip = _get_client_ip(request)
_check_rate_limit(client_ip)
if (password or "") != personal_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)
elif username_login_config.require_password:
client_ip = _get_client_ip(request)
_check_rate_limit(client_ip)
if password != username_login_config.effective_password:
if not await verify_account_password(password or "", existing):
_record_login_failure(client_ip)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="口令错误").model_dump(),
)
credentials_verified = True
_record_login_success(client_ip)
user, created = await _get_or_create_user_by_username(body.username)
user, created = await _get_or_create_user_by_username(body.username, existing_user=existing)
# A registration/reset may commit after the initial lookup/password gate.
# Never mint the new account/version's session using an earlier decision.
if has_account_password(user) and (existing is None or existing.id != user.id or existing.token_version != user.token_version):
client_ip = _get_client_ip(request)
_check_rate_limit(client_ip)
if not await verify_account_password(password or "", user):
_record_login_failure(client_ip)
raise HTTPException(status_code=401, detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="口令错误").model_dump())
credentials_verified = True
enforce_user_approved(user)
token = create_access_token(str(user.id), token_version=user.token_version)
user = await _prepare_login_session(user)
token = create_access_token(str(user.id), token_version=user.token_version, auth_method="passphrase" if credentials_verified else None)
_set_session_cookie(response, token, request)
await _sync_user_position(request, user.id)
_sync_user_position(request, user.id)
return UsernameLoginResponse(
access_token=token,
@@ -675,6 +803,7 @@ async def login_by_token(
Returns the JWT access token in the response body and also sets it as a
session cookie for browser callers.
"""
_require_login_method("sso_enabled")
config = get_app_config().auth_login.token_login
if not config.enabled:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="token 登录未开启")
@@ -694,9 +823,10 @@ async def login_by_token(
user, created = await _get_or_create_user_by_username(username)
enforce_user_approved(user)
access_token = create_access_token(str(user.id), token_version=user.token_version)
user = await _prepare_login_session(user)
access_token = create_access_token(str(user.id), token_version=user.token_version, auth_method="sso")
_set_session_cookie(response, access_token, request)
await _sync_user_position(request, user.id)
_sync_user_position(request, user.id)
return UsernameLoginResponse(
access_token=access_token,
@@ -713,26 +843,41 @@ async def login_by_token(
)
@router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
@router.post("/register", response_model=UsernameLoginResponse, status_code=status.HTTP_201_CREATED)
async def register(request: Request, response: Response, body: RegisterRequest):
"""Register a new user account (always 'user' role).
Admin is auto-created on first boot. This endpoint creates regular users.
Auto-login by setting the session cookie.
"""
_require_login_method("password_login_enabled")
_require_login_method("registration_enabled")
client_ip = _get_client_ip(request)
_check_rate_limit(client_ip)
provider = get_local_provider()
username = body.username or str(body.email)
email = _username_to_email(username)
# Match every domain, even for explicit emails: a self-registration must
# never shadow the stable account selected by bare-username login.
duplicate = await provider.find_user_by_email_local_part(email.split("@", 1)[0])
try:
user = await get_local_provider().create_user(email=body.email, password=body.password, system_role="user")
if duplicate is not None:
raise ValueError("Duplicate username")
user = await provider.create_user(email=email, password=body.password, system_role="user", approved=True)
except ValueError:
_record_login_failure(client_ip)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=AuthErrorResponse(code=AuthErrorCode.EMAIL_ALREADY_EXISTS, message="Email already registered").model_dump(),
status_code=status.HTTP_409_CONFLICT,
detail=AuthErrorResponse(code=AuthErrorCode.EMAIL_ALREADY_EXISTS, message="该用户名或邮箱已注册").model_dump(),
)
token = create_access_token(str(user.id), token_version=user.token_version)
enforce_user_approved(user)
user = await _prepare_login_session(user)
token = create_access_token(str(user.id), token_version=user.token_version, auth_method="password")
_set_session_cookie(response, token, request)
await _sync_user_position(request, user.id)
_sync_user_position(request, user.id)
return UserResponse(id=str(user.id), email=user.email, system_role=user.system_role)
return _login_response(user, token, username=username, created=True)
@router.post("/logout", response_model=MessageResponse)
@@ -742,7 +887,7 @@ async def logout(request: Request, response: Response):
return MessageResponse(message="Successfully logged out")
@router.post("/change-password", response_model=MessageResponse)
@router.post("/change-password", response_model=PasswordChangeResponse)
async def change_password(request: Request, response: Response, body: ChangePasswordRequest):
"""Change password for the currently authenticated user.
@@ -752,47 +897,46 @@ async def change_password(request: Request, response: Response, body: ChangePass
- Always increments token_version to invalidate old sessions
- Re-issues session cookie with new token_version
"""
from app.gateway.auth.password import hash_password_async, verify_password_async
user = await get_current_user_from_request(request)
if user.password_hash is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="OAuth users cannot change password").model_dump())
if not await verify_password_async(body.current_password, user.password_hash):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="Current password is incorrect").model_dump())
client_ip = _get_client_ip(request)
_check_rate_limit(client_ip)
if not await verify_account_password(body.current_password, user):
_record_login_failure(client_ip)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=AuthErrorResponse(code=AuthErrorCode.INVALID_CREDENTIALS, message="当前密码错误").model_dump())
provider = get_local_provider()
# Update email if provided
if body.new_email is not None:
existing = await provider.get_user_by_email(body.new_email)
existing = await provider.find_user_by_email_local_part(body.new_email.split("@", 1)[0])
if existing and str(existing.id) != str(user.id):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=AuthErrorResponse(code=AuthErrorCode.EMAIL_ALREADY_EXISTS, message="Email already in use").model_dump())
user.email = body.new_email
# Update password + bump version
user.password_hash = await hash_password_async(body.new_password)
user.token_version += 1
# Clear setup flag if this is the setup flow
if user.needs_setup and body.new_email is not None:
user.needs_setup = False
await provider.update_user(user)
try:
user = await provider.update_credentials(user, await hash_password_async(body.new_password), email=body.new_email)
except ValueError as exc:
raise HTTPException(status_code=409, detail="账号信息已变更,请刷新后重试") from exc
_record_login_success(client_ip)
# Re-issue cookie with new token_version
token = create_access_token(str(user.id), token_version=user.token_version)
token = create_access_token(str(user.id), token_version=user.token_version, auth_method="password")
_set_session_cookie(response, token, request)
return MessageResponse(message="Password changed successfully")
return PasswordChangeResponse(message="密码已更新", access_token=token, expires_in=get_auth_config().token_expiry_days * 24 * 3600)
@router.get("/me", response_model=UserResponse)
async def get_me(request: Request):
"""Get current authenticated user info."""
user = await get_current_user_from_request(request)
return UserResponse(id=str(user.id), email=user.email, system_role=user.system_role, needs_setup=user.needs_setup)
return UserResponse(
id=str(user.id),
email=user.email,
system_role=user.system_role,
needs_setup=user.needs_setup,
has_password=has_account_password(user),
requires_current_password=True,
uses_default_password=not has_account_password(user),
)
_SETUP_STATUS_COOLDOWN: dict[str, float] = {}
@@ -834,12 +978,12 @@ class InitializeAdminRequest(BaseModel):
"""Request model for first-boot admin account creation."""
email: EmailStr
password: str = Field(..., min_length=8)
password: str = Field(..., min_length=8, max_length=255)
_strong_password = field_validator("password")(classmethod(lambda cls, v: _validate_strong_password(v)))
@router.post("/initialize", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
@router.post("/initialize", response_model=UsernameLoginResponse, status_code=status.HTTP_201_CREATED)
async def initialize_admin(request: Request, response: Response, body: InitializeAdminRequest):
"""Create the first admin account on initial system setup.
@@ -857,7 +1001,7 @@ async def initialize_admin(request: Request, response: Response, body: Initializ
)
try:
user = await get_local_provider().create_user(email=body.email, password=body.password, system_role="admin", needs_setup=False, approved=True)
user = await get_local_provider().create_initial_admin(email=str(body.email), password=body.password)
except ValueError:
# DB unique-constraint race: another concurrent request beat us.
raise HTTPException(
@@ -865,10 +1009,11 @@ async def initialize_admin(request: Request, response: Response, body: Initializ
detail=AuthErrorResponse(code=AuthErrorCode.SYSTEM_ALREADY_INITIALIZED, message="System already initialized").model_dump(),
)
token = create_access_token(str(user.id), token_version=user.token_version)
user = await _prepare_login_session(user)
token = create_access_token(str(user.id), token_version=user.token_version, auth_method="password")
_set_session_cookie(response, token, request)
return UserResponse(id=str(user.id), email=user.email, system_role=user.system_role)
return _login_response(user, token, created=True)
# ── Admin Endpoints ───────────────────────────────────────────────────────
@@ -882,44 +1027,99 @@ class UserListItem(BaseModel):
agent_count: int
qa_count: int = 0 # 问答次数: number of runs (one run = one question)
approved: bool = True # 登录白名单放行标记(白名单管理页据此放行/取消)
login_password: str | None = None # 账号级登录口令(明文,管理员可见/可复制登录链接)
login_password: str | None = None # Legacy plaintext only; never return hashes.
has_login_password: bool = False
access_token: str | None = None
token_type: str = "bearer"
expires_in: int | None = None
@router.get("/users", response_model=list[UserListItem])
def _legacy_login_password(user: User) -> str | None:
value = user.login_password
return value if value and not is_password_hash(value) else None
class UserListPage(BaseModel):
"""Paged user list — returned when the caller passes ``limit``."""
items: list[UserListItem]
total: int
approved_count: int # approved 或 admin(搜索范围内)
limit: int
offset: int
_USER_LIST_TIMEOUT_SECONDS = 15
def _user_list_skill_store(request: Request, include_counts: bool = True) -> SkillStore | None:
return get_skill_store(request) if include_counts else None
def _user_list_agent_store(request: Request, include_counts: bool = True) -> AgentStore | None:
return get_agent_store(request) if include_counts else None
@router.get("/users", response_model=list[UserListItem] | UserListPage)
async def list_all_users(
request: Request,
skill_store: SkillStore = Depends(get_skill_store),
agent_store: AgentStore = Depends(get_agent_store),
include_counts: bool = Query(True, description="False=只查 users 表,跳过 runs 统计与 skill/agent 计数(白名单管理页用,避免慢查询)"),
q: str | None = Query(None, max_length=100, description="可选:按邮箱/用户ID 子串过滤(仅分页模式生效)"),
limit: int | None = Query(None, ge=1, le=200, description="传入即分页返回 UserListPage;不传保持旧的全量列表"),
offset: int = Query(0, ge=0),
skill_store: SkillStore | None = Depends(_user_list_skill_store),
agent_store: AgentStore | None = Depends(_user_list_agent_store),
):
"""List all users with their skill, agent and Q&A counts. Admin only."""
user = await get_current_user_from_request(request)
if user.system_role != "admin":
raise HTTPException(status_code=403, detail="Admin only")
users = await get_local_provider().list_users()
# One GROUP BY query for everyone's 问答次数, so the list stays a single
# aggregate read instead of a per-user count. Best-effort: if the run store
# is unavailable the column simply renders as 0 rather than failing the list.
"""List all users with their skill, agent and Q&A counts. Admin only.
Passing ``limit`` switches to a paged response that reads one page of the
users table plus two COUNT queries; omitting it keeps the legacy flat list.
"""
try:
qa_counts = await get_run_store(request).count_by_user()
except Exception:
logger.warning("Failed to load per-user run counts for user list", exc_info=True)
qa_counts = {}
result = []
for u in users:
uid = str(u.id)
result.append(
UserListItem(
id=uid,
email=u.email,
system_role=u.system_role,
skill_count=await skill_store.count_owned(uid),
agent_count=await agent_store.count_owned(uid),
qa_count=qa_counts.get(uid, 0),
approved=getattr(u, "approved", True),
login_password=getattr(u, "login_password", None),
async with asyncio.timeout(_USER_LIST_TIMEOUT_SECONDS if not include_counts else None):
user = await get_current_user_from_request(request)
if user.system_role != "admin":
raise HTTPException(status_code=403, detail="Admin only")
provider = get_local_provider()
users = (
await provider.list_users()
if limit is None
else await provider.list_users_page(q=q, limit=limit, offset=offset)
)
)
return result
qa_counts: dict[str, int] = {}
# One recent-window GROUP BY for everyone's 问答次数. This keeps the admin
# user list from scanning the complete lifetime of the runs table.
if include_counts:
try:
qa_counts = await get_run_store(request).count_by_user(
since=recent_admin_query_cutoff()
)
except Exception:
logger.warning("Failed to load per-user run counts for user list", exc_info=True)
result = []
for u in users:
uid = str(u.id)
result.append(
UserListItem(
id=uid,
email=u.email,
system_role=u.system_role,
skill_count=(await skill_store.count_owned(uid)) if include_counts else 0,
agent_count=(await agent_store.count_owned(uid)) if include_counts else 0,
qa_count=qa_counts.get(uid, 0),
approved=getattr(u, "approved", True),
login_password=_legacy_login_password(u),
has_login_password=has_account_password(u),
)
)
if limit is None:
return result
total = await provider.count_users_filtered(q=q)
approved_count = await provider.count_users_filtered(q=q, approved_or_admin=True)
return UserListPage(items=result, total=total, approved_count=approved_count, limit=limit, offset=offset)
except TimeoutError as exc:
logger.warning("User list timed out waiting for account data")
raise HTTPException(status_code=503, detail="用户基础信息查询超时,请稍后重试") from exc
class UserApprovalRequest(BaseModel):
@@ -942,7 +1142,10 @@ async def set_user_approval(user_id: str, body: UserApprovalRequest, request: Re
raise HTTPException(status_code=404, detail="用户不存在")
target.approved = bool(body.approved)
saved = await provider.update_user(target)
try:
saved = await provider.update_user(target)
except CredentialConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
return UserListItem(
id=str(saved.id),
email=saved.email,
@@ -951,7 +1154,8 @@ async def set_user_approval(user_id: str, body: UserApprovalRequest, request: Re
agent_count=0,
qa_count=0,
approved=saved.approved,
login_password=saved.login_password,
login_password=_legacy_login_password(saved),
has_login_password=has_account_password(saved),
)
@@ -959,18 +1163,14 @@ class UserLoginPasswordRequest(BaseModel):
password: str | None = Field(
default=None,
max_length=255,
description="设为非空 → 该账号用户名直登需带此明文口令;传 null/空字符串 → 清除该口令(回到共享口令门/免口令)。",
description="设置账号密码(与登录口令一致);不允许清除后退回免密码登录。",
)
@router.put("/users/{user_id}/login-password", response_model=UserListItem)
async def set_user_login_password(user_id: str, body: UserLoginPasswordRequest, request: Request) -> UserListItem:
"""设置 / 清除某个账号的「登录口令」(明文)。Admin only。
设置后,该账号的用户名直登(``/login/username``)必须带匹配的 ``?password=``;
管理员据返回的明文口令拼出登录链接 ``…/login/<用户名>?password=xxxx`` 发给用户。
不动 ``token_version``,现有会话不受影响(仅影响下次登录)。
"""
@router.put("/users/{user_id}/reset-password", response_model=UserListItem)
async def set_user_login_password(user_id: str, body: UserLoginPasswordRequest, request: Request, response: Response) -> UserListItem:
"""Admin password reset; rotates both credential columns and all sessions."""
admin = await get_current_user_from_request(request)
if admin.system_role != "admin":
raise HTTPException(status_code=403, detail="Admin only")
@@ -980,10 +1180,25 @@ async def set_user_login_password(user_id: str, body: UserLoginPasswordRequest,
if target is None:
raise HTTPException(status_code=404, detail="用户不存在")
# 空字符串 / null / 纯空白 → 清除(None);否则存去掉首尾空白后的明文。
pwd = (body.password or "").strip()
target.login_password = pwd or None
saved = await provider.update_user(target)
pwd = body.password or ""
if not pwd:
raise HTTPException(status_code=400, detail="不能清除账号密码,请设置新密码")
if len(pwd) < 8:
raise HTTPException(status_code=400, detail="密码至少需要 8 个字符")
try:
_validate_strong_password(pwd)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
try:
saved = await provider.update_credentials(target, await hash_password_async(pwd))
except CredentialConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
token = None
expires_in = None
if str(admin.id) == str(saved.id):
token = create_access_token(str(saved.id), token_version=saved.token_version, auth_method="password")
_set_session_cookie(response, token, request)
expires_in = get_auth_config().token_expiry_days * 24 * 3600
return UserListItem(
id=str(saved.id),
email=saved.email,
@@ -992,7 +1207,10 @@ async def set_user_login_password(user_id: str, body: UserLoginPasswordRequest,
agent_count=0,
qa_count=0,
approved=saved.approved,
login_password=saved.login_password,
login_password=None,
has_login_password=True,
access_token=token,
expires_in=expires_in,
)
@@ -1006,6 +1224,7 @@ async def oauth_login(provider: str):
Redirects to the OAuth provider's authorization URL.
Currently a placeholder - requires OAuth provider implementation.
"""
_require_login_method("sso_enabled")
if provider not in ["github", "google"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -1025,6 +1244,7 @@ async def oauth_callback(provider: str, code: str, state: str):
Handles the OAuth provider's callback after user authorization.
Currently a placeholder.
"""
_require_login_method("sso_enabled")
raise HTTPException(
status_code=status.HTTP_501_NOT_IMPLEMENTED,
detail="OAuth callback not yet implemented",