fast-web-core 6.2.8__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.
Files changed (48) hide show
  1. fast_web_core/__init__.py +9 -0
  2. fast_web_core/auth/__init__.py +0 -0
  3. fast_web_core/auth/auth_cache.py +122 -0
  4. fast_web_core/auth/share_auth.py +260 -0
  5. fast_web_core/client/__init__.py +1 -0
  6. fast_web_core/client/async_elasticsearch_client.py +399 -0
  7. fast_web_core/client/async_http_client.py +107 -0
  8. fast_web_core/client/async_mongo_client.py +214 -0
  9. fast_web_core/client/async_mulit_tenant_mongo_client.py +69 -0
  10. fast_web_core/client/async_multi_database_mongo_client.py +60 -0
  11. fast_web_core/client/async_rabbit_client.py +71 -0
  12. fast_web_core/client/async_redis_client.py +37 -0
  13. fast_web_core/client/mongo_client.py +208 -0
  14. fast_web_core/client/multi_database_mongo_client.py +59 -0
  15. fast_web_core/client/multi_tenant_mongo_client.py +60 -0
  16. fast_web_core/client/oss2_client.py +95 -0
  17. fast_web_core/client/redis_client.py +36 -0
  18. fast_web_core/context/__init__.py +0 -0
  19. fast_web_core/context/context_vars.py +12 -0
  20. fast_web_core/exception/__init__.py +0 -0
  21. fast_web_core/exception/exceptions.py +38 -0
  22. fast_web_core/lib/__init__.py +0 -0
  23. fast_web_core/lib/cfg.py +60 -0
  24. fast_web_core/lib/func.py +92 -0
  25. fast_web_core/lib/log_filter.py +37 -0
  26. fast_web_core/lib/logger.py +87 -0
  27. fast_web_core/lib/secret.py +59 -0
  28. fast_web_core/lib/service.py +30 -0
  29. fast_web_core/lib/settings.py +101 -0
  30. fast_web_core/lib/time.py +344 -0
  31. fast_web_core/lib/util.py +56 -0
  32. fast_web_core/middleware/__init__.py +0 -0
  33. fast_web_core/middleware/auth.py +78 -0
  34. fast_web_core/model/__init__.py +0 -0
  35. fast_web_core/model/base.py +25 -0
  36. fast_web_core/model/enums.py +24 -0
  37. fast_web_core/model/handler.py +96 -0
  38. fast_web_core/model/items.py +151 -0
  39. fast_web_core/model/query.py +23 -0
  40. fast_web_core/utils/__init__.py +0 -0
  41. fast_web_core/utils/common.py +164 -0
  42. fast_web_core/utils/decator.py +13 -0
  43. fast_web_core/utils/encryption.py +75 -0
  44. fast_web_core/utils/sequence.py +44 -0
  45. fast_web_core-6.2.8.dist-info/METADATA +113 -0
  46. fast_web_core-6.2.8.dist-info/RECORD +48 -0
  47. fast_web_core-6.2.8.dist-info/WHEEL +5 -0
  48. fast_web_core-6.2.8.dist-info/top_level.txt +1 -0
