sync update from LAN repo (source dhk-1 @ 3b1ec5b4)
This commit is contained in:
1 parent
da6521b6cb
commit
264e2200d6
995 files changed
+148105
-13399
No files matched your search
@@ -23,8 +23,14 @@ _cached_assumed_user: User | None = None
|
||||
|
||||
|
||||
def is_auth_disabled() -> bool:
|
||||
"""Return True when auth gate should be bypassed (development / local tooling)."""
|
||||
return os.environ.get("DEER_FLOW_AUTH_DISABLED", "").strip().lower() in ("1", "true", "yes", "on")
|
||||
"""Enabled password or single-session login overrides the dev bypass."""
|
||||
requested = os.environ.get("DEER_FLOW_AUTH_DISABLED", "").strip().lower() in ("1", "true", "yes", "on")
|
||||
if not requested:
|
||||
return False
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
|
||||
policy = load_system_settings().authentication
|
||||
return not (policy.password_login_enabled or policy.single_session_enabled)
|
||||
|
||||
|
||||
def _row_to_user(row: UserRow) -> User:
|
||||
|
||||
@@ -1,55 +1,77 @@
|
||||
"""JWT token creation and verification."""
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import jwt
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.gateway.auth.config import get_auth_config
|
||||
from app.gateway.auth.errors import TokenError
|
||||
|
||||
|
||||
class TokenPayload(BaseModel):
|
||||
"""JWT token payload."""
|
||||
|
||||
sub: str # user_id
|
||||
exp: datetime
|
||||
iat: datetime | None = None
|
||||
ver: int = 0 # token_version — must match User.token_version
|
||||
|
||||
|
||||
def create_access_token(user_id: str, expires_delta: timedelta | None = None, token_version: int = 0) -> str:
|
||||
"""Create a JWT access token.
|
||||
|
||||
Args:
|
||||
user_id: The user's UUID as string
|
||||
expires_delta: Optional custom expiry, defaults to 7 days
|
||||
token_version: User's current token_version for invalidation
|
||||
|
||||
Returns:
|
||||
Encoded JWT string
|
||||
"""
|
||||
config = get_auth_config()
|
||||
expiry = expires_delta or timedelta(days=config.token_expiry_days)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
payload = {"sub": user_id, "exp": now + expiry, "iat": now, "ver": token_version}
|
||||
return jwt.encode(payload, config.jwt_secret, algorithm="HS256")
|
||||
|
||||
|
||||
def decode_token(token: str) -> TokenPayload | TokenError:
|
||||
"""Decode and validate a JWT token.
|
||||
|
||||
Returns:
|
||||
TokenPayload if valid, or a specific TokenError variant.
|
||||
"""
|
||||
config = get_auth_config()
|
||||
try:
|
||||
payload = jwt.decode(token, config.jwt_secret, algorithms=["HS256"])
|
||||
return TokenPayload(**payload)
|
||||
except jwt.ExpiredSignatureError:
|
||||
return TokenError.EXPIRED
|
||||
except jwt.InvalidSignatureError:
|
||||
return TokenError.INVALID_SIGNATURE
|
||||
except jwt.PyJWTError:
|
||||
return TokenError.MALFORMED
|
||||
"""JWT token creation and verification."""
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Literal
|
||||
|
||||
import jwt
|
||||
from pydantic import BaseModel, Field, ValidationError
|
||||
|
||||
from app.gateway.auth.config import get_auth_config
|
||||
from app.gateway.auth.errors import TokenError
|
||||
|
||||
AuthMethod = Literal["password", "passphrase", "sso", "service"]
|
||||
|
||||
|
||||
class TokenPayload(BaseModel):
|
||||
"""JWT token payload."""
|
||||
|
||||
sub: str # user_id
|
||||
exp: datetime
|
||||
iat: datetime | None = None
|
||||
ver: int = 0 # token_version — must match User.token_version
|
||||
auth_method: AuthMethod | None = None # None is historical/unverified identity-only login.
|
||||
client_id: str | None = None
|
||||
scope: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def create_access_token(
|
||||
user_id: str,
|
||||
expires_delta: timedelta | None = None,
|
||||
token_version: int = 0,
|
||||
*,
|
||||
auth_method: AuthMethod | None = None,
|
||||
client_id: str | None = None,
|
||||
scope: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Create a JWT access token.
|
||||
|
||||
Args:
|
||||
user_id: The user's UUID as string
|
||||
expires_delta: Optional custom expiry, defaults to 7 days
|
||||
token_version: User's current token_version for invalidation
|
||||
auth_method: Explicit proof verified by the issuing login path. Never
|
||||
defaults to a trusted method for old or identity-only callers.
|
||||
|
||||
Returns:
|
||||
Encoded JWT string
|
||||
"""
|
||||
config = get_auth_config()
|
||||
expiry = expires_delta or timedelta(days=config.token_expiry_days)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
payload = {"sub": user_id, "exp": now + expiry, "iat": now, "ver": token_version}
|
||||
if auth_method is not None:
|
||||
payload["auth_method"] = auth_method
|
||||
if client_id is not None:
|
||||
payload["client_id"] = client_id
|
||||
if scope:
|
||||
payload["scope"] = scope
|
||||
return jwt.encode(payload, config.jwt_secret, algorithm="HS256")
|
||||
|
||||
|
||||
def decode_token(token: str) -> TokenPayload | TokenError:
|
||||
"""Decode and validate a JWT token.
|
||||
|
||||
Returns:
|
||||
TokenPayload if valid, or a specific TokenError variant.
|
||||
"""
|
||||
config = get_auth_config()
|
||||
try:
|
||||
payload = jwt.decode(token, config.jwt_secret, algorithms=["HS256"])
|
||||
return TokenPayload(**payload)
|
||||
except jwt.ExpiredSignatureError:
|
||||
return TokenError.EXPIRED
|
||||
except jwt.InvalidSignatureError:
|
||||
return TokenError.INVALID_SIGNATURE
|
||||
except (jwt.PyJWTError, ValidationError):
|
||||
return TokenError.MALFORMED
|
||||
@@ -3,7 +3,7 @@
|
||||
import logging
|
||||
|
||||
from app.gateway.auth.models import User
|
||||
from app.gateway.auth.password import hash_password_async, needs_rehash, verify_password_async
|
||||
from app.gateway.auth.password import hash_password_async, verify_account_password
|
||||
from app.gateway.auth.providers import AuthProvider
|
||||
from app.gateway.auth.repositories.base import UserRepository
|
||||
|
||||
@@ -40,28 +40,19 @@ class LocalAuthProvider(AuthProvider):
|
||||
if user is None:
|
||||
return None
|
||||
|
||||
if user.password_hash is None:
|
||||
# OAuth user without local password
|
||||
if not await verify_account_password(password, user):
|
||||
return None
|
||||
|
||||
if not await verify_password_async(password, user.password_hash):
|
||||
return None
|
||||
|
||||
if needs_rehash(user.password_hash):
|
||||
try:
|
||||
user.password_hash = await hash_password_async(password)
|
||||
await self._repo.update_user(user)
|
||||
except Exception:
|
||||
# Rehash is an opportunistic upgrade; a transient DB error must not
|
||||
# prevent an otherwise-valid login from succeeding.
|
||||
logger.warning("Failed to rehash password for user %s; login will still succeed", user.email, exc_info=True)
|
||||
|
||||
return user
|
||||
|
||||
async def get_user(self, user_id: str) -> User | None:
|
||||
"""Get user by ID."""
|
||||
return await self._repo.get_user_by_id(user_id)
|
||||
|
||||
async def get_users_by_ids(self, user_ids: list[str]) -> list[User]:
|
||||
"""Resolve many account owners with one repository read."""
|
||||
return await self._repo.get_users_by_ids(user_ids)
|
||||
|
||||
async def find_user_by_email_local_part(self, local_part: str) -> User | None:
|
||||
"""Find a user whose email starts with ``local_part@`` regardless of domain.
|
||||
|
||||
@@ -99,6 +90,7 @@ class LocalAuthProvider(AuthProvider):
|
||||
user = User(
|
||||
email=email,
|
||||
password_hash=password_hash,
|
||||
login_password=password_hash,
|
||||
system_role=system_role,
|
||||
needs_setup=needs_setup,
|
||||
approved=approved,
|
||||
@@ -109,6 +101,11 @@ class LocalAuthProvider(AuthProvider):
|
||||
"""Get user by OAuth provider and ID."""
|
||||
return await self._repo.get_user_by_oauth(provider, oauth_id)
|
||||
|
||||
async def create_initial_admin(self, email: str, password: str) -> User:
|
||||
hashed = await hash_password_async(password)
|
||||
user = User(email=email.strip().lower(), password_hash=hashed, login_password=hashed, system_role="admin", approved=True)
|
||||
return await self._repo.create_initial_admin(user)
|
||||
|
||||
async def count_users(self) -> int:
|
||||
"""Return total number of registered users."""
|
||||
return await self._repo.count_users()
|
||||
@@ -121,10 +118,29 @@ class LocalAuthProvider(AuthProvider):
|
||||
"""Update an existing user."""
|
||||
return await self._repo.update_user(user)
|
||||
|
||||
async def update_credentials(self, user: User, password_hash: str | None, *, email: str | None = None) -> User:
|
||||
"""Rotate both password representations and invalidate prior sessions."""
|
||||
return await self._repo.update_credentials(user, password_hash, email=email)
|
||||
|
||||
async def start_login_session(self, user: User) -> User:
|
||||
return await self._repo.start_login_session(user)
|
||||
|
||||
async def list_users(self) -> list[User]:
|
||||
"""Return all registered users ordered by creation date."""
|
||||
return await self._repo.list_users()
|
||||
|
||||
async def list_users_page(
|
||||
self, *, q: str | None = None, limit: int = 20, offset: int = 0
|
||||
) -> list[User]:
|
||||
"""Return one page of users (optionally filtered by ``q``)."""
|
||||
return await self._repo.list_users_page(q=q, limit=limit, offset=offset)
|
||||
|
||||
async def count_users_filtered(
|
||||
self, *, q: str | None = None, approved_or_admin: bool = False
|
||||
) -> int:
|
||||
"""Count users with the same ``q`` filter; optionally approved/admin only."""
|
||||
return await self._repo.count_users_filtered(q=q, approved_or_admin=approved_or_admin)
|
||||
|
||||
async def get_user_by_email(self, email: str) -> User | None:
|
||||
"""Get user by email."""
|
||||
return await self._repo.get_user_by_email(email)
|
||||
@@ -29,9 +29,9 @@ class User(BaseModel):
|
||||
|
||||
# Auth lifecycle
|
||||
needs_setup: bool = Field(default=False, description="True for auto-created admin until setup completes")
|
||||
token_version: int = Field(default=0, description="Incremented on password change to invalidate old JWTs")
|
||||
token_version: int = Field(default=0, description="Incremented on password change or a successful login under the single-session policy")
|
||||
approved: bool = Field(default=True, description="登录白名单放行标记(黑名单模式);仅当系统设置 login_whitelist.enabled 打开时拦截被取消放行的用户。新账号默认放行(True),管理员可「取消放行」(False)封禁个别用户。")
|
||||
login_password: str | None = Field(default=None, description="管理员在白名单管理页给该账号设置的「登录口令」(明文,仅 admin 可见)。非空 → 该账号用户名直登必须带匹配的 ?password=;为空 → 走原有共享口令门/免口令逻辑。")
|
||||
login_password: str | None = Field(default=None, description="Unified password/passphrase hash; legacy plaintext remains readable for compatibility.")
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
@@ -41,3 +41,6 @@ class UserResponse(BaseModel):
|
||||
email: str
|
||||
system_role: Literal["admin", "user"]
|
||||
needs_setup: bool = False
|
||||
has_password: bool = False
|
||||
requires_current_password: bool = True
|
||||
uses_default_password: bool = False
|
||||
@@ -9,15 +9,19 @@ Hash format: ``$dfv<N>$<bcrypt_hash>`` where ``<N>`` is the version.
|
||||
to the hash.
|
||||
|
||||
Verification auto-detects the version and falls back to v1 for hashes
|
||||
without a prefix, so existing deployments upgrade transparently on next
|
||||
login.
|
||||
without a prefix, so existing credentials stay valid until their next explicit
|
||||
password change writes the current format.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
|
||||
import bcrypt
|
||||
|
||||
from deerflow.config import get_app_config
|
||||
|
||||
_CURRENT_VERSION = 2
|
||||
_PREFIX_V2 = "$dfv2$"
|
||||
@@ -79,3 +83,30 @@ async def verify_password_async(plain_password: str, hashed_password: str) -> bo
|
||||
blocking the event loop during password verification.
|
||||
"""
|
||||
return await asyncio.to_thread(verify_password, plain_password, hashed_password)
|
||||
|
||||
|
||||
def is_password_hash(value: str) -> bool:
|
||||
"""Recognize current and historical hashes without exposing them in APIs."""
|
||||
return bool(re.fullmatch(r"(?:\$dfv[12]\$)?\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}", value))
|
||||
|
||||
|
||||
def has_account_password(user) -> bool:
|
||||
return bool(getattr(user, "login_password", None) or getattr(user, "password_hash", None))
|
||||
|
||||
|
||||
async def verify_account_password(password: str, user) -> bool:
|
||||
"""The historical personal passphrase takes precedence over the old hash.
|
||||
|
||||
New credentials store the same hash in both columns. Legacy plaintext
|
||||
passphrases remain accepted, including when an older password_hash differs.
|
||||
Accounts without either credential use the deployment's shared passphrase
|
||||
(the historical fallback is 123ewq), regardless of its old require flag.
|
||||
"""
|
||||
if getattr(user, "login_password", None):
|
||||
if is_password_hash(user.login_password):
|
||||
return await verify_password_async(password, user.login_password)
|
||||
return hmac.compare_digest(password.encode("utf-8"), user.login_password.encode("utf-8"))
|
||||
if getattr(user, "password_hash", None):
|
||||
return await verify_password_async(password, user.password_hash)
|
||||
fallback = get_app_config().auth_login.username_login.effective_password
|
||||
return hmac.compare_digest(password.encode("utf-8"), fallback.encode("utf-8"))
|
||||
@@ -15,6 +15,10 @@ class UserNotFoundError(LookupError):
|
||||
"""
|
||||
|
||||
|
||||
class CredentialConflictError(ValueError):
|
||||
"""Credentials changed after the caller authenticated the old password."""
|
||||
|
||||
|
||||
class UserRepository(ABC):
|
||||
"""Abstract interface for user data storage.
|
||||
|
||||
@@ -61,6 +65,15 @@ class UserRepository(ABC):
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_users_by_ids(self, user_ids: list[str]) -> list[User]:
|
||||
"""Batch lookup users; fallback keeps lightweight repositories compatible."""
|
||||
users = []
|
||||
for user_id in dict.fromkeys(user_ids):
|
||||
user = await self.get_user_by_id(user_id)
|
||||
if user is not None:
|
||||
users.append(user)
|
||||
return users
|
||||
|
||||
@abstractmethod
|
||||
async def find_user_by_email_local_part(self, local_part: str) -> User | None:
|
||||
"""Find a user by the local part of their email (the bit before ``@``).
|
||||
@@ -99,6 +112,26 @@ class UserRepository(ABC):
|
||||
"""
|
||||
return []
|
||||
|
||||
async def update_credentials(self, user: User, password_hash: str | None, *, email: str | None = None) -> User:
|
||||
"""Fallback for non-SQL implementations; SQL overrides with atomic CAS."""
|
||||
user.password_hash = password_hash
|
||||
user.login_password = password_hash
|
||||
user.token_version += 1
|
||||
user.needs_setup = False
|
||||
if email is not None:
|
||||
user.email = email
|
||||
return await self.update_user(user)
|
||||
|
||||
async def create_initial_admin(self, user: User) -> User:
|
||||
if await self.count_admin_users():
|
||||
raise ValueError("System already initialized")
|
||||
return await self.create_user(user)
|
||||
|
||||
async def start_login_session(self, user: User) -> User:
|
||||
"""Invalidate earlier sessions after a successful credential check."""
|
||||
user.token_version += 1
|
||||
return await self.update_user(user)
|
||||
|
||||
@abstractmethod
|
||||
async def update_user(self, user: User) -> User:
|
||||
"""Update an existing user.
|
||||
@@ -131,6 +164,25 @@ class UserRepository(ABC):
|
||||
"""Return all users ordered by creation date."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def list_users_page(
|
||||
self, *, q: str | None = None, limit: int = 20, offset: int = 0
|
||||
) -> list[User]:
|
||||
"""Return one page of users ordered by creation date.
|
||||
|
||||
``q`` optionally matches (case-insensitive substring) email or user id.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def count_users_filtered(
|
||||
self, *, q: str | None = None, approved_or_admin: bool = False
|
||||
) -> int:
|
||||
"""Count users, optionally filtered by the same ``q`` as
|
||||
:meth:`list_users_page`; ``approved_or_admin`` restricts to users the
|
||||
login whitelist would let in (approved or admin role)."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def get_user_by_oauth(self, provider: str, oauth_id: str) -> User | None:
|
||||
"""Get user by OAuth provider and ID.
|
||||
|
||||
@@ -15,13 +15,13 @@ from __future__ import annotations
|
||||
from datetime import UTC
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy import func, or_, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from app.gateway.auth.models import User
|
||||
from app.gateway.auth.repositories.base import UserNotFoundError, UserRepository
|
||||
from deerflow.persistence.user.model import UserRow
|
||||
from app.gateway.auth.repositories.base import CredentialConflictError, UserNotFoundError, UserRepository
|
||||
from deerflow.persistence.user.model import AuthInitializationRow, AuthUsernameRow, UserRow
|
||||
|
||||
|
||||
class SQLiteUserRepository(UserRepository):
|
||||
@@ -55,6 +55,7 @@ class SQLiteUserRepository(UserRepository):
|
||||
return UserRow(
|
||||
id=str(user.id),
|
||||
email=user.email,
|
||||
username_key=(user.email or "").split("@", 1)[0].strip().lower()[:128],
|
||||
password_hash=user.password_hash,
|
||||
system_role=user.system_role,
|
||||
created_at=user.created_at,
|
||||
@@ -72,6 +73,7 @@ class SQLiteUserRepository(UserRepository):
|
||||
"""Insert a new user. Raises ``ValueError`` on duplicate email."""
|
||||
row = self._user_to_row(user)
|
||||
async with self._sf() as session:
|
||||
await self._reserve_username(session, user.email)
|
||||
session.add(row)
|
||||
try:
|
||||
await session.commit()
|
||||
@@ -80,37 +82,102 @@ class SQLiteUserRepository(UserRepository):
|
||||
raise ValueError(f"Email already registered: {user.email}") from exc
|
||||
return user
|
||||
|
||||
@staticmethod
|
||||
async def _reserve_username(session: AsyncSession, email: str) -> None:
|
||||
"""Fence new registrations without rewriting historical user rows."""
|
||||
local = email.split("@", 1)[0].lower()
|
||||
escaped = local.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
existing = await session.scalar(select(UserRow.id).where(UserRow.username_key == local).limit(1))
|
||||
if existing is None:
|
||||
existing = await session.scalar(
|
||||
select(UserRow.id)
|
||||
.where(func.lower(UserRow.email).like(f"{escaped}@%", escape="\\"))
|
||||
.limit(1)
|
||||
)
|
||||
if existing is not None:
|
||||
raise ValueError("Username already registered")
|
||||
session.add(AuthUsernameRow(username=local))
|
||||
|
||||
async def create_initial_admin(self, user: User) -> User:
|
||||
"""Claim a singleton and create the first admin in one transaction.
|
||||
|
||||
A unique primary key fences concurrent requests across Gateway workers,
|
||||
including requests using different email addresses.
|
||||
"""
|
||||
async with self._sf() as session:
|
||||
count = await session.scalar(select(func.count()).select_from(UserRow).where(UserRow.system_role == "admin"))
|
||||
if count:
|
||||
raise ValueError("System already initialized")
|
||||
await self._reserve_username(session, user.email)
|
||||
session.add(AuthInitializationRow(id="initial-admin"))
|
||||
session.add(self._user_to_row(user))
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError as exc:
|
||||
await session.rollback()
|
||||
raise ValueError("System already initialized") from exc
|
||||
return user
|
||||
|
||||
async def get_user_by_id(self, user_id: str) -> User | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(UserRow, user_id)
|
||||
return self._row_to_user(row) if row is not None else None
|
||||
|
||||
async def get_users_by_ids(self, user_ids: list[str]) -> list[User]:
|
||||
wanted = list(dict.fromkeys(user_id for user_id in user_ids if user_id))
|
||||
if not wanted:
|
||||
return []
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(select(UserRow).where(UserRow.id.in_(wanted)))
|
||||
return [self._row_to_user(row) for row in result.scalars()]
|
||||
|
||||
async def get_user_by_email(self, email: str) -> User | None:
|
||||
stmt = select(UserRow).where(UserRow.email == email)
|
||||
normalized = email.strip().lower()
|
||||
stmt = select(UserRow).where(UserRow.email == normalized).order_by(UserRow.created_at.asc()).limit(1)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
row = result.scalar_one_or_none()
|
||||
if row is None:
|
||||
result = await session.execute(
|
||||
select(UserRow)
|
||||
.where(func.lower(UserRow.email) == normalized)
|
||||
.order_by(UserRow.created_at.asc())
|
||||
.limit(1)
|
||||
)
|
||||
row = result.scalar_one_or_none()
|
||||
return self._row_to_user(row) if row is not None else None
|
||||
|
||||
async def find_user_by_email_local_part(self, local_part: str) -> User | None:
|
||||
local = (local_part or "").strip().lower()
|
||||
if not local:
|
||||
return None
|
||||
# Escape SQL LIKE wildcards so usernames like ``foo_bar`` or ``a%b`` do
|
||||
# Compatibility fallback for rows predating the indexed username key.
|
||||
# not match unrelated rows. ``\`` is the chosen escape char below.
|
||||
escaped = local.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
pattern = f"{escaped}@%"
|
||||
# Case-insensitive prefix match on the email field, oldest first so a
|
||||
# subsequent registration cannot shadow an existing account.
|
||||
stmt = (
|
||||
select(UserRow)
|
||||
.where(func.lower(UserRow.email).like(pattern, escape="\\"))
|
||||
.order_by(UserRow.created_at.asc())
|
||||
.limit(1)
|
||||
)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
result = await session.execute(
|
||||
select(UserRow)
|
||||
.where(UserRow.username_key == local)
|
||||
.order_by(UserRow.created_at.asc())
|
||||
.limit(1)
|
||||
)
|
||||
row = result.scalar_one_or_none()
|
||||
if row is None:
|
||||
result = await session.execute(
|
||||
select(UserRow)
|
||||
.where(func.lower(UserRow.email).like(pattern, escape="\\"))
|
||||
.order_by(UserRow.created_at.asc())
|
||||
.limit(1)
|
||||
)
|
||||
row = result.scalar_one_or_none()
|
||||
if row is not None and not row.username_key:
|
||||
await session.execute(
|
||||
update(UserRow)
|
||||
.where(UserRow.id == row.id, UserRow.username_key.is_(None))
|
||||
.values(username_key=local)
|
||||
)
|
||||
await session.commit()
|
||||
return self._row_to_user(row) if row is not None else None
|
||||
|
||||
async def find_users_by_email_local_part_like(self, substring: str, *, limit: int = 500) -> list[User]:
|
||||
@@ -124,12 +191,7 @@ class SQLiteUserRepository(UserRepository):
|
||||
# Prefilter in SQL on the whole email (portable across sqlite/postgres/
|
||||
# mysql), then keep only rows whose *local part* contains the term so a
|
||||
# domain-only hit (e.g. searching "gmail") doesn't pull unrelated users.
|
||||
stmt = (
|
||||
select(UserRow)
|
||||
.where(func.lower(UserRow.email).like(pattern, escape="\\"))
|
||||
.order_by(UserRow.created_at.asc())
|
||||
.limit(max(1, limit))
|
||||
)
|
||||
stmt = select(UserRow).where(func.lower(UserRow.email).like(pattern, escape="\\")).order_by(UserRow.created_at.asc()).limit(max(1, limit))
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
rows = result.scalars().all()
|
||||
@@ -142,27 +204,88 @@ class SQLiteUserRepository(UserRepository):
|
||||
|
||||
async def update_user(self, user: User) -> User:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(UserRow, str(user.id))
|
||||
if row is None:
|
||||
# Hard fail on concurrent delete: callers (reset_admin,
|
||||
# password change handlers, _ensure_admin_user) all
|
||||
# fetched the user just before this call, so a missing
|
||||
# row here means the row vanished underneath us. Silent
|
||||
# success would let the caller log "password reset" for
|
||||
# a row that no longer exists.
|
||||
raise UserNotFoundError(f"User {user.id} no longer exists")
|
||||
row.email = user.email
|
||||
row.password_hash = user.password_hash
|
||||
row.system_role = user.system_role
|
||||
row.oauth_provider = user.oauth_provider
|
||||
row.oauth_id = user.oauth_id
|
||||
row.needs_setup = user.needs_setup
|
||||
row.token_version = user.token_version
|
||||
row.approved = user.approved
|
||||
row.login_password = user.login_password
|
||||
# Profile/approval writes cannot restore credentials from a stale
|
||||
# User object after a concurrent password reset.
|
||||
result = await session.execute(
|
||||
update(UserRow)
|
||||
.where(UserRow.id == str(user.id), UserRow.token_version == user.token_version)
|
||||
.values(
|
||||
email=user.email,
|
||||
username_key=(user.email or "").split("@", 1)[0].strip().lower()[:128],
|
||||
system_role=user.system_role,
|
||||
oauth_provider=user.oauth_provider,
|
||||
oauth_id=user.oauth_id,
|
||||
needs_setup=user.needs_setup,
|
||||
approved=user.approved,
|
||||
)
|
||||
)
|
||||
if result.rowcount != 1:
|
||||
row = await session.get(UserRow, str(user.id))
|
||||
await session.rollback()
|
||||
if row is None:
|
||||
raise UserNotFoundError(f"User {user.id} no longer exists")
|
||||
raise CredentialConflictError("账号密码已更新,请刷新后重试")
|
||||
await session.commit()
|
||||
return user
|
||||
|
||||
async def update_credentials(self, user: User, password_hash: str | None, *, email: str | None = None) -> User:
|
||||
values = {
|
||||
"password_hash": password_hash,
|
||||
"login_password": password_hash,
|
||||
"token_version": UserRow.token_version + 1,
|
||||
"needs_setup": False,
|
||||
}
|
||||
if email is not None:
|
||||
values["email"] = email
|
||||
values["username_key"] = email.split("@", 1)[0].strip().lower()[:128]
|
||||
async with self._sf() as session:
|
||||
if email is not None and email.split("@", 1)[0].lower() != user.email.split("@", 1)[0].lower():
|
||||
await self._reserve_username(session, email)
|
||||
with session.no_autoflush:
|
||||
result = await session.execute(update(UserRow).where(UserRow.id == str(user.id), UserRow.token_version == user.token_version).values(**values))
|
||||
if result.rowcount != 1:
|
||||
await session.rollback()
|
||||
raise CredentialConflictError("账号密码已更新,请重新登录后操作")
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError as exc:
|
||||
await session.rollback()
|
||||
raise ValueError("Email already registered") from exc
|
||||
user.password_hash = password_hash
|
||||
user.login_password = password_hash
|
||||
user.token_version += 1
|
||||
user.needs_setup = False
|
||||
if email is not None:
|
||||
user.email = email
|
||||
return user
|
||||
|
||||
async def start_login_session(self, user: User) -> User:
|
||||
"""Atomically fence older logins without accepting a concurrently reset password.
|
||||
|
||||
Ordinary login races may advance the version again; the last issued
|
||||
generation alone remains usable. Credential/approval changes after the
|
||||
original check require the caller to authenticate again instead.
|
||||
"""
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(
|
||||
update(UserRow)
|
||||
.where(
|
||||
UserRow.id == str(user.id),
|
||||
UserRow.password_hash == user.password_hash,
|
||||
UserRow.login_password == user.login_password,
|
||||
UserRow.approved == user.approved,
|
||||
UserRow.system_role == user.system_role,
|
||||
)
|
||||
.values(token_version=UserRow.token_version + 1)
|
||||
)
|
||||
if result.rowcount != 1:
|
||||
await session.rollback()
|
||||
raise CredentialConflictError("账号凭据或权限已变更,请重新登录")
|
||||
row = (await session.execute(select(UserRow).where(UserRow.id == str(user.id)))).scalar_one()
|
||||
saved = self._row_to_user(row)
|
||||
await session.commit()
|
||||
return saved
|
||||
|
||||
async def count_users(self) -> int:
|
||||
stmt = select(func.count()).select_from(UserRow)
|
||||
async with self._sf() as session:
|
||||
@@ -179,6 +302,40 @@ class SQLiteUserRepository(UserRepository):
|
||||
result = await session.execute(stmt)
|
||||
return [self._row_to_user(row) for row in result.scalars()]
|
||||
|
||||
@staticmethod
|
||||
def _user_search_filter(q: str | None):
|
||||
"""Case-insensitive substring match on email or user id (None → no filter)."""
|
||||
if not q or not q.strip():
|
||||
return None
|
||||
needle = f"%{q.strip().lower()}%"
|
||||
return or_(
|
||||
func.lower(UserRow.email).like(needle),
|
||||
func.lower(UserRow.id).like(needle),
|
||||
)
|
||||
|
||||
async def list_users_page(
|
||||
self, *, q: str | None = None, limit: int = 20, offset: int = 0
|
||||
) -> list[User]:
|
||||
stmt = select(UserRow).order_by(UserRow.created_at.asc()).limit(limit).offset(offset)
|
||||
search = self._user_search_filter(q)
|
||||
if search is not None:
|
||||
stmt = stmt.where(search)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [self._row_to_user(row) for row in result.scalars()]
|
||||
|
||||
async def count_users_filtered(
|
||||
self, *, q: str | None = None, approved_or_admin: bool = False
|
||||
) -> int:
|
||||
stmt = select(func.count()).select_from(UserRow)
|
||||
search = self._user_search_filter(q)
|
||||
if search is not None:
|
||||
stmt = stmt.where(search)
|
||||
if approved_or_admin:
|
||||
stmt = stmt.where(or_(UserRow.approved.is_(True), UserRow.system_role == "admin"))
|
||||
async with self._sf() as session:
|
||||
return await session.scalar(stmt) or 0
|
||||
|
||||
async def get_user_by_oauth(self, provider: str, oauth_id: str) -> User | None:
|
||||
stmt = select(UserRow).where(UserRow.oauth_provider == provider, UserRow.oauth_id == oauth_id)
|
||||
async with self._sf() as session:
|
||||
|
||||
@@ -64,8 +64,7 @@ async def _run(email: str | None) -> int:
|
||||
return 1
|
||||
|
||||
new_password = secrets.token_urlsafe(16)
|
||||
user.password_hash = hash_password(new_password)
|
||||
user.token_version += 1
|
||||
user = await repo.update_credentials(user, hash_password(new_password))
|
||||
user.needs_setup = True
|
||||
await repo.update_user(user)
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Credential assurance required by both Gateway and LangGraph sessions."""
|
||||
|
||||
from app.gateway.auth.jwt import TokenPayload
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
|
||||
|
||||
def session_policy_error(payload: TokenPayload) -> str | None:
|
||||
"""Return a rejection reason for a signed but no longer permitted session."""
|
||||
policy = load_system_settings().authentication
|
||||
if payload.auth_method == "sso" and not policy.sso_enabled:
|
||||
return "外部系统免登已关闭,请使用账号密码重新登录"
|
||||
if policy.password_login_enabled and payload.auth_method not in {"password", "passphrase", "sso"}:
|
||||
return "已开启登录验证,请重新登录"
|
||||
return None
|
||||
Reference in new issue
Block a user