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/casdoor/__init__.py
用途:导出不依赖 HXOPS User 模型的 Casdoor 认证公共能力。
依赖:config、client、identity、errors。
逻辑:HXOPS 与平级服务可复制本目录,并用各自配置适配器创建 CasdoorClient。
"""
from .client import CasdoorClient, CasdoorTokenResult, get_casdoor_client
from .config import CasdoorConfig, casdoor_config_from_flask
from .identity import identity_from_claims
__all__ = [
'CasdoorClient',
'CasdoorConfig',
'CasdoorTokenResult',
'casdoor_config_from_flask',
'get_casdoor_client',
'identity_from_claims',
]
+170
View File
@@ -0,0 +1,170 @@
"""
backend/app/services/auth/casdoor/client.py
用途:封装 Casdoor OAuth/OIDC HTTP 通信,供 HXOPS 与平级服务复制复用。
依赖:requests、CasdoorConfig、Casdoor 错误映射。
逻辑:所有 grant 和 userinfo 请求集中在此;模块不依赖 HXOPS User、数据库或业务权限。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from threading import Lock
from typing import Any
import requests
from .config import CasdoorConfig, casdoor_config_from_flask
from .errors import raise_auth_error
_CLIENT_CACHE_LOCK = Lock()
_CLIENT_CACHE_CONFIG: CasdoorConfig | None = None
_CLIENT_CACHE_VALUE: CasdoorClient | None = None
@dataclass(frozen=True)
class CasdoorTokenResult:
"""Casdoor token endpoint 返回的标准字段和原始扩展字段。"""
access_token: str
refresh_token: str | None
id_token: str | None
token_type: str
expires_in: int
raw: dict[str, Any]
def as_dict(self) -> dict[str, Any]:
"""返回兼容现有 HXOPS 路由和测试的 token 字典。"""
return dict(self.raw)
class CasdoorClient:
"""无业务模型依赖的 Casdoor OAuth/OIDC 客户端。"""
def __init__(self, config: CasdoorConfig, *, http_session=requests):
"""
创建客户端并注入配置和 HTTP 实现。
Args:
config: 当前服务自己的 Casdoor Application 配置。
http_session: 兼容 requests 的 HTTP 对象,测试可注入替身。
"""
self.config = config
self._http = http_session
self._metadata: dict[str, Any] | None = None
self._metadata_expires_at: datetime | None = None
self._metadata_lock = Lock()
def oidc_metadata(self) -> dict[str, Any]:
"""读取并缓存 OIDC discovery 文档 10 分钟。"""
now = datetime.now(timezone.utc)
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
return dict(self._metadata)
with self._metadata_lock:
now = datetime.now(timezone.utc)
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
return dict(self._metadata)
response = self._http.get(
f'{self.config.base_url}/.well-known/openid-configuration',
timeout=self.config.timeout_seconds,
)
response.raise_for_status()
data = response.json() or {}
if not isinstance(data, dict):
raise RuntimeError('Casdoor OIDC metadata is invalid')
self._metadata = data
self._metadata_expires_at = now + timedelta(minutes=10)
return dict(data)
def _token_endpoint(self) -> str:
"""从 discovery 文档读取 token endpoint,缺失时安全失败。"""
endpoint = str(self.oidc_metadata().get('token_endpoint') or '').strip()
if not endpoint:
raise RuntimeError('Casdoor token endpoint missing')
return endpoint
def _token_request(self, payload: dict[str, Any], *, context: str) -> CasdoorTokenResult:
"""执行 token endpoint 请求并统一解析成功或失败结果。"""
response = self._http.post(
self._token_endpoint(),
data=payload,
timeout=self.config.timeout_seconds,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor token request failed: HTTP {response.status_code}') from exc
if not response.ok or not data.get('access_token'):
raise_auth_error(data, context=context)
return CasdoorTokenResult(
access_token=str(data['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=dict(data),
)
def password_login(self, username: str, password: str) -> CasdoorTokenResult:
"""使用当前服务自己的 Casdoor Application 执行 password grant。"""
return self._token_request({
'grant_type': 'password',
'username': username,
'password': password,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
'scope': self.config.scope,
}, context='password')
def authorization_code_login(self, code: str, redirect_uri: str) -> CasdoorTokenResult:
"""将浏览器返回的 authorization code 兑换为 Casdoor token。"""
return self._token_request({
'grant_type': 'authorization_code',
'code': code,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
'redirect_uri': redirect_uri,
}, context='code')
def refresh(self, refresh_token: str) -> CasdoorTokenResult:
"""使用 Casdoor refresh token 获取新 token 集合。"""
return self._token_request({
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
}, context='refresh')
def userinfo(self, access_token: str) -> dict[str, Any]:
"""使用 Casdoor access token 获取可信用户声明。"""
endpoint = str(self.oidc_metadata().get('userinfo_endpoint') or '').strip()
if not endpoint:
raise RuntimeError('Casdoor userinfo endpoint missing')
response = self._http.get(
endpoint,
headers={'Authorization': f'Bearer {access_token}'},
timeout=self.config.timeout_seconds,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}') from exc
if not response.ok or not isinstance(data, dict):
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}')
return data
def get_casdoor_client() -> CasdoorClient:
"""复用当前配置对应的进程内客户端,配置变化时自动替换缓存实例。"""
global _CLIENT_CACHE_CONFIG, _CLIENT_CACHE_VALUE
config = casdoor_config_from_flask()
if _CLIENT_CACHE_VALUE is not None and _CLIENT_CACHE_CONFIG == config:
return _CLIENT_CACHE_VALUE
with _CLIENT_CACHE_LOCK:
if _CLIENT_CACHE_VALUE is None or _CLIENT_CACHE_CONFIG != config:
_CLIENT_CACHE_CONFIG = config
_CLIENT_CACHE_VALUE = CasdoorClient(config)
return _CLIENT_CACHE_VALUE
@@ -0,0 +1,68 @@
"""
backend/app/services/auth/casdoor/config.py
用途:定义纯 Casdoor 客户端配置及 HXOPS Flask 配置适配器。
依赖:dataclasses、flask.current_app、app.core.errors。
逻辑:公共客户端只接收 CasdoorConfig;不同服务只需替换配置适配器。
"""
from __future__ import annotations
from dataclasses import dataclass
from flask import current_app
from app.core.errors import AppError
@dataclass(frozen=True)
class CasdoorConfig:
"""Casdoor OAuth/OIDC 客户端运行参数,secret 不参与 repr。"""
base_url: str
client_id: str
client_secret: str
issuer: str
scope: str = 'openid profile email'
timeout_seconds: int = 8
def __repr__(self) -> str:
"""输出可诊断但不包含 client_secret 的配置摘要。"""
return (
'CasdoorConfig('
f'base_url={self.base_url!r}, client_id={self.client_id!r}, '
f'issuer={self.issuer!r}, scope={self.scope!r}, '
f'timeout_seconds={self.timeout_seconds!r})'
)
def casdoor_config_from_flask() -> CasdoorConfig:
"""
从当前 Flask 应用读取并校验 Casdoor 客户端配置。
Returns:
可交给 CasdoorClient 的不可变配置。
Raises:
AppError: 基础地址、客户端凭据或 issuer 未配置。
"""
base_url = str(current_app.config.get('CASDOOR_BASE_URL') or '').strip().rstrip('/')
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '').strip()
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip().rstrip('/')
scope = str(current_app.config.get('CASDOOR_SCOPE') or 'openid profile email').strip()
timeout_seconds = int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8)
if not base_url or not client_id or not client_secret or not issuer:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
return CasdoorConfig(
base_url=base_url,
client_id=client_id,
client_secret=client_secret,
issuer=issuer,
scope=scope or 'openid profile email',
timeout_seconds=max(1, timeout_seconds),
)
+106
View File
@@ -0,0 +1,106 @@
"""
backend/app/services/auth/casdoor/errors.py
用途:把 Casdoor OAuth/OIDC 失败转换为稳定业务错误码。
依赖:标准库解析工具、flask.current_app、app.core.errors。
逻辑:CasdoorClient 将失败响应交给本模块,API 层只处理统一 AppError。
"""
from __future__ import annotations
import ast
import json
import re
from flask import current_app
from app.core.errors import AppError, ValidationError
def clean_str(value) -> str | None:
"""去除字符串首尾空白,空值统一返回 None。"""
if value is None:
return None
return str(value).strip() or None
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应字典或异常文本中提取可识别错误字段。"""
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
return parsed if isinstance(parsed, dict) else {}
except (json.JSONDecodeError, TypeError):
return {}
def is_password_error(message: str) -> bool:
"""判断 Casdoor 错误是否表示用户名或密码无效。"""
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""
将 Casdoor 登录、授权码和刷新失败映射为稳定错误。
Args:
source: Casdoor JSON 错误体或捕获的异常。
context: ``password``、``code``、``refresh`` 或 ``verify``。
status_code: 未识别错误的默认 HTTP 状态码。
Raises:
AppError: 所有失败均转换为统一认证错误,不返回原始 token 或 secret。
"""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = (clean_str(data.get('error')) or '').lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or is_password_error(raw):
if context in {'password', 'verify'}:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in {'invalid_client', 'unauthorized_client'}:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is misconfigured. Please contact the administrator.',
http_status=503,
details={'casdoor_error': oauth_error},
)
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if oauth_error == 'unsupported_grant_type':
raise AppError(
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
message='Casdoor refresh token is not supported by current application config',
http_status=400,
)
lowered_raw = raw.lower()
if 'token endpoint missing' in lowered_raw or 'casdoor_base_url is not configured' in lowered_raw:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
if 'invalid or expired casdoor state' in lowered_raw:
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data)
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None},
)
@@ -0,0 +1,59 @@
"""
backend/app/services/auth/casdoor/identity.py
用途:将 Casdoor ID token/userinfo claims 转换为统一 AuthIdentity。
依赖:hmac、typing、services.auth.common.identity。
逻辑:严格绑定预期 issuer,提取稳定 subject 与可变用户资料,不访问业务数据库。
"""
from __future__ import annotations
import hmac
from collections.abc import Mapping
from typing import Any
from app.services.auth.common import AuthIdentity, IdentityValidationError, require_stable_identity
def _claim_text(claims: Mapping[str, Any], *keys: str) -> str | None:
"""按优先级读取第一个非空 claim 并转换为去空白字符串。"""
for key in keys:
value = claims.get(key)
if value is not None and str(value).strip():
return str(value).strip()
return None
def identity_from_claims(
claims: Mapping[str, Any],
*,
expected_issuer: str,
) -> AuthIdentity:
"""
将可信 Casdoor claims 转换为跨服务统一身份。
Args:
claims: 已验证 ID token 或通过 HTTPS 从 userinfo 获取的声明。
expected_issuer: 当前服务配置的可信 Casdoor issuer。
Returns:
不包含角色和业务权限的 AuthIdentity。
Raises:
IdentityValidationError: issuer 不匹配或缺少稳定 subject/username。
"""
trusted_issuer = str(expected_issuer or '').strip().rstrip('/')
claim_issuer = str(claims.get('iss') or trusted_issuer).strip().rstrip('/')
if not trusted_issuer or not claim_issuer or not hmac.compare_digest(claim_issuer, trusted_issuer):
raise IdentityValidationError('Casdoor identity issuer does not match the trusted issuer')
identity = AuthIdentity(
issuer=trusted_issuer,
subject=_claim_text(claims, 'sub') or '',
username=_claim_text(claims, 'preferred_username', 'name') or '',
display_name=_claim_text(claims, 'display_name', 'displayName', 'real_name', 'realName', 'name'),
email=_claim_text(claims, 'email'),
phone_number=_claim_text(claims, 'phone_number', 'phone'),
employee_id=_claim_text(claims, 'employee_id', 'employeeId'),
department=_claim_text(claims, 'department', 'affiliation'),
)
return require_stable_identity(identity)
+53 -321
View File
@@ -1,373 +1,105 @@
"""
backend/app/services/auth/casdoor_service.py
用途:Casdoor IdP 用户同步与 OAuth 错误映射(管理端创建/改密、用户域登录共用)。
依赖:flask.current_app、requests、app.core.errors。
逻辑:由 services/admin/user_service、api/user 登录路由调用。
用途:为历史调用点保留 Casdoor 错误与 HXOPS 用户同步兼容门面。
依赖:公共 casdoor.errors、HXOPS casdoor_user_sync。
逻辑:新代码按职责导入分层模块;旧路由、管理端和测试可继续替换本文件函数。
"""
from __future__ import annotations
import ast
import json
import re
from typing import Any
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError, ValidationError
from app.models import User
def clean_str(value) -> str | None:
"""Trim 字符串;空串返回 None。"""
if value is None:
return None
if isinstance(value, str):
value = value.strip()
return value or None
return str(value).strip() or None
from app.services.auth.casdoor.errors import (
clean_str,
extract_error_payload,
is_password_error,
raise_auth_error,
)
from app.services.auth.hxops import casdoor_user_sync as _sync
def is_casdoor_configured() -> bool:
"""Casdoor 基础配置是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = (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)
"""兼容入口:检查 Casdoor 用户同步配置。"""
return _sync.is_casdoor_configured()
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 extract_error_payload(source) -> dict:
"""从 Casdoor 响应或异常文本解析 JSON 错误体。"""
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
if isinstance(parsed, dict):
return parsed
except (json.JSONDecodeError, TypeError):
pass
return {}
"""兼容入口:返回 Casdoor organization owner。"""
return _sync.casdoor_user_owner()
def is_user_exists_error(message: str) -> bool:
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_password_error(message: str) -> bool:
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
"""兼容入口:判断 IdP 用户已存在错误。"""
return _sync.is_user_exists_error(message)
def is_user_missing_error(message: str) -> bool:
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
)
"""兼容入口:判断 IdP 用户不存在错误。"""
return _sync.is_user_missing_error(message)
def raise_user_not_in_idp(source=None) -> None:
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]},
)
"""兼容入口:抛出 IdP 缺失用户业务错误。"""
_sync.raise_user_not_in_idp(source)
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]},
)
"""兼容入口:映射 Casdoor 新增用户错误。"""
_sync.raise_add_user_error(source)
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]},
)
"""兼容入口:映射 Casdoor 更新用户错误。"""
_sync.raise_update_user_error(source)
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]},
)
"""兼容入口:映射 Casdoor 修改密码错误。"""
_sync.raise_set_password_error(source)
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""Map Casdoor OAuth/API failures to stable business error codes."""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = clean_str(data.get('error')).lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or is_password_error(raw):
if context in ('password', 'verify'):
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in ('invalid_client', 'unauthorized_client'):
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is misconfigured. Please contact the administrator.',
http_status=503,
details={'casdoor_error': oauth_error},
)
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
if 'invalid or expired casdoor state' in raw.lower():
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None, 'technical': raw[:300]},
)
def build_user_profile_payload(**kwargs) -> dict[str, Any]:
"""兼容入口:构造不含密码的 Casdoor 用户资料。"""
return _sync.build_user_profile_payload(**kwargs)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor 用户资料字段(不含 password)。"""
display_name = clean_str(real_name) or username
payload = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': display_name,
'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(**kwargs) -> dict[str, Any]:
"""兼容入口:构造 Casdoor 创建用户请求体。"""
return _sync.build_user_payload(**kwargs)
def build_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 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 casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 创建用户。"""
_sync.casdoor_add_user(user_payload)
def casdoor_add_user(user_payload: dict) -> None:
"""调用 Casdoor /api/add-user 创建 IdP 用户。"""
base = (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 ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/add-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict) -> None:
"""调用 Casdoor /api/update-user 更新 IdP 用户资料。"""
base = (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 ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/update-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 更新用户。"""
_sync.casdoor_update_user(user_payload)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor /api/set-password。"""
base = (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 ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/set-password'
resp = requests.post(
url,
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=8,
)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_set_password_error(data)
"""兼容入口:调用 Casdoor 修改密码。"""
_sync.casdoor_set_password(user_owner, user_name, old_password, new_password)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> None:
"""管理端创建用户时同步至 Casdoor。"""
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,
)
casdoor_add_user(payload)
def sync_create_user(**kwargs) -> None:
"""兼容入口:同步创建用户,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_create_user(**kwargs, add_user=casdoor_add_user)
def sync_admin_set_password(user: User, new_password: str) -> None:
"""管理端重设密码时同步 Casdoor(无旧密码)。"""
if not is_casdoor_configured():
return
user_owner = casdoor_user_owner()
try:
casdoor_set_password(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)
"""兼容入口:同步管理员改密,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_admin_set_password(user, new_password, set_password=casdoor_set_password)
def sync_update_user(user: User, *, new_password: str | None = None) -> None:
"""管理端编辑用户时同步 Casdoor:仅改密;IdP 无账号则 add-user 补建。"""
if not is_casdoor_configured() or not new_password:
return
def _provision_missing_user_in_casdoor():
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,
)
try:
sync_admin_set_password(user, new_password)
except AppError as exc:
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
_provision_missing_user_in_casdoor()
return
raise
"""兼容入口:同步用户改密或补建 IdP 账号,并保留测试替换点。"""
_sync.sync_update_user(
user,
new_password=new_password,
set_password=casdoor_set_password,
add_user=casdoor_add_user,
)
@@ -0,0 +1,16 @@
"""
backend/app/services/auth/common/__init__.py
用途:导出不依赖 HXOPS 数据模型的认证公共类型。
依赖:common.identity。
逻辑:Casdoor 客户端、HXOPS 登录和 SSO 模块通过本入口共享统一身份对象。
"""
from .identity import AuthIdentity, IdentityValidationError, identity_key, require_stable_identity
__all__ = [
'AuthIdentity',
'IdentityValidationError',
'identity_key',
'require_stable_identity',
]
@@ -0,0 +1,69 @@
"""
backend/app/services/auth/common/identity.py
用途:定义跨认证来源通用、可复制的稳定身份对象。
依赖:Python dataclasses;不依赖 Flask、SQLAlchemy 或 HXOPS User。
逻辑:Casdoor claims 先转换为 AuthIdentity,业务系统再按 issuer + subject 映射自己的用户。
"""
from __future__ import annotations
from dataclasses import dataclass
class IdentityValidationError(ValueError):
"""身份缺少跨服务稳定键时抛出,调用方负责映射为自身错误契约。"""
@dataclass(frozen=True)
class AuthIdentity:
"""认证系统返回的稳定身份和可变展示资料,不包含任何业务权限。"""
issuer: str
subject: str
username: str
display_name: str | None = None
email: str | None = None
phone_number: str | None = None
employee_id: str | None = None
department: str | None = None
def require_stable_identity(identity: AuthIdentity) -> AuthIdentity:
"""
校验跨服务身份必须具备 issuer、subject 和 username。
Args:
identity: 待校验的认证身份。
Returns:
去除稳定键首尾空白后的不可变身份对象。
Raises:
IdentityValidationError: 缺少稳定身份键或用户名。
"""
issuer = str(identity.issuer or '').strip()
subject = str(identity.subject or '').strip()
username = str(identity.username or '').strip()
if not issuer or not subject:
raise IdentityValidationError('Identity issuer and subject are required')
if not username:
raise IdentityValidationError('Identity username is required')
if issuer == identity.issuer and subject == identity.subject and username == identity.username:
return identity
return AuthIdentity(
issuer=issuer,
subject=subject,
username=username,
display_name=identity.display_name,
email=identity.email,
phone_number=identity.phone_number,
employee_id=identity.employee_id,
department=identity.department,
)
def identity_key(identity: AuthIdentity) -> tuple[str, str]:
"""返回业务系统建立外部身份映射时使用的唯一键 ``(issuer, subject)``。"""
stable = require_stable_identity(identity)
return stable.issuer, stable.subject
@@ -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
+18
View File
@@ -0,0 +1,18 @@
"""
backend/app/services/auth/sso/__init__.py
Purpose: Export the reusable HXOPS-to-peer-service SSO signing surface.
Dependencies: application registry and assertion signing modules.
Flow: API routes import this package; peer services consume the documented assertion/JWKS contract.
"""
from .application_registry import SsoApplication, get_application, list_applications
from .assertion_service import build_jwks, issue_assertion
__all__ = [
'SsoApplication',
'build_jwks',
'get_application',
'issue_assertion',
'list_applications',
]
@@ -0,0 +1,149 @@
"""
backend/app/services/auth/sso/application_registry.py
Purpose: Parse and validate peer services allowed to receive HXOPS SSO assertions.
Dependencies: Flask configuration, JSON, URL parsing, and AppError.
Flow: Assertion routes resolve app metadata here so browser-provided callback URLs are never trusted.
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from urllib.parse import urlparse
from flask import current_app
from app.core.errors import AppError, NotFoundError
_APP_KEY_RE = re.compile(r'^[a-z0-9][a-z0-9_-]{1,63}$')
@dataclass(frozen=True)
class SsoApplication:
"""Registered peer-service metadata safe for server-controlled SSO routing."""
key: str
display_name: str
login_url: str
callback_url: str
audience: str
enabled: bool = True
def public_payload(self) -> dict[str, str]:
"""Return fields safe for authenticated HXOPS navigation components."""
return {
'key': self.key,
'display_name': self.display_name,
'login_url': self.login_url,
}
def _validate_http_url(value: str, *, field: str) -> str:
"""
Validate an application URL from server configuration.
Args:
value: Absolute browser or callback URL.
field: Configuration field name used in diagnostics.
Returns:
Normalized URL without surrounding whitespace.
Raises:
AppError: URL is missing, malformed, or uses HTTP outside development/testing.
"""
normalized = str(value or '').strip()
parsed = urlparse(normalized)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'Invalid SSO application {field}',
http_status=503,
)
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'SSO application {field} must use HTTPS',
http_status=503,
)
return normalized
def list_applications() -> list[SsoApplication]:
"""
Parse the enabled SSO application registry from ``SSO_APPS_JSON``.
Returns:
Valid enabled application definitions.
Raises:
AppError: Configuration is invalid. Fail closed to avoid open redirects.
"""
if not bool(current_app.config.get('SSO_ENABLED', False)):
return []
raw = current_app.config.get('SSO_APPS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry is invalid',
http_status=503,
) from exc
if not isinstance(items, list):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry must be a JSON array',
http_status=503,
)
applications: list[SsoApplication] = []
seen_keys: set[str] = set()
seen_audiences: set[str] = set()
for item in items:
if not isinstance(item, dict) or not bool(item.get('enabled', True)):
continue
key = str(item.get('key') or '').strip().lower()
audience = str(item.get('audience') or key).strip()
display_name = str(item.get('display_name') or key).strip()
if (
not _APP_KEY_RE.fullmatch(key)
or not _APP_KEY_RE.fullmatch(audience.lower())
or audience != audience.lower()
or not display_name
):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application identity configuration is incomplete',
http_status=503,
)
if key in seen_keys or audience in seen_audiences:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application keys and audiences must be unique',
http_status=503,
)
applications.append(SsoApplication(
key=key,
display_name=display_name,
login_url=_validate_http_url(item.get('login_url'), field='login_url'),
callback_url=_validate_http_url(item.get('callback_url'), field='callback_url'),
audience=audience,
enabled=True,
))
seen_keys.add(key)
seen_audiences.add(audience)
return applications
def get_application(app_key: str) -> SsoApplication:
"""Resolve one enabled application by its server-controlled key."""
normalized = str(app_key or '').strip().lower()
for application in list_applications():
if application.key == normalized:
return application
raise NotFoundError('SSO application not found', code='AUTH.SSO_APP_NOT_FOUND')
@@ -0,0 +1,265 @@
"""
backend/app/services/auth/sso/assertion_service.py
Purpose: Sign peer-service-specific short-lived login assertions and publish their verification key.
Dependencies: application registry, PyJWT, cryptography, Flask configuration, and User.
Flow: The SSO API authenticates an HXOPS user, this module signs an audience-bound JWT, and peers verify it through JWKS.
"""
from __future__ import annotations
import base64
import json
import secrets
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from flask import current_app
from app.core.errors import AppError, ValidationError
from app.models import User
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from .application_registry import get_application
def _config_error(message: str) -> AppError:
"""Build a fail-closed SSO configuration error without leaking key material."""
return AppError(code='AUTH.SSO_CONFIG_ERROR', message=message, http_status=503)
def _read_signing_key() -> rsa.RSAPrivateKey:
"""
Load the configured RSA private key used only for product SSO assertions.
Returns:
Parsed RSA private key.
Raises:
AppError: The path is absent, unreadable, invalid, or not an RSA private key.
"""
raw_path = str(current_app.config.get('SSO_PRIVATE_KEY_PATH') or '').strip()
if not raw_path:
raise _config_error('SSO signing private key is not configured')
try:
key_bytes = Path(raw_path).read_bytes()
private_key = serialization.load_pem_private_key(key_bytes, password=None)
except (OSError, ValueError, TypeError) as exc:
raise _config_error('SSO signing private key cannot be loaded') from exc
if not isinstance(private_key, rsa.RSAPrivateKey):
raise _config_error('SSO signing key must be an RSA private key')
return private_key
def _issuer() -> str:
"""Return the configured absolute SSO issuer after environment-aware URL validation."""
issuer = str(current_app.config.get('SSO_ISSUER') or '').strip().rstrip('/')
parsed = urlparse(issuer)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise _config_error('SSO issuer must be an absolute URL')
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise _config_error('SSO issuer must use HTTPS')
return issuer
def _ttl_seconds() -> int:
"""Validate the short assertion lifetime; values outside 10-60 seconds fail closed."""
try:
ttl_seconds = int(current_app.config.get('SSO_ASSERTION_TTL_SECONDS') or 60)
except (TypeError, ValueError) as exc:
raise _config_error('SSO assertion TTL is invalid') from exc
if ttl_seconds < 10 or ttl_seconds > 60:
raise _config_error('SSO assertion TTL must be between 10 and 60 seconds')
return ttl_seconds
def _algorithm() -> str:
"""Enforce the single supported asymmetric signing algorithm and reject downgrade configuration."""
algorithm = str(current_app.config.get('SSO_SIGNING_ALGORITHM') or 'RS256').strip().upper()
if algorithm != 'RS256':
raise _config_error('SSO signing algorithm must be RS256')
return algorithm
def _key_id() -> str:
"""Return the stable public key identifier embedded in JWT and JWKS metadata."""
key_id = str(current_app.config.get('SSO_SIGNING_KEY_ID') or '').strip()
if not key_id or len(key_id) > 128:
raise _config_error('SSO signing key ID is not configured')
return key_id
def _identity_claims(user: User, claims: dict[str, Any]) -> dict[str, Any]:
"""
Build the portable Casdoor identity claims without HXOPS business permissions.
Args:
user: Active HXOPS user mapped from the authenticated Casdoor identity.
claims: Verified HXOPS API JWT claims containing ``casdoor_iss/casdoor_sub``.
Returns:
Stable identity plus mutable display attributes safe for peer-service user mapping.
"""
expected_issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
try:
identity = identity_from_claims({
'iss': claims.get('casdoor_iss'),
'sub': claims.get('casdoor_sub'),
'preferred_username': user.username,
'name': user.real_name or user.username,
'email': user.email,
'phone_number': user.phone_number,
'employee_id': user.employee_id,
'department': user.department,
}, expected_issuer=expected_issuer)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.SSO_IDENTITY_UNSUPPORTED',
message='Current login is not backed by a Casdoor identity',
http_status=403,
) from exc
return {
'sub': identity.subject,
'identity_issuer': identity.issuer,
'preferred_username': identity.username,
'name': identity.display_name,
'email': identity.email,
'phone_number': identity.phone_number,
'employee_id': identity.employee_id,
'department': identity.department,
}
def issue_assertion(*, app_key: str, user: User, claims: dict[str, Any], state: Any) -> dict[str, Any]:
"""
Sign a peer-service-specific login assertion for an active HXOPS user.
Args:
app_key: Server-registered target service key.
user: Current active HXOPS user.
claims: Verified HXOPS API JWT claims with Casdoor identity references.
state: Opaque signed state created by the peer service and returned unchanged.
Returns:
Registered callback URL, RS256 assertion, original state, and expiry seconds.
"""
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
normalized_state = str(state or '').strip()
if not normalized_state or len(normalized_state) > 4096:
raise ValidationError('state is required and must not exceed 4096 characters')
application = get_application(app_key)
ttl_seconds = _ttl_seconds()
now = datetime.now(timezone.utc)
payload = {
'iss': _issuer(),
'aud': application.audience,
**_identity_claims(user, claims),
'iat': int(now.timestamp()),
'nbf': int((now - timedelta(seconds=5)).timestamp()),
'exp': int((now + timedelta(seconds=ttl_seconds)).timestamp()),
'jti': secrets.token_urlsafe(24),
}
try:
assertion = jwt.encode(
payload,
_read_signing_key(),
algorithm=_algorithm(),
headers={'kid': _key_id(), 'typ': 'JWT'},
)
except AppError:
raise
except Exception as exc:
current_app.logger.exception('[sso] failed to sign assertion app=%s', application.key)
raise AppError(
code='AUTH.SSO_ASSERTION_ISSUE_FAILED',
message='Failed to issue an SSO assertion',
http_status=503,
retryable=True,
) from exc
current_app.logger.info(
'[sso] assertion issued app=%s user_id=%s subject=%s ttl=%s',
application.key,
user.id,
payload['sub'],
ttl_seconds,
)
return {
'post_url': application.callback_url,
'assertion': assertion,
'state': normalized_state,
'expires_in': ttl_seconds,
}
def _base64url_uint(value: int) -> str:
"""Encode an RSA integer using the unpadded base64url form required by JWK."""
raw = value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big')
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')
def _public_jwk(public_key: rsa.RSAPublicKey, *, key_id: str) -> dict[str, str]:
"""Convert one trusted RSA public key to the minimal signing JWK contract."""
numbers = public_key.public_numbers()
return {
'kty': 'RSA',
'kid': key_id,
'use': 'sig',
'alg': _algorithm(),
'n': _base64url_uint(numbers.n),
'e': _base64url_uint(numbers.e),
}
def _additional_public_jwks(active_key_id: str) -> list[dict[str, str]]:
"""
Load verification-only public keys retained during a signing-key rotation window.
Returns:
Additional JWK entries configured as ``[{"kid", "public_key_path"}]``.
Raises:
AppError: JSON, key IDs, paths, or public key material are invalid.
"""
raw = current_app.config.get('SSO_ADDITIONAL_PUBLIC_KEYS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise _config_error('Additional SSO public keys configuration is invalid') from exc
if not isinstance(items, list):
raise _config_error('Additional SSO public keys must be a JSON array')
jwks: list[dict[str, str]] = []
seen_key_ids = {active_key_id}
for item in items:
if not isinstance(item, dict):
raise _config_error('Additional SSO public key entry is invalid')
key_id = str(item.get('kid') or '').strip()
path = str(item.get('public_key_path') or '').strip()
if not key_id or len(key_id) > 128 or not path or key_id in seen_key_ids:
raise _config_error('Additional SSO public key identity is invalid or duplicated')
try:
public_key = serialization.load_pem_public_key(Path(path).read_bytes())
except (OSError, ValueError, TypeError) as exc:
raise _config_error('Additional SSO public key cannot be loaded') from exc
if not isinstance(public_key, rsa.RSAPublicKey):
raise _config_error('Additional SSO public key must be RSA')
jwks.append(_public_jwk(public_key, key_id=key_id))
seen_key_ids.add(key_id)
return jwks
def build_jwks() -> dict[str, list[dict[str, str]]]:
"""Build JWKS with the active signing key plus verification-only rotation keys."""
active_key_id = _key_id()
active_jwk = _public_jwk(_read_signing_key().public_key(), key_id=active_key_id)
return {'keys': [active_jwk, *_additional_public_jwks(active_key_id)]}