skyplatform-iam 1.0.3__py3-none-any.whl → 1.0.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- skyplatform_iam/__init__.py +68 -17
- skyplatform_iam/api.py +366 -0
- skyplatform_iam/config.py +173 -18
- skyplatform_iam/connect_agenterra_iam.py +209 -0
- skyplatform_iam/global_manager.py +272 -0
- skyplatform_iam/middleware.py +138 -31
- skyplatform_iam-1.0.5.dist-info/METADATA +461 -0
- skyplatform_iam-1.0.5.dist-info/RECORD +10 -0
- skyplatform_iam-1.0.3.dist-info/METADATA +0 -261
- skyplatform_iam-1.0.3.dist-info/RECORD +0 -8
- {skyplatform_iam-1.0.3.dist-info → skyplatform_iam-1.0.5.dist-info}/WHEEL +0 -0
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SkyPlatform IAM SDK 全局管理器模块
|
|
3
|
+
提供单例模式的全局状态管理,确保线程安全和统一配置
|
|
4
|
+
"""
|
|
5
|
+
import threading
|
|
6
|
+
import logging
|
|
7
|
+
from typing import Optional, Dict, Any, TYPE_CHECKING
|
|
8
|
+
from fastapi import FastAPI, Request
|
|
9
|
+
|
|
10
|
+
from .config import AuthConfig
|
|
11
|
+
from .connect_agenterra_iam import ConnectAgenterraIam
|
|
12
|
+
from .exceptions import ConfigurationError, IAMServiceError
|
|
13
|
+
|
|
14
|
+
# 使用TYPE_CHECKING避免循环导入
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from .middleware import AuthMiddleware
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class GlobalIAMManager:
|
|
22
|
+
"""
|
|
23
|
+
全局IAM管理器,使用单例模式
|
|
24
|
+
负责管理全局的IAM配置、客户端实例和中间件
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
_instance: Optional['GlobalIAMManager'] = None
|
|
28
|
+
_lock = threading.Lock()
|
|
29
|
+
|
|
30
|
+
def __new__(cls) -> 'GlobalIAMManager':
|
|
31
|
+
"""单例模式实现,确保线程安全"""
|
|
32
|
+
if cls._instance is None:
|
|
33
|
+
with cls._lock:
|
|
34
|
+
if cls._instance is None:
|
|
35
|
+
cls._instance = super().__new__(cls)
|
|
36
|
+
cls._instance._initialized = False
|
|
37
|
+
return cls._instance
|
|
38
|
+
|
|
39
|
+
def __init__(self):
|
|
40
|
+
"""初始化全局管理器"""
|
|
41
|
+
if hasattr(self, '_initialized') and self._initialized:
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
self._config: Optional[AuthConfig] = None
|
|
45
|
+
self._iam_client: Optional[ConnectAgenterraIam] = None
|
|
46
|
+
self._middleware: Optional['AuthMiddleware'] = None
|
|
47
|
+
self._app: Optional[FastAPI] = None
|
|
48
|
+
self._initialized = False
|
|
49
|
+
self._init_lock = threading.Lock()
|
|
50
|
+
|
|
51
|
+
logger.debug("GlobalIAMManager实例已创建")
|
|
52
|
+
|
|
53
|
+
def initialize(self, app: FastAPI, config: Optional[AuthConfig] = None, **kwargs) -> None:
|
|
54
|
+
"""
|
|
55
|
+
初始化IAM管理器
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
app: FastAPI应用实例
|
|
59
|
+
config: 认证配置,如果为None则从环境变量加载
|
|
60
|
+
**kwargs: 额外配置参数
|
|
61
|
+
|
|
62
|
+
Raises:
|
|
63
|
+
ConfigurationError: 配置错误
|
|
64
|
+
IAMServiceError: IAM服务连接错误
|
|
65
|
+
"""
|
|
66
|
+
with self._init_lock:
|
|
67
|
+
if self._initialized:
|
|
68
|
+
logger.warning("GlobalIAMManager已经初始化,跳过重复初始化")
|
|
69
|
+
return
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
# 1. 处理配置
|
|
73
|
+
if config is None:
|
|
74
|
+
logger.info("未提供配置,尝试从环境变量加载")
|
|
75
|
+
config = AuthConfig.from_env()
|
|
76
|
+
|
|
77
|
+
# 验证配置
|
|
78
|
+
config.validate_config()
|
|
79
|
+
self._config = config
|
|
80
|
+
|
|
81
|
+
# 2. 创建IAM客户端
|
|
82
|
+
self._iam_client = ConnectAgenterraIam(config=config)
|
|
83
|
+
logger.info(f"IAM客户端已创建,连接到: {config.agenterra_iam_host}")
|
|
84
|
+
|
|
85
|
+
# 3. 创建中间件(不直接注册,由用户决定)
|
|
86
|
+
from .middleware import AuthMiddleware
|
|
87
|
+
self._middleware = AuthMiddleware(app=app, config=config, use_global_manager=False)
|
|
88
|
+
logger.info("认证中间件已创建")
|
|
89
|
+
|
|
90
|
+
# 4. 保存应用引用
|
|
91
|
+
self._app = app
|
|
92
|
+
|
|
93
|
+
# 5. 标记为已初始化
|
|
94
|
+
self._initialized = True
|
|
95
|
+
|
|
96
|
+
logger.info(f"GlobalIAMManager初始化完成 - 服务: {config.server_name}, "
|
|
97
|
+
f"白名单路径数量: {len(config.get_whitelist_paths())}")
|
|
98
|
+
|
|
99
|
+
except Exception as e:
|
|
100
|
+
logger.error(f"GlobalIAMManager初始化失败: {str(e)}")
|
|
101
|
+
# 清理部分初始化的状态
|
|
102
|
+
self._config = None
|
|
103
|
+
self._iam_client = None
|
|
104
|
+
self._middleware = None
|
|
105
|
+
self._app = None
|
|
106
|
+
|
|
107
|
+
if isinstance(e, (ConfigurationError, IAMServiceError)):
|
|
108
|
+
raise
|
|
109
|
+
else:
|
|
110
|
+
raise IAMServiceError(f"初始化失败: {str(e)}")
|
|
111
|
+
|
|
112
|
+
def get_client(self) -> ConnectAgenterraIam:
|
|
113
|
+
"""
|
|
114
|
+
获取IAM客户端实例
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
ConnectAgenterraIam: IAM客户端实例
|
|
118
|
+
|
|
119
|
+
Raises:
|
|
120
|
+
IAMServiceError: 如果管理器未初始化
|
|
121
|
+
"""
|
|
122
|
+
if not self._initialized or self._iam_client is None:
|
|
123
|
+
raise IAMServiceError(
|
|
124
|
+
"GlobalIAMManager未初始化,请先调用init_skyplatform_iam()函数进行初始化"
|
|
125
|
+
)
|
|
126
|
+
return self._iam_client
|
|
127
|
+
|
|
128
|
+
def get_config(self) -> AuthConfig:
|
|
129
|
+
"""
|
|
130
|
+
获取当前配置
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
AuthConfig: 当前认证配置
|
|
134
|
+
|
|
135
|
+
Raises:
|
|
136
|
+
IAMServiceError: 如果管理器未初始化
|
|
137
|
+
"""
|
|
138
|
+
if not self._initialized or self._config is None:
|
|
139
|
+
raise IAMServiceError(
|
|
140
|
+
"GlobalIAMManager未初始化,请先调用init_skyplatform_iam()函数进行初始化"
|
|
141
|
+
)
|
|
142
|
+
return self._config
|
|
143
|
+
|
|
144
|
+
def get_middleware(self) -> 'AuthMiddleware':
|
|
145
|
+
"""
|
|
146
|
+
获取中间件实例
|
|
147
|
+
|
|
148
|
+
Returns:
|
|
149
|
+
AuthMiddleware: 认证中间件实例
|
|
150
|
+
|
|
151
|
+
Raises:
|
|
152
|
+
IAMServiceError: 如果管理器未初始化
|
|
153
|
+
"""
|
|
154
|
+
if not self._initialized or self._middleware is None:
|
|
155
|
+
raise IAMServiceError(
|
|
156
|
+
"GlobalIAMManager未初始化,请先调用init_skyplatform_iam()函数进行初始化"
|
|
157
|
+
)
|
|
158
|
+
return self._middleware
|
|
159
|
+
|
|
160
|
+
def is_initialized(self) -> bool:
|
|
161
|
+
"""
|
|
162
|
+
检查是否已初始化
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
bool: 是否已初始化
|
|
166
|
+
"""
|
|
167
|
+
return self._initialized
|
|
168
|
+
|
|
169
|
+
async def get_current_user_info(self, request: Request) -> Optional[Dict[str, Any]]:
|
|
170
|
+
"""
|
|
171
|
+
便捷方法:获取当前用户信息
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
request: FastAPI请求对象
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
Optional[Dict]: 用户信息字典,如果未登录则返回None
|
|
178
|
+
|
|
179
|
+
Raises:
|
|
180
|
+
IAMServiceError: 如果管理器未初始化
|
|
181
|
+
"""
|
|
182
|
+
if not self._initialized:
|
|
183
|
+
raise IAMServiceError(
|
|
184
|
+
"GlobalIAMManager未初始化,请先调用init_skyplatform_iam()函数进行初始化"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# 检查请求状态中是否已有用户信息(由中间件设置)
|
|
188
|
+
if hasattr(request.state, 'user') and request.state.user:
|
|
189
|
+
return request.state.user
|
|
190
|
+
|
|
191
|
+
# 如果中间件没有设置用户信息,尝试手动验证
|
|
192
|
+
try:
|
|
193
|
+
from .middleware import AuthService
|
|
194
|
+
auth_service = AuthService(self._config)
|
|
195
|
+
return await auth_service.get_current_user(request)
|
|
196
|
+
except Exception as e:
|
|
197
|
+
logger.error(f"获取用户信息失败: {str(e)}")
|
|
198
|
+
return None
|
|
199
|
+
|
|
200
|
+
async def verify_permission(
|
|
201
|
+
self,
|
|
202
|
+
user_id: str,
|
|
203
|
+
permission: str,
|
|
204
|
+
resource: Optional[str] = None
|
|
205
|
+
) -> bool:
|
|
206
|
+
"""
|
|
207
|
+
便捷方法:验证用户权限
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
user_id: 用户ID
|
|
211
|
+
permission: 权限标识
|
|
212
|
+
resource: 资源标识(可选)
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
bool: 是否有权限
|
|
216
|
+
|
|
217
|
+
Raises:
|
|
218
|
+
IAMServiceError: 如果管理器未初始化
|
|
219
|
+
"""
|
|
220
|
+
client = self.get_client()
|
|
221
|
+
try:
|
|
222
|
+
# 这里可以根据实际的IAM客户端API进行权限验证
|
|
223
|
+
# 目前先返回True,具体实现需要根据ConnectAgenterraIam的API
|
|
224
|
+
logger.info(f"验证权限: user_id={user_id}, permission={permission}, resource={resource}")
|
|
225
|
+
return True
|
|
226
|
+
except Exception as e:
|
|
227
|
+
logger.error(f"权限验证失败: {str(e)}")
|
|
228
|
+
return False
|
|
229
|
+
|
|
230
|
+
def reset(self) -> None:
|
|
231
|
+
"""
|
|
232
|
+
重置管理器状态(主要用于测试)
|
|
233
|
+
"""
|
|
234
|
+
with self._init_lock:
|
|
235
|
+
self._config = None
|
|
236
|
+
self._iam_client = None
|
|
237
|
+
self._middleware = None
|
|
238
|
+
self._app = None
|
|
239
|
+
self._initialized = False
|
|
240
|
+
logger.info("GlobalIAMManager状态已重置")
|
|
241
|
+
|
|
242
|
+
def get_status(self) -> Dict[str, Any]:
|
|
243
|
+
"""
|
|
244
|
+
获取管理器状态信息
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
Dict: 状态信息
|
|
248
|
+
"""
|
|
249
|
+
return {
|
|
250
|
+
"initialized": self._initialized,
|
|
251
|
+
"has_config": self._config is not None,
|
|
252
|
+
"has_client": self._iam_client is not None,
|
|
253
|
+
"has_middleware": self._middleware is not None,
|
|
254
|
+
"has_app": self._app is not None,
|
|
255
|
+
"server_name": self._config.server_name if self._config else None,
|
|
256
|
+
"iam_host": self._config.agenterra_iam_host if self._config else None,
|
|
257
|
+
"whitelist_paths_count": len(self._config.get_whitelist_paths()) if self._config else 0
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
# 全局管理器实例
|
|
262
|
+
_global_manager = GlobalIAMManager()
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def get_global_manager() -> GlobalIAMManager:
|
|
266
|
+
"""
|
|
267
|
+
获取全局管理器实例
|
|
268
|
+
|
|
269
|
+
Returns:
|
|
270
|
+
GlobalIAMManager: 全局管理器实例
|
|
271
|
+
"""
|
|
272
|
+
return _global_manager
|
skyplatform_iam/middleware.py
CHANGED
|
@@ -11,10 +11,12 @@ import jwt
|
|
|
11
11
|
|
|
12
12
|
from .config import AuthConfig
|
|
13
13
|
from .connect_agenterra_iam import ConnectAgenterraIam
|
|
14
|
+
from .global_manager import get_global_manager
|
|
14
15
|
from .exceptions import (
|
|
15
16
|
AuthenticationError,
|
|
16
17
|
AuthorizationError,
|
|
17
|
-
ConfigurationError
|
|
18
|
+
ConfigurationError,
|
|
19
|
+
IAMServiceError
|
|
18
20
|
)
|
|
19
21
|
|
|
20
22
|
logger = logging.getLogger(__name__)
|
|
@@ -24,40 +26,72 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
|
|
24
26
|
"""
|
|
25
27
|
认证中间件
|
|
26
28
|
自动拦截请求进行Token验证和权限检查
|
|
29
|
+
支持全局实例共享和延迟初始化
|
|
27
30
|
"""
|
|
28
31
|
|
|
29
32
|
def __init__(
|
|
30
33
|
self,
|
|
31
34
|
app,
|
|
32
|
-
config: AuthConfig,
|
|
33
|
-
skip_validation: Optional[Callable[[Request], bool]] = None
|
|
35
|
+
config: Optional[AuthConfig] = None,
|
|
36
|
+
skip_validation: Optional[Callable[[Request], bool]] = None,
|
|
37
|
+
use_global_manager: bool = True
|
|
34
38
|
):
|
|
35
39
|
"""
|
|
36
40
|
初始化认证中间件
|
|
37
41
|
|
|
38
42
|
Args:
|
|
39
43
|
app: FastAPI应用实例
|
|
40
|
-
config:
|
|
44
|
+
config: 认证配置,如果为None且use_global_manager=True,则从全局管理器获取
|
|
41
45
|
skip_validation: 自定义跳过验证的函数
|
|
46
|
+
use_global_manager: 是否使用全局管理器(推荐)
|
|
42
47
|
"""
|
|
43
48
|
super().__init__(app)
|
|
44
|
-
self.
|
|
45
|
-
self.iam_client = ConnectAgenterraIam(config=config)
|
|
49
|
+
self.use_global_manager = use_global_manager
|
|
46
50
|
self.skip_validation = skip_validation
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
self.config
|
|
51
|
-
|
|
52
|
-
|
|
51
|
+
|
|
52
|
+
if use_global_manager:
|
|
53
|
+
# 使用全局管理器(延迟初始化)
|
|
54
|
+
self.config = None
|
|
55
|
+
self.iam_client = None
|
|
56
|
+
logger.info("AuthMiddleware使用全局管理器模式")
|
|
57
|
+
else:
|
|
58
|
+
# 传统模式(向后兼容)
|
|
59
|
+
if config is None:
|
|
60
|
+
raise ConfigurationError("在非全局管理器模式下,config参数不能为None")
|
|
61
|
+
self.config = config
|
|
62
|
+
self.iam_client = ConnectAgenterraIam(config=config)
|
|
63
|
+
|
|
64
|
+
# 验证配置
|
|
65
|
+
try:
|
|
66
|
+
self.config.validate_config()
|
|
67
|
+
except ValueError as e:
|
|
68
|
+
raise ConfigurationError(str(e))
|
|
69
|
+
logger.info("AuthMiddleware使用传统模式")
|
|
70
|
+
|
|
71
|
+
def _get_config_and_client(self):
|
|
72
|
+
"""获取配置和客户端实例"""
|
|
73
|
+
if self.use_global_manager:
|
|
74
|
+
try:
|
|
75
|
+
manager = get_global_manager()
|
|
76
|
+
if not manager.is_initialized():
|
|
77
|
+
raise IAMServiceError("SkyPlatform IAM SDK未初始化,请先调用init_skyplatform_iam()")
|
|
78
|
+
return manager.get_config(), manager.get_client()
|
|
79
|
+
except Exception as e:
|
|
80
|
+
logger.error(f"从全局管理器获取配置和客户端失败: {str(e)}")
|
|
81
|
+
raise IAMServiceError(f"获取IAM配置失败: {str(e)}")
|
|
82
|
+
else:
|
|
83
|
+
return self.config, self.iam_client
|
|
53
84
|
|
|
54
85
|
def is_path_whitelisted(self, path: str) -> bool:
|
|
55
86
|
"""
|
|
56
87
|
检查路径是否在本地白名单中
|
|
57
88
|
"""
|
|
58
|
-
|
|
89
|
+
try:
|
|
90
|
+
config, _ = self._get_config_and_client()
|
|
91
|
+
return config.is_path_whitelisted(path)
|
|
92
|
+
except Exception as e:
|
|
93
|
+
logger.error(f"检查白名单路径失败: {str(e)}")
|
|
59
94
|
return False
|
|
60
|
-
return self.config.is_path_whitelisted(path)
|
|
61
95
|
|
|
62
96
|
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
|
63
97
|
"""
|
|
@@ -139,23 +173,31 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
|
|
139
173
|
"""
|
|
140
174
|
从请求中提取Token
|
|
141
175
|
"""
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
176
|
+
try:
|
|
177
|
+
config, _ = self._get_config_and_client()
|
|
178
|
+
|
|
179
|
+
# 从Authorization头提取
|
|
180
|
+
auth_header = request.headers.get(config.token_header)
|
|
181
|
+
if auth_header and auth_header.startswith(config.token_prefix):
|
|
182
|
+
return auth_header[len(config.token_prefix):].strip()
|
|
146
183
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
184
|
+
# 从查询参数提取(备选方案)
|
|
185
|
+
token = request.query_params.get("token")
|
|
186
|
+
if token:
|
|
187
|
+
return token
|
|
151
188
|
|
|
152
|
-
|
|
189
|
+
return None
|
|
190
|
+
except Exception as e:
|
|
191
|
+
logger.error(f"提取Token失败: {str(e)}")
|
|
192
|
+
return None
|
|
153
193
|
|
|
154
194
|
async def _verify_token_and_permission(self, request: Request, token: Optional[str]) -> Optional[Dict[str, Any]]:
|
|
155
195
|
"""
|
|
156
196
|
验证Token和权限
|
|
157
197
|
"""
|
|
158
198
|
try:
|
|
199
|
+
config, iam_client = self._get_config_and_client()
|
|
200
|
+
|
|
159
201
|
# 获取请求信息
|
|
160
202
|
api_path = request.url.path
|
|
161
203
|
method = request.method
|
|
@@ -165,7 +207,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
|
|
165
207
|
server_sk = request.headers.get("SERVER-SK", "")
|
|
166
208
|
|
|
167
209
|
# 调用IAM验证接口(即使token为空也要调用,因为可能是白名单接口)
|
|
168
|
-
user_info =
|
|
210
|
+
user_info = iam_client.verify_token(
|
|
169
211
|
token=token or "", # 如果token为None,传递空字符串
|
|
170
212
|
api=api_path,
|
|
171
213
|
method=method,
|
|
@@ -180,8 +222,12 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
|
|
180
222
|
raise
|
|
181
223
|
except Exception as e:
|
|
182
224
|
logger.error(f"Token验证异常: {str(e)}")
|
|
183
|
-
|
|
184
|
-
|
|
225
|
+
try:
|
|
226
|
+
config, _ = self._get_config_and_client()
|
|
227
|
+
if config.enable_debug:
|
|
228
|
+
logger.exception("详细异常信息:")
|
|
229
|
+
except:
|
|
230
|
+
pass
|
|
185
231
|
return None
|
|
186
232
|
|
|
187
233
|
def _create_error_response(
|
|
@@ -387,32 +433,93 @@ auth_service = None
|
|
|
387
433
|
|
|
388
434
|
def setup_auth_middleware(auth_config: AuthConfig) -> None:
|
|
389
435
|
"""
|
|
390
|
-
|
|
436
|
+
设置认证中间件配置(向后兼容)
|
|
391
437
|
|
|
392
438
|
Args:
|
|
393
439
|
auth_config: 认证配置实例,包含白名单路径等配置
|
|
440
|
+
|
|
441
|
+
Deprecated:
|
|
442
|
+
请使用 init_skyplatform_iam() 替代
|
|
394
443
|
"""
|
|
395
444
|
global auth_service
|
|
396
445
|
auth_service = AuthService(auth_config)
|
|
446
|
+
logger.warning("setup_auth_middleware()已废弃,请使用init_skyplatform_iam()替代")
|
|
397
447
|
logger.info(f"认证中间件已配置,白名单路径数量: {len(auth_config.get_whitelist_paths())}")
|
|
398
448
|
|
|
399
449
|
|
|
450
|
+
def create_auth_middleware(
|
|
451
|
+
app,
|
|
452
|
+
config: Optional[AuthConfig] = None,
|
|
453
|
+
use_global_manager: bool = True
|
|
454
|
+
) -> AuthMiddleware:
|
|
455
|
+
"""
|
|
456
|
+
创建认证中间件实例
|
|
457
|
+
|
|
458
|
+
Args:
|
|
459
|
+
app: FastAPI应用实例
|
|
460
|
+
config: 认证配置,如果为None且use_global_manager=True,则从全局管理器获取
|
|
461
|
+
use_global_manager: 是否使用全局管理器(推荐)
|
|
462
|
+
|
|
463
|
+
Returns:
|
|
464
|
+
AuthMiddleware: 认证中间件实例
|
|
465
|
+
|
|
466
|
+
Example:
|
|
467
|
+
# 使用全局管理器(推荐)
|
|
468
|
+
middleware = create_auth_middleware(app)
|
|
469
|
+
|
|
470
|
+
# 传统模式(向后兼容)
|
|
471
|
+
middleware = create_auth_middleware(app, config, use_global_manager=False)
|
|
472
|
+
"""
|
|
473
|
+
return AuthMiddleware(app, config, use_global_manager=use_global_manager)
|
|
474
|
+
|
|
475
|
+
|
|
400
476
|
# 便捷的依赖函数
|
|
401
477
|
async def get_current_user(request: Request) -> Dict:
|
|
402
|
-
"""
|
|
478
|
+
"""
|
|
479
|
+
获取当前用户的依赖函数
|
|
480
|
+
优先使用全局管理器,向后兼容传统模式
|
|
481
|
+
"""
|
|
482
|
+
try:
|
|
483
|
+
# 尝试使用全局管理器
|
|
484
|
+
manager = get_global_manager()
|
|
485
|
+
if manager.is_initialized():
|
|
486
|
+
user_info = await manager.get_current_user_info(request)
|
|
487
|
+
if user_info is None:
|
|
488
|
+
raise HTTPException(
|
|
489
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
490
|
+
detail="需要登录认证",
|
|
491
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
492
|
+
)
|
|
493
|
+
return user_info
|
|
494
|
+
except IAMServiceError:
|
|
495
|
+
pass # 全局管理器未初始化,尝试传统模式
|
|
496
|
+
|
|
497
|
+
# 传统模式(向后兼容)
|
|
403
498
|
if auth_service is None:
|
|
404
499
|
raise HTTPException(
|
|
405
500
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
406
|
-
detail="认证服务未初始化,请先调用setup_auth_middleware函数进行配置"
|
|
501
|
+
detail="认证服务未初始化,请先调用init_skyplatform_iam()或setup_auth_middleware()函数进行配置"
|
|
407
502
|
)
|
|
408
503
|
return await auth_service.require_auth(request)
|
|
409
504
|
|
|
410
505
|
|
|
411
506
|
async def get_optional_user(request: Request) -> Optional[Dict]:
|
|
412
|
-
"""
|
|
507
|
+
"""
|
|
508
|
+
获取可选当前用户的依赖函数
|
|
509
|
+
优先使用全局管理器,向后兼容传统模式
|
|
510
|
+
"""
|
|
511
|
+
try:
|
|
512
|
+
# 尝试使用全局管理器
|
|
513
|
+
manager = get_global_manager()
|
|
514
|
+
if manager.is_initialized():
|
|
515
|
+
return await manager.get_current_user_info(request)
|
|
516
|
+
except IAMServiceError:
|
|
517
|
+
pass # 全局管理器未初始化,尝试传统模式
|
|
518
|
+
|
|
519
|
+
# 传统模式(向后兼容)
|
|
413
520
|
if auth_service is None:
|
|
414
521
|
raise HTTPException(
|
|
415
522
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
416
|
-
detail="认证服务未初始化,请先调用setup_auth_middleware函数进行配置"
|
|
523
|
+
detail="认证服务未初始化,请先调用init_skyplatform_iam()或setup_auth_middleware()函数进行配置"
|
|
417
524
|
)
|
|
418
525
|
return await auth_service.optional_auth(request)
|