@@ -0,0 +1,9 @@
1
+ from __future__ import absolute_import
2
+
3
+
4
+ def init_core_modules(*args, **kwargs) -> None:
5
+ """
6
+ Init core handlers, middlewares and services for fastapi application
7
+ :return: None
8
+ """
9
+ pass
File without changes
@@ -0,0 +1,122 @@
1
+ # -*- coding: utf-8 -*-
2
+ import json
3
+ import logging
4
+ from typing import Optional, Dict
5
+
6
+ from fast_web_core.exception.exceptions import AccessDecodeException
7
+ from fast_web_core.lib import cfg
8
+ from fast_web_core.client.async_redis_client import AsyncRedis
9
+ from fast_web_core.model.items import AuthUser, AuthApp, AuthAdmin, Team
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class TokenPrefix:
15
+ """Token 角色前缀,用于从 token 本身区分用户类型"""
16
+ ADMIN = "admin-"
17
+ USER = "user-"
18
+ APP = "app-"
19
+ TK = "tk-"
20
+
21
+
22
+ class AuthCachePool:
23
+ def __init__(self, redis_url: str = None, redis_db: int = None):
24
+ self.redis_url = redis_url or cfg.get('AUTH_REDIS_URL', None)
25
+ self.redis_db = redis_db or cfg.get('AUTH_REDIS_DB', None)
26
+ self.series_prefix = cfg.get('AUTH_SERIES_PREFIX', 'fast')
27
+
28
+ self.rds = AsyncRedis(redis_uri=self.redis_url, redis_db=self.redis_db).client
29
+
30
+ async def get_cached_app(self, access_token: str) -> Optional[AuthApp]:
31
+ # 前缀校验:token 必须以 app- tk- 开头
32
+ if not (access_token.startswith(TokenPrefix.APP) or access_token.startswith(TokenPrefix.TK)):
33
+ return None
34
+
35
+ rs = await self.rds.get(f'{self.series_prefix}:share:access:{access_token}')
36
+ if rs:
37
+ try:
38
+ js_app = json.loads(rs)
39
+ if isinstance(js_app, str):
40
+ js_app = json.loads(js_app)
41
+ if js_app and js_app.get('app_id', None) is not None:
42
+ return AuthApp(**js_app)
43
+ except Exception as e:
44
+ raise AccessDecodeException('应用信息解析失败')
45
+
46
+ return None
47
+
48
+ async def get_cached_user(self, access_token: str) -> Optional[AuthUser]:
49
+ # 前缀校验:token 必须以 user- 开头
50
+ if not access_token.startswith(TokenPrefix.USER):
51
+ return None
52
+
53
+ rs = await self.rds.get(f'{self.series_prefix}:share:access:{access_token}')
54
+ if rs:
55
+ try:
56
+ js_user = json.loads(rs)
57
+ if isinstance(js_user, str):
58
+ js_user = json.loads(js_user)
59
+ if js_user and js_user.get('id', None) is not None:
60
+ return AuthUser(**js_user)
61
+ except Exception as e:
62
+ raise AccessDecodeException('用户信息解析失败')
63
+
64
+ return None
65
+
66
+ async def get_cached_admin(self, access_token: str) -> Optional[AuthAdmin]:
67
+ # 前缀校验:token 必须以 admin- 开头
68
+ if not access_token.startswith(TokenPrefix.ADMIN):
69
+ return None
70
+
71
+ rs = await self.rds.get(f'{self.series_prefix}:share:access:{access_token}')
72
+ if rs:
73
+ try:
74
+ js_admin = json.loads(rs)
75
+ if isinstance(js_admin, str):
76
+ js_admin = json.loads(js_admin)
77
+ if js_admin and js_admin.get('id', None) is not None:
78
+ return AuthAdmin(**js_admin)
79
+ except Exception as e:
80
+ raise AccessDecodeException('管理员信息解析失败')
81
+
82
+ return None
83
+
84
+ async def get_cached_access_dict(self, access_token: str) -> Optional[Dict]:
85
+ rs = await self.rds.get(f'{self.series_prefix}:share:access:{access_token}')
86
+ if rs:
87
+ item = json.loads(rs)
88
+ # 容错
89
+ if isinstance(item, str):
90
+ item = json.loads(item)
91
+ return item
92
+
93
+ return None
94
+
95
+ async def has_access(self, access_token: str) -> bool:
96
+ return await self.rds.exists(f'{self.series_prefix}:share:access:{access_token}')
97
+
98
+ async def has_permission(self, access_token: str, permission: str) -> bool:
99
+ return await self.rds.sismember(f'{self.series_prefix}:share:permissions:{access_token}', permission)
100
+
101
+ async def has_permissions(self, access_token: str, permissions: list) -> bool:
102
+ if not permissions:
103
+ return True
104
+ async with self.rds.pipeline() as pipe:
105
+ for perm in permissions:
106
+ pipe.sismember(f'{self.series_prefix}:share:permissions:{access_token}', perm)
107
+ results = await pipe.execute()
108
+ return all(results)
109
+
110
+ async def get_cached_team(self, team_id: int) -> Optional[Team]:
111
+ rs = await self.rds.get(f'{self.series_prefix}:share:team:{team_id}')
112
+ if rs:
113
+ try:
114
+ js_team = json.loads(rs)
115
+ if isinstance(js_team, str):
116
+ js_team = json.loads(js_team)
117
+ if js_team and js_team.get('id', None) is not None:
118
+ return Team(**js_team)
119
+ except Exception as e:
120
+ raise AccessDecodeException('团队信息解析失败')
121
+
122
+ return None
@@ -0,0 +1,260 @@
1
+ # -*- coding: utf-8 -*-
2
+ import logging
3
+ import re
4
+ import threading
5
+ from typing import Optional, List
6
+ from starlette.routing import Route, compile_path
7
+ from fastapi.routing import APIRoute
8
+ from starlette.requests import Request
9
+
10
+ from .auth_cache import AuthCachePool
11
+ from ..exception.exceptions import NoAuthException
12
+ from ..model.items import AuthUser, AuthApp, AuthAdmin, Team
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class ShareAuth(object):
18
+ _instance_lock = threading.Lock()
19
+ _biz_inited = False
20
+ _routes_inited = False
21
+
22
+ def __new__(cls, *args, **kwargs):
23
+ if not hasattr(ShareAuth, "_instance"):
24
+ with ShareAuth._instance_lock:
25
+ if not hasattr(ShareAuth, "_instance"):
26
+ ShareAuth._instance = object.__new__(cls)
27
+ return ShareAuth._instance
28
+
29
+ def __init__(self):
30
+ if not self._biz_inited:
31
+ self._biz_inited = True
32
+ # route path regex -> tags
33
+ self.regex_to_tags_map = dict()
34
+ # 鉴权白名单
35
+ self.auth_whitelist = []
36
+ self.auth_cache_pool = AuthCachePool()
37
+
38
+ @staticmethod
39
+ def get_access_token(request: Request):
40
+ """
41
+ 解析请求头鉴权信息
42
+ :param request:
43
+ :return:
44
+ """
45
+ if request and (request.headers or request.query_params):
46
+ access_token = request.headers.get('Authorization', '').replace('Bearer ', '')
47
+ if not access_token:
48
+ access_token = request.cookies.get('access_token')
49
+ if not access_token:
50
+ access_token = request.query_params.get('access_token')
51
+ return access_token
52
+
53
+ return ''
54
+
55
+ def ensure_init(self, routes: List[Route], white_list: List[str] = None, force: bool = False):
56
+ if not force and self._routes_inited:
57
+ return self
58
+ # 构造路由匹配正则与权限颗粒(tags)映射(递归处理 _IncludedRouter 等嵌套路由)
59
+ _tmp_regex_to_tags_map = self._collect_route_tags(routes, prefix='')
60
+ self.regex_to_tags_map.clear()
61
+ self.regex_to_tags_map = _tmp_regex_to_tags_map
62
+ logger.info(f'reload path to tags map: {len(self.regex_to_tags_map)}')
63
+
64
+ # 构造权限白名单
65
+ _auth_whitelist = list()
66
+ if white_list:
67
+ for row in white_list:
68
+ _auth_whitelist.append(re.compile(row))
69
+ self.auth_whitelist.clear()
70
+ self.auth_whitelist = _auth_whitelist
71
+ logger.info(f'reload no auth whitelist: {len(self.auth_whitelist)}')
72
+ # 标记路由已初始化
73
+ self._routes_inited = True
74
+
75
+ return self
76
+
77
+ @staticmethod
78
+ def _collect_route_tags(routes, prefix=''):
79
+ """递归收集 (path_regex, tags) ,展开 _IncludedRouter 等嵌套路由并拼接前缀。"""
80
+ result = dict()
81
+ for route in routes:
82
+ if isinstance(route, APIRoute):
83
+ full_path = prefix + route.path
84
+ path_regex, _, _ = compile_path(full_path)
85
+ result[path_regex] = route.tags
86
+ elif hasattr(route, 'original_router'):
87
+ # FastAPI _IncludedRouter:取嵌套路由 + 前缀
88
+ inc_prefix = prefix
89
+ ctx = getattr(route, 'include_context', None)
90
+ if ctx and ctx.prefix:
91
+ inc_prefix = prefix + ctx.prefix
92
+ nested = ShareAuth._collect_route_tags(route.original_router.routes, inc_prefix)
93
+ result.update(nested)
94
+ elif hasattr(route, 'routes'):
95
+ nested = ShareAuth._collect_route_tags(route.routes, prefix)
96
+ result.update(nested)
97
+ return result
98
+
99
+ async def access_check(self, request: Request):
100
+ """
101
+ 登录校验
102
+ :param request:
103
+ :return:
104
+ """
105
+ access_token = self.get_access_token(request)
106
+ if not access_token:
107
+ raise NoAuthException('请先登录')
108
+
109
+ if not await self.auth_cache_pool.has_access(access_token):
110
+ raise NoAuthException('登录信息已失效')
111
+
112
+ return access_token
113
+
114
+ async def auth_check(self, request: Request):
115
+ """
116
+ 权限校验
117
+ :param request:
118
+ :return:
119
+ """
120
+ if not self.regex_to_tags_map:
121
+ logger.debug(f'no path to tags map')
122
+ return False
123
+ # 优先处理白名单
124
+ for white_regex in self.auth_whitelist:
125
+ if white_regex.match(request.url.path):
126
+ return True
127
+ # 先校验登录
128
+ access_token = await self.access_check(request)
129
+ for regex in self.regex_to_tags_map.keys():
130
+ if regex.match(request.url.path):
131
+ # 匹配到路由
132
+ tags = self.regex_to_tags_map.get(regex)
133
+ if tags:
134
+ # 需要登录且需要鉴权
135
+ auth_rs = await self._rds_permissions_check(tags, access_token)
136
+ if not auth_rs:
137
+ raise NoAuthException('权限不足')
138
+ return True
139
+ else:
140
+ # 仅登录无需鉴权
141
+ return True
142
+
143
+ return False
144
+
145
+ async def _rds_permissions_check(self, tags, access_token) -> bool:
146
+ return await self.auth_cache_pool.has_permissions(access_token, tags)
147
+
148
+ async def get_auth_user(self, request: Request) -> Optional[AuthUser]:
149
+ """
150
+ 获取当前登录的用户信息
151
+ :param request:
152
+ :return:
153
+ """
154
+ access_token = self.get_access_token(request)
155
+ if not access_token:
156
+ raise NoAuthException('请先登录')
157
+
158
+ auth_user = await self.auth_cache_pool.get_cached_user(access_token)
159
+ if not auth_user:
160
+ raise NoAuthException('登录信息已失效或无法获取用户信息')
161
+
162
+ # TODO 待完善
163
+ # # 设置团队上下文
164
+ # if auth_user and auth_user.team_code:
165
+ # team_code_context.set(auth_user.team_code)
166
+
167
+ return auth_user
168
+
169
+ async def get_auth_app(self, request: Request) -> Optional[AuthApp]:
170
+ """
171
+ 获取当前登录的应用信息
172
+ :param request:
173
+ :return:
174
+ """
175
+ access_token = self.get_access_token(request)
176
+ if not access_token:
177
+ raise NoAuthException('请先登录')
178
+
179
+ auth_app = await self.auth_cache_pool.get_cached_app(access_token)
180
+ if not auth_app:
181
+ raise NoAuthException('登录信息已失效或无法获取用户信息')
182
+
183
+ return auth_app
184
+
185
+ async def get_auth_admin(self, request: Request) -> Optional[AuthAdmin]:
186
+ """
187
+ 获取当前登录的管理员信息
188
+ :param request:
189
+ :return:
190
+ """
191
+ access_token = self.get_access_token(request)
192
+ if not access_token:
193
+ raise NoAuthException('请先登录')
194
+
195
+ auth_admin = await self.auth_cache_pool.get_cached_admin(access_token)
196
+ if not auth_admin:
197
+ raise NoAuthException('登录信息已失效或无法获取用户信息')
198
+
199
+ return auth_admin
200
+
201
+ async def get_auth_team(self, request: Request) -> Optional[Team]:
202
+ """
203
+ 获取当前授权用户的团队信息
204
+ :param request:
205
+ :return:
206
+ """
207
+ auth_user = await self.get_auth_user(request)
208
+ if auth_user and auth_user.team_id:
209
+ return await self.auth_cache_pool.get_cached_team(auth_user.team_id)
210
+
211
+ return None
212
+
213
+ async def get_auth_team_by_id(self, team_id: int) -> Optional[Team]:
214
+ """
215
+ 通过团队ID获取团队信息
216
+ :param team_id:
217
+ :return:
218
+ """
219
+ return await self.auth_cache_pool.get_cached_team(team_id)
220
+
221
+ async def get_auth_team_code(self, request: Request) -> Optional[str]:
222
+ """
223
+ 获取授权用户所属团队
224
+ :param request:
225
+ :return:
226
+ """
227
+ access_token = self.get_access_token(request)
228
+ if access_token:
229
+ access_item = await self.auth_cache_pool.get_cached_access_dict(access_token)
230
+ if access_item:
231
+ team_code = access_item.get('team_code', None)
232
+ if team_code:
233
+ return team_code
234
+
235
+ return ''
236
+
237
+
238
+ # 用于handler来Depends,获取授权用户
239
+ async def authed_user(request: Request) -> Optional[AuthUser]:
240
+ return await ShareAuth().get_auth_user(request)
241
+
242
+
243
+ # 用于handler来Depends,获取授权APP信息
244
+ async def authed_app(request: Request) -> Optional[AuthApp]:
245
+ return await ShareAuth().get_auth_app(request)
246
+
247
+
248
+ # 用于handler来Depends,获取授权管理员信息
249
+ async def authed_admin(request: Request) -> Optional[AuthAdmin]:
250
+ return await ShareAuth().get_auth_admin(request)
251
+
252
+
253
+ # 用于handler来Depends,获取授权用户的团队信息
254
+ async def authed_team(request: Request) -> Optional[Team]:
255
+ return await ShareAuth().get_auth_team(request)
256
+
257
+
258
+ # 用于handler来Depends,获取当前授权用户令牌
259
+ def current_access_token(request: Request) -> Optional[str]:
260
+ return ShareAuth.get_access_token(request)
@@ -0,0 +1 @@
1
+ from .async_http_client import AsyncHttpClient