feat(auth): 重构统一认证并支持平级服务无感登录

This commit is contained in:
sophie committed 2026-07-28 09:15:41 +08:00
1 parent d79def5519
commit ca312ea751
64 files changed
+3713 -449

No files matched your search

@@ -0,0 +1,20 @@
"""
backend/app/services/auth/hxops/__init__.py
用途:导出依赖 HXOPS User、数据库和会话契约的认证编排能力。
依赖:user_resolver、session_token、login_service、casdoor_user_sync。
逻辑:API 路由调用本包;平级服务不复制本目录。
"""
from .login_service import HxopsLoginService, LoginResult
from . import casdoor_user_sync
from .session_token import issue_hxops_access_token
from .user_resolver import resolve_hxops_user
__all__ = [
'HxopsLoginService',
'LoginResult',
'casdoor_user_sync',
'issue_hxops_access_token',
'resolve_hxops_user',
]
@@ -0,0 +1,315 @@
"""
backend/app/services/auth/hxops/casdoor_user_sync.py
用途:集中实现 HXOPS 用户创建和改密到 Casdoor 的管理端同步。
依赖:Flask 配置、requests、HXOPS User 模型、公共 Casdoor 错误解析。
逻辑:管理端事务调用本模块;HTTP 失败映射为稳定 AppError,由上层决定回滚。
"""
from __future__ import annotations
from typing import Any, Callable
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError
from app.models import User
from app.services.auth.casdoor.errors import clean_str, extract_error_payload, is_password_error
AddUserOperation = Callable[[dict[str, Any]], None]
SetPasswordOperation = Callable[[str, str, str, str], None]
def is_casdoor_configured() -> bool:
"""检查用户同步所需的 organization、地址和客户端凭据是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner,缺失时阻止构造无效用户请求。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def is_user_exists_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示用户名或用户记录已存在。"""
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_user_missing_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示 IdP 中不存在目标用户。"""
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
def raise_user_not_in_idp(source=None) -> None:
"""将 IdP 缺失用户转换为稳定业务错误,避免上层解析供应商文本。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_exists_error(lowered):
raise ConflictError(
'Username already exists in Casdoor',
code='USER.USERNAME_EXISTS',
details={'field': 'username', 'technical': msg_text},
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(
code='CASDOOR_ADD_USER_FAILED',
message='Failed to create user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError(
'Email already exists in Casdoor',
code='USER.EMAIL_EXISTS',
details={'field': 'email', 'technical': msg_text},
)
raise AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor 用户资料字段,不包含任何密码。"""
payload: dict[str, Any] = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': clean_str(real_name) or username,
'realName': clean_str(real_name) or '',
'phone': clean_str(phone_number) or '',
'isForbidden': clean_str(status) not in (None, 'active'),
}
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
return payload
def build_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor add-user 请求体,并只在创建场景附加明文密码。"""
payload = build_user_profile_payload(
username=username,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def _management_config() -> tuple[str, str, str, int]:
"""读取 Casdoor 管理 API 配置,返回地址、凭据和 HTTP 超时。"""
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '')
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
timeout = max(1, int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8))
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
return base, client_id, client_secret, timeout
def casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/add-user` 创建 IdP 用户。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/add-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor add-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/update-user` 更新 IdP 用户资料。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/update-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor update-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor `/api/set-password` 修改或由管理员覆盖用户密码。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/set-password',
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor set-password failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_set_password_error(data)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
add_user: AddUserOperation | None = None,
) -> None:
"""管理端创建 HXOPS 用户时同步 Casdoor;未配置 IdP 时保持原有跳过行为。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
(add_user or casdoor_add_user)(payload)
def sync_admin_set_password(
user: User,
new_password: str,
*,
set_password: SetPasswordOperation | None = None,
) -> None:
"""管理端无旧密码重设 Casdoor 密码,并将缺失用户转换为稳定错误。"""
if not is_casdoor_configured():
return
try:
(set_password or casdoor_set_password)(casdoor_user_owner(), user.username, '', new_password)
except RuntimeError as exc:
if is_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
def sync_update_user(
user: User,
*,
new_password: str | None = None,
set_password: SetPasswordOperation | None = None,
add_user: AddUserOperation | None = None,
) -> None:
"""同步管理端改密;IdP 缺失账号时用新密码补建,资料编辑仍不主动同步。"""
if not is_casdoor_configured() or not new_password:
return
try:
sync_admin_set_password(user, new_password, set_password=set_password)
except AppError as exc:
if exc.code != 'CASDOOR_USER_NOT_IN_IDP':
raise
sync_create_user(
username=user.username,
password=new_password,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
add_user=add_user,
)
@@ -0,0 +1,196 @@
"""
backend/app/services/auth/hxops/login_service.py
用途:统一编排 HXOPS 的 Casdoor 密码登录、授权码登录和刷新流程。
依赖:Casdoor token/identity 公共模块、HXOPS 用户映射、HXOPS API Token。
逻辑:Casdoor token -> claims -> AuthIdentity -> HXOPS User -> 本地 API JWT;路由仅负责参数和事务边界。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
from flask import current_app
from app.core.auth.jwt import _decode_jwt
from app.core.errors import AppError
from app.models import User
from app.services.auth.casdoor.client import CasdoorTokenResult
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import AuthIdentity, IdentityValidationError
from .session_token import issue_hxops_access_token
from .user_resolver import HxopsIdentityMappingError, resolve_hxops_user
TokenOperation = Callable[..., CasdoorTokenResult | dict[str, Any]]
UserinfoOperation = Callable[[str], dict[str, Any]]
AuditOperation = Callable[..., None]
@dataclass(frozen=True)
class LoginResult:
"""HXOPS 登录接口所需的用户、Token 和原响应有效期数据。"""
user: User
identity: AuthIdentity
access_token: str
refresh_token: str | None
id_token: str | None
token_type: str
expires_in: int
def login_payload(self) -> dict[str, Any]:
"""生成与现有 password/code 登录接口完全一致的扁平响应。"""
return {
'id': self.user.id,
'username': self.user.username,
'role': self.user.role,
'default_agent_id': self.user.default_agent_id,
'feature_permissions': self.user.get_feature_permissions(),
'source': 'casdoor',
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def refresh_payload(self) -> dict[str, Any]:
"""生成与现有 refresh 接口完全一致的 Token 响应。"""
return {
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def _normalize_token_result(source: CasdoorTokenResult | dict[str, Any]) -> CasdoorTokenResult:
"""兼容重构期间旧字典替身和新的 CasdoorTokenResult。"""
if isinstance(source, CasdoorTokenResult):
return source
data = dict(source or {})
access_token = str(data.get('access_token') or '')
if not access_token:
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=401)
return CasdoorTokenResult(
access_token=access_token,
refresh_token=str(data['refresh_token']) if data.get('refresh_token') else None,
id_token=str(data['id_token']) if data.get('id_token') else None,
token_type=str(data.get('token_type') or 'Bearer'),
expires_in=int(data.get('expires_in') or 3600),
raw=data,
)
class HxopsLoginService:
"""把公共 Casdoor 能力与 HXOPS 用户、审计和 API JWT 组合起来。"""
def __init__(
self,
*,
password_login: TokenOperation,
authorization_code_login: TokenOperation,
refresh_token: TokenOperation,
userinfo: UserinfoOperation,
write_login_audit: AuditOperation | None = None,
decode_id_token: Callable[[str], dict[str, Any]] = _decode_jwt,
):
"""
注入 Casdoor 操作和可选审计函数,便于路由兼容与单元测试。
Args:
password_login: 执行 password grant 的函数。
authorization_code_login: 执行 code grant 的函数。
refresh_token: 执行 refresh grant 的函数。
userinfo: 读取 Casdoor userinfo 的函数。
write_login_audit: HXOPS 登录审计函数;公共模块不感知请求对象。
decode_id_token: 现有 Casdoor JWKS 验证函数。
"""
self._password_login = password_login
self._authorization_code_login = authorization_code_login
self._refresh_token = refresh_token
self._userinfo = userinfo
self._write_login_audit = write_login_audit
self._decode_id_token = decode_id_token
def _identity_from_token(self, token: CasdoorTokenResult, *, prefer_id_token: bool) -> AuthIdentity:
"""优先验证 ID token,失败或缺失时回退 HTTPS userinfo。"""
claims: dict[str, Any] | None = None
if prefer_id_token and token.id_token:
try:
claims = self._decode_id_token(token.id_token)
except Exception:
claims = None
if claims is None:
claims = self._userinfo(token.access_token)
try:
return identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
)
except IdentityValidationError as exc:
current_app.logger.warning(
'[casdoor_login] invalid stable identity reason=%s claim_keys=%s',
str(exc),
sorted(str(key) for key in claims.keys()),
)
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
def _complete_login(
self,
token_source: CasdoorTokenResult | dict[str, Any],
*,
prefer_id_token: bool,
fallback_refresh_token: str | None = None,
audit_success: bool = False,
) -> LoginResult:
"""完成身份解析、本地用户映射和 HXOPS API Token 签发。"""
token = _normalize_token_result(token_source)
identity = self._identity_from_token(token, prefer_id_token=prefer_id_token)
try:
user = resolve_hxops_user(identity)
except HxopsIdentityMappingError as exc:
raise AppError(code=exc.code, message=str(exc), http_status=exc.status) from exc
if audit_success and self._write_login_audit:
self._write_login_audit('casdoor', 'success', user=user)
return LoginResult(
user=user,
identity=identity,
access_token=issue_hxops_access_token(user, identity),
refresh_token=token.refresh_token or fallback_refresh_token,
id_token=token.id_token,
token_type=token.token_type,
expires_in=token.expires_in,
)
def password(self, username: str, password: str) -> LoginResult:
"""通过 Casdoor password grant 登录 HXOPS。"""
return self._complete_login(
self._password_login(username, password),
prefer_id_token=True,
audit_success=True,
)
def authorization_code(self, code: str, redirect_uri: str) -> LoginResult:
"""通过 Casdoor authorization code 登录 HXOPS。"""
return self._complete_login(
self._authorization_code_login(code, redirect_uri),
prefer_id_token=True,
audit_success=True,
)
def refresh(self, refresh_token: str) -> LoginResult:
"""刷新 Casdoor token 后重新确认身份并签发 HXOPS API JWT。"""
return self._complete_login(
self._refresh_token(refresh_token),
prefer_id_token=False,
fallback_refresh_token=refresh_token,
)
@@ -0,0 +1,31 @@
"""
backend/app/services/auth/hxops/session_token.py
用途:为 HXOPS 本地 API 签发包含 Casdoor 稳定身份引用的会话 JWT。
依赖:User、AuthIdentity、app.core.auth.jwt 现有签发函数。
逻辑:保留现有 HS256 claims 和有效期;只调整调用边界,不改变 Token 契约。
"""
from __future__ import annotations
from app.core.auth.jwt import issue_local_access_token
from app.models import User
from app.services.auth.common import AuthIdentity
def issue_hxops_access_token(user: User, identity: AuthIdentity | None = None) -> str:
"""
签发 HXOPS API 会话 JWT,保持重构前 claims 完全兼容。
Args:
user: 已映射并检查 active 的 HXOPS 用户。
identity: 可选 Casdoor 稳定身份;存在时写入 casdoor_iss/casdoor_sub。
Returns:
由 HXOPS SECRET_KEY 签名的本站 Bearer Token。
"""
return issue_local_access_token(
user,
casdoor_issuer=identity.issuer if identity else None,
casdoor_subject=identity.subject if identity else None,
)
@@ -0,0 +1,57 @@
"""
backend/app/services/auth/hxops/user_resolver.py
用途:将统一 AuthIdentity 映射为 HXOPS 本地 User。
依赖:Flask 日志、SQLAlchemy session、User、AuthIdentity。
逻辑:当前阶段保持原用户名优先、邮箱回退规则,并统一检查本地用户状态。
"""
from __future__ import annotations
from flask import current_app
from app.extensions import db
from app.models import User
from app.services.auth.common import AuthIdentity
class HxopsIdentityMappingError(Exception):
"""HXOPS 本地用户无法映射或状态不允许登录。"""
def __init__(self, message: str, *, code: str, status: int):
super().__init__(message)
self.code = code
self.status = status
def resolve_hxops_user(identity: AuthIdentity) -> User:
"""
按现有规则将认证身份映射到 HXOPS 用户。
Args:
identity: 已验证 Casdoor issuer/subject 的统一身份。
Returns:
状态为 active 的 HXOPS User。
Raises:
HxopsIdentityMappingError: 用户未同步到 HXOPS 或账号已禁用。
"""
current_app.logger.info(
'[casdoor_login] identity username=%s email=%s subject=%s',
identity.username,
identity.email,
identity.subject,
)
user = db.session.query(User).filter_by(username=identity.username).first()
if user is None and identity.email:
user = db.session.query(User).filter_by(email=identity.email).first()
if user is None:
raise HxopsIdentityMappingError(
'No local user matched Casdoor identity. Please contact admin to provision account.',
code='CASDOOR_USER_NOT_FOUND',
status=403,
)
if user.status != 'active':
raise HxopsIdentityMappingError('Account is disabled', code='ACCOUNT_DISABLED', status=403)
return user