skyplatform-iam 1.0.0__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.
@@ -0,0 +1,71 @@
1
+ """
2
+ SkyPlatform IAM SDK 异常模块
3
+ """
4
+ from typing import Optional
5
+
6
+
7
+ class SkyPlatformAuthException(Exception):
8
+ """
9
+ SkyPlatform认证SDK基础异常类
10
+ """
11
+ def __init__(self, message: str, status_code: int = 500, detail: Optional[str] = None):
12
+ self.message = message
13
+ self.status_code = status_code
14
+ self.detail = detail
15
+ super().__init__(self.message)
16
+
17
+
18
+ class AuthenticationError(SkyPlatformAuthException):
19
+ """
20
+ 认证失败异常
21
+ """
22
+ def __init__(self, message: str = "认证失败", detail: Optional[str] = None):
23
+ super().__init__(message, status_code=401, detail=detail)
24
+
25
+
26
+ class AuthorizationError(SkyPlatformAuthException):
27
+ """
28
+ 授权失败异常
29
+ """
30
+ def __init__(self, message: str = "权限不足", detail: Optional[str] = None):
31
+ super().__init__(message, status_code=403, detail=detail)
32
+
33
+
34
+ class TokenExpiredError(AuthenticationError):
35
+ """
36
+ Token过期异常
37
+ """
38
+ def __init__(self, message: str = "Token已过期", detail: Optional[str] = None):
39
+ super().__init__(message, detail=detail)
40
+
41
+
42
+ class TokenInvalidError(AuthenticationError):
43
+ """
44
+ Token无效异常
45
+ """
46
+ def __init__(self, message: str = "Token无效", detail: Optional[str] = None):
47
+ super().__init__(message, detail=detail)
48
+
49
+
50
+ class ConfigurationError(SkyPlatformAuthException):
51
+ """
52
+ 配置错误异常
53
+ """
54
+ def __init__(self, message: str = "配置错误", detail: Optional[str] = None):
55
+ super().__init__(message, status_code=500, detail=detail)
56
+
57
+
58
+ class IAMServiceError(SkyPlatformAuthException):
59
+ """
60
+ IAM服务错误异常
61
+ """
62
+ def __init__(self, message: str = "IAM服务错误", status_code: int = 500, detail: Optional[str] = None):
63
+ super().__init__(message, status_code=status_code, detail=detail)
64
+
65
+
66
+ class NetworkError(SkyPlatformAuthException):
67
+ """
68
+ 网络错误异常
69
+ """
70
+ def __init__(self, message: str = "网络连接错误", detail: Optional[str] = None):
71
+ super().__init__(message, status_code=503, detail=detail)
@@ -0,0 +1,186 @@
1
+ """
2
+ SkyPlatform IAM SDK 中间件模块
3
+ """
4
+ import logging
5
+ from typing import Optional, Callable, Dict, Any
6
+ from fastapi import Request, Response, HTTPException
7
+ from fastapi.responses import JSONResponse
8
+ from starlette.middleware.base import BaseHTTPMiddleware
9
+
10
+ from .config import AuthConfig
11
+ from .connect_agenterra_iam import ConnectAgenterraIam
12
+ from .exceptions import (
13
+ AuthenticationError,
14
+ AuthorizationError,
15
+ ConfigurationError
16
+ )
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class AuthMiddleware(BaseHTTPMiddleware):
22
+ """
23
+ 认证中间件
24
+ 自动拦截请求进行Token验证和权限检查
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ app,
30
+ config: AuthConfig,
31
+ skip_validation: Optional[Callable[[Request], bool]] = None
32
+ ):
33
+ """
34
+ 初始化认证中间件
35
+
36
+ Args:
37
+ app: FastAPI应用实例
38
+ config: 认证配置
39
+ skip_validation: 自定义跳过验证的函数
40
+ """
41
+ super().__init__(app)
42
+ self.config = config
43
+ self.iam_client = ConnectAgenterraIam()
44
+ self.skip_validation = skip_validation
45
+
46
+ # 验证配置
47
+ try:
48
+ self.config.validate_config()
49
+ except ValueError as e:
50
+ raise ConfigurationError(str(e))
51
+
52
+ async def dispatch(self, request: Request, call_next: Callable) -> Response:
53
+ """
54
+ 中间件主要处理逻辑
55
+ """
56
+ try:
57
+
58
+ # 提取Token(可能为空,白名单接口不需要token)
59
+ token = self._extract_token(request)
60
+
61
+ # 验证Token和权限(即使token为空也要调用IAM验证,因为可能是白名单接口)
62
+ user_info = await self._verify_token_and_permission(request, token)
63
+ if not user_info:
64
+ return self._create_error_response(
65
+ status_code=401,
66
+ message="Token验证失败",
67
+ detail="提供的Token无效或已过期"
68
+ )
69
+
70
+ # 检查是否为白名单接口
71
+ if user_info.get('is_whitelist', False):
72
+ # 白名单接口,允许访问但不设置用户信息
73
+ request.state.user = None
74
+ request.state.authenticated = False
75
+ request.state.is_whitelist = True
76
+ else:
77
+ # 正常认证接口,设置用户信息
78
+ request.state.user = user_info
79
+ request.state.authenticated = True
80
+ request.state.is_whitelist = False
81
+
82
+ # 继续处理请求
83
+ response = await call_next(request)
84
+ return response
85
+
86
+ except HTTPException as e:
87
+ # FastAPI HTTPException直接返回
88
+ return self._create_error_response(
89
+ status_code=e.status_code,
90
+ message=str(e.detail),
91
+ detail=getattr(e, 'detail', None)
92
+ )
93
+ except AuthenticationError as e:
94
+ return self._create_error_response(
95
+ status_code=e.status_code,
96
+ message=e.message,
97
+ detail=e.detail
98
+ )
99
+ except AuthorizationError as e:
100
+ return self._create_error_response(
101
+ status_code=e.status_code,
102
+ message=e.message,
103
+ detail=e.detail
104
+ )
105
+ except Exception as e:
106
+ logger.error(f"认证中间件处理异常: {str(e)}")
107
+ if self.config.enable_debug:
108
+ logger.exception("详细异常信息:")
109
+
110
+ return self._create_error_response(
111
+ status_code=500,
112
+ message="内部服务器错误",
113
+ detail=str(e) if self.config.enable_debug else None
114
+ )
115
+
116
+ def _extract_token(self, request: Request) -> Optional[str]:
117
+ """
118
+ 从请求中提取Token
119
+ """
120
+ # 从Authorization头提取
121
+ auth_header = request.headers.get(self.config.token_header)
122
+ if auth_header and auth_header.startswith(self.config.token_prefix):
123
+ return auth_header[len(self.config.token_prefix):].strip()
124
+
125
+ # 从查询参数提取(备选方案)
126
+ token = request.query_params.get("token")
127
+ if token:
128
+ return token
129
+
130
+ return None
131
+
132
+ async def _verify_token_and_permission(self, request: Request, token: Optional[str]) -> Optional[Dict[str, Any]]:
133
+ """
134
+ 验证Token和权限
135
+ """
136
+ try:
137
+ # 获取请求信息
138
+ api_path = request.url.path
139
+ method = request.method
140
+
141
+ # 从请求头获取服务认证信息(可选)
142
+ server_ak = request.headers.get("SERVER-AK", "")
143
+ server_sk = request.headers.get("SERVER-SK", "")
144
+
145
+ # 调用IAM验证接口(即使token为空也要调用,因为可能是白名单接口)
146
+ user_info = self.iam_client.verify_token(
147
+ token=token or "", # 如果token为None,传递空字符串
148
+ api=api_path,
149
+ method=method,
150
+ server_ak=server_ak,
151
+ server_sk=server_sk
152
+ )
153
+
154
+ return user_info
155
+
156
+ except HTTPException:
157
+ # 重新抛出HTTP异常
158
+ raise
159
+ except Exception as e:
160
+ logger.error(f"Token验证异常: {str(e)}")
161
+ if self.config.enable_debug:
162
+ logger.exception("详细异常信息:")
163
+ return None
164
+
165
+ def _create_error_response(
166
+ self,
167
+ status_code: int,
168
+ message: str,
169
+ detail: Optional[str] = None
170
+ ) -> JSONResponse:
171
+ """
172
+ 创建错误响应
173
+ """
174
+ error_data = {
175
+ "success": False,
176
+ "message": message,
177
+ "status_code": status_code
178
+ }
179
+
180
+ if detail:
181
+ error_data["detail"] = detail
182
+
183
+ return JSONResponse(
184
+ status_code=status_code,
185
+ content=error_data
186
+ )
@@ -0,0 +1,262 @@
1
+ Metadata-Version: 2.4
2
+ Name: skyplatform-iam
3
+ Version: 1.0.0
4
+ Summary: SkyPlatform IAM认证SDK,提供FastAPI中间件和认证路由
5
+ Project-URL: Homepage, https://github.com/xinmayoujiang12621/agenterra_iam
6
+ Project-URL: Documentation, https://skyplatform-iam.readthedocs.io/
7
+ Project-URL: Repository, https://github.com/xinmayoujiang12621/agenterra_iam.git
8
+ Project-URL: Issues, https://github.com/xinmayoujiang12621/agenterra_iam/issues
9
+ Project-URL: Changelog, https://github.com/xinmayoujiang12621/agenterra_iam/blob/main/CHANGELOG.md
10
+ Author-email: x9 <xuanxienanxunmobao@gmail.com>
11
+ License: MIT
12
+ Keywords: authentication,fastapi,iam,middleware,skyplatform
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Framework :: FastAPI
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
25
+ Classifier: Topic :: Security
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Requires-Python: >=3.8
28
+ Requires-Dist: fastapi>=0.68.0
29
+ Requires-Dist: pydantic>=1.8.0
30
+ Requires-Dist: python-dotenv>=0.19.0
31
+ Requires-Dist: requests>=2.25.0
32
+ Requires-Dist: starlette>=0.14.0
33
+ Provides-Extra: dev
34
+ Requires-Dist: black>=22.0.0; extra == 'dev'
35
+ Requires-Dist: flake8>=4.0.0; extra == 'dev'
36
+ Requires-Dist: httpx>=0.23.0; extra == 'dev'
37
+ Requires-Dist: isort>=5.10.0; extra == 'dev'
38
+ Requires-Dist: mypy>=0.950; extra == 'dev'
39
+ Requires-Dist: pytest-asyncio>=0.18.0; extra == 'dev'
40
+ Requires-Dist: pytest>=6.0.0; extra == 'dev'
41
+ Description-Content-Type: text/markdown
42
+
43
+ # SkyPlatform IAM SDK
44
+
45
+ SkyPlatform IAM认证SDK,提供FastAPI中间件和认证路由,简化第三方服务的认证集成。
46
+
47
+ ## 功能特性
48
+
49
+ - 🔐 **FastAPI中间件**: 自动拦截请求进行Token验证和权限检查
50
+ - 🚀 **认证路由**: 封装用户注册、登录、登出等认证接口
51
+ - ⚙️ **灵活配置**: 支持环境变量和代码配置
52
+ - 🛡️ **白名单机制**: 支持配置无需认证的路径
53
+ - 🔧 **完整兼容**: 基于现有ConnectAgenterraIam类,保持完全兼容
54
+ - 📝 **类型提示**: 完整的TypeScript风格类型提示
55
+ - 🚨 **异常处理**: 完善的错误处理和自定义异常
56
+
57
+ ## 快速开始
58
+
59
+ ### 安装
60
+
61
+ ```bash
62
+ pip install skyplatform-iam
63
+ ```
64
+
65
+ ### 环境变量配置
66
+
67
+ 创建 `.env` 文件或设置环境变量:
68
+
69
+ ```bash
70
+ AGENTERRA_IAM_HOST=https://your-iam-host.com
71
+ AGENTERRA_SERVER_NAME=your-server-name
72
+ AGENTERRA_ACCESS_KEY=your-access-key
73
+ ```
74
+
75
+ ### 基本使用
76
+
77
+ #### 方式1:一键设置(推荐)
78
+
79
+ ```python
80
+ from fastapi import FastAPI
81
+ from skyplatform_iam import setup_auth
82
+
83
+ app = FastAPI()
84
+
85
+ # 一键设置认证中间件和路由
86
+ setup_auth(app)
87
+
88
+ @app.get("/protected")
89
+ async def protected_endpoint(request):
90
+ # 获取用户信息(由中间件自动设置)
91
+ user = request.state.user
92
+ return {"message": "访问成功", "user": user}
93
+ ```
94
+
95
+ #### 方式2:手动设置
96
+
97
+ ```python
98
+ from fastapi import FastAPI
99
+ from skyplatform_iam import AuthConfig, AuthMiddleware, create_auth_router
100
+
101
+ app = FastAPI()
102
+
103
+ # 创建配置
104
+ config = AuthConfig.from_env()
105
+
106
+ # 添加认证中间件
107
+ app.add_middleware(AuthMiddleware, config=config)
108
+
109
+ # 添加认证路由
110
+ auth_router = create_auth_router(config=config, prefix="/auth")
111
+ app.include_router(auth_router)
112
+ ```
113
+
114
+ #### 方式3:自定义配置
115
+
116
+ ```python
117
+ from skyplatform_iam import AuthConfig, setup_auth
118
+
119
+ # 自定义配置
120
+ config = AuthConfig(
121
+ agenterra_iam_host="https://your-iam-host.com",
122
+ server_name="your-server-name",
123
+ access_key="your-access-key",
124
+ whitelist_paths=[
125
+ "/docs", "/redoc", "/openapi.json",
126
+ "/health", "/public",
127
+ "/auth/register", "/auth/login"
128
+ ],
129
+ enable_debug=True
130
+ )
131
+
132
+ setup_auth(app, config=config)
133
+ ```
134
+
135
+ ## API接口
136
+
137
+ SDK自动提供以下认证接口:
138
+
139
+ - `POST /auth/register` - 用户注册
140
+ - `POST /auth/login` - 用户登录
141
+ - `POST /auth/login_without_password` - 免密登录
142
+ - `POST /auth/logout` - 用户登出
143
+ - `POST /auth/reset_password` - 重置密码
144
+ - `POST /auth/refresh_token` - 刷新Token
145
+ - `POST /auth/assign_role` - 分配角色
146
+ - `POST /auth/user_info` - 获取用户信息
147
+
148
+ ## 中间件功能
149
+
150
+ ### 自动Token验证
151
+
152
+ 中间件会自动:
153
+ 1. 检查请求路径是否在白名单中
154
+ 2. 从请求头提取Authorization Token
155
+ 3. 调用IAM服务验证Token和权限
156
+ 4. 将用户信息设置到 `request.state.user`
157
+
158
+ ### 白名单配置
159
+
160
+ 默认白名单路径:
161
+ - `/docs`, `/redoc`, `/openapi.json` - API文档
162
+ - `/health` - 健康检查
163
+ - `/auth/*` - 认证相关接口
164
+
165
+ 添加自定义白名单:
166
+
167
+ ```python
168
+ config = AuthConfig.from_env()
169
+ config.add_whitelist_path("/public")
170
+ config.add_whitelist_path("/status")
171
+ ```
172
+
173
+ ### 获取用户信息
174
+
175
+ 在受保护的路由中获取用户信息:
176
+
177
+ ```python
178
+ @app.get("/user-profile")
179
+ async def get_user_profile(request):
180
+ if hasattr(request.state, 'user'):
181
+ user = request.state.user
182
+ return {
183
+ "user_id": user["user_id"],
184
+ "username": user["username"],
185
+ "session_id": user["session_id"]
186
+ }
187
+ else:
188
+ raise HTTPException(status_code=401, detail="未认证")
189
+ ```
190
+
191
+ ## 异常处理
192
+
193
+ SDK提供完整的异常处理:
194
+
195
+ ```python
196
+ from skyplatform_iam.exceptions import (
197
+ AuthenticationError, # 认证失败
198
+ AuthorizationError, # 权限不足
199
+ TokenExpiredError, # Token过期
200
+ TokenInvalidError, # Token无效
201
+ ConfigurationError, # 配置错误
202
+ IAMServiceError, # IAM服务错误
203
+ NetworkError # 网络错误
204
+ )
205
+ ```
206
+
207
+ ## 配置选项
208
+
209
+ ### AuthConfig参数
210
+
211
+ | 参数 | 类型 | 必填 | 说明 |
212
+ |------|------|------|------|
213
+ | `agenterra_iam_host` | str | ✓ | IAM服务地址 |
214
+ | `server_name` | str | ✓ | 服务名称 |
215
+ | `access_key` | str | ✓ | 访问密钥 |
216
+ | `whitelist_paths` | List[str] | ✗ | 白名单路径 |
217
+ | `token_header` | str | ✗ | Token请求头名称(默认:Authorization) |
218
+ | `token_prefix` | str | ✗ | Token前缀(默认:Bearer ) |
219
+ | `enable_debug` | bool | ✗ | 启用调试模式 |
220
+
221
+ ## 开发和测试
222
+
223
+ ### 运行测试
224
+
225
+ ```bash
226
+ # 安装开发依赖
227
+ pip install -e ".[dev]"
228
+
229
+ # 运行测试
230
+ python examples/test_sdk.py
231
+ ```
232
+
233
+ ### 运行示例
234
+
235
+ ```bash
236
+ # 启动示例应用
237
+ python examples/basic_usage.py
238
+
239
+ # 访问 http://localhost:8000/docs 查看API文档
240
+ ```
241
+
242
+ ## 兼容性
243
+
244
+ - Python 3.8+
245
+ - FastAPI 0.68.0+
246
+ - 完全兼容现有的 `ConnectAgenterraIam` 类
247
+
248
+ ## 许可证
249
+
250
+ MIT License
251
+
252
+ ## 贡献
253
+
254
+ 欢迎提交Issue和Pull Request!
255
+
256
+ ## 更新日志
257
+
258
+ ### v1.0.0
259
+ - 初始版本发布
260
+ - 提供FastAPI中间件和认证路由
261
+ - 支持完整的认证功能
262
+ - 兼容现有ConnectAgenterraIam类
@@ -0,0 +1,9 @@
1
+ skyplatform_iam/__init__.py,sha256=dUrP_jrnS1KLaJWbpGU1_tdSM5sOSc4yt1wTVcXyQfo,2434
2
+ skyplatform_iam/auth_middleware.py,sha256=aE2zNuoJVs4JGwmzrS0B6Pfs7vDDLdaFDxWiSt9Mm04,7137
3
+ skyplatform_iam/config.py,sha256=2oKTkH0wIzbfK2YP9Tj8evtBgqtt-UaN83F2sKO4gcc,1869
4
+ skyplatform_iam/connect_agenterra_iam.py,sha256=kF4iWMhV-NoxCHgV7pyoClK9UliqC16n-E9V1aDPfKw,31843
5
+ skyplatform_iam/exceptions.py,sha256=Rt55QIzVK1F_kn6yzKQKKakD6PZDFdPLCGaCphKKms8,2166
6
+ skyplatform_iam/middleware.py,sha256=Yg-pX-wI8ROYCIHtwW7F1ABiFK5FSNlDJUgMc6fD_b4,6231
7
+ skyplatform_iam-1.0.0.dist-info/METADATA,sha256=Ii01sk1ovetEjixB1_UkrzJjRHQqW4YdmQWAtQ4WSc4,7027
8
+ skyplatform_iam-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ skyplatform_iam-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any