sync: 鍚屾灞€鍩熺綉鏈€鏂颁唬鐮?(source master @ b69568e4)

This commit is contained in:
gozeros committed 2026-10-21 14:51:31 +08:00
1 parent 4f7f07504a
commit 8bc8b0e082
1651 files changed
+278599 -11416

No files matched your search

@@ -9,7 +9,7 @@ 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, field_validator, model_validator
from app.gateway.auth import (
UserResponse,
@@ -18,10 +18,12 @@ 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 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
@@ -106,17 +108,34 @@ 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):
@@ -160,8 +179,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)))
@@ -171,6 +190,12 @@ class MessageResponse(BaseModel):
"""Generic message response."""
message: str
class PasswordChangeResponse(MessageResponse):
access_token: str
token_type: str = "bearer"
expires_in: int
# ── Helpers ───────────────────────────────────────────────────────────────
@@ -227,24 +252,13 @@ async def _sync_user_position(request: Request, user_id: str) -> None:
logger.debug("position sync on login failed for user %s", user_id, exc_info=True)
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):
"""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)
@@ -265,10 +279,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 +290,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,35 +555,80 @@ 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(response: Response) -> AuthenticationOptions:
"""Anonymous, non-secret capability discovery for the login page."""
response.headers["Cache-Control"] = "no-store"
return AuthenticationOptions(
**load_system_settings().authentication.model_dump(),
needs_setup=await get_local_provider().count_admin_users() == 0,
)
@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)
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())
@router.post("/login/username", response_model=UsernameLoginResponse)
@@ -586,62 +636,51 @@ 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.
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.
"""Compatibility username login, gated by the current credential policy.
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.
"""
_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)
# 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)
@@ -675,6 +714,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,7 +734,8 @@ 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)
@@ -713,26 +754,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)
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 +798,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 +808,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 +889,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 +912,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 +920,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,7 +938,16 @@ 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
def _legacy_login_password(user: User) -> str | None:
value = user.login_password
return value if value and not is_password_hash(value) else None
@router.get("/users", response_model=list[UserListItem])
@@ -916,7 +981,8 @@ async def list_all_users(
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),
login_password=_legacy_login_password(u),
has_login_password=has_account_password(u),
)
)
return result
@@ -942,7 +1008,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 +1020,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 +1029,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 +1046,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 +1073,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 +1090,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 +1110,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",