diff --git a/apps/common/auth/authenticate.py b/apps/common/auth/authenticate.py index 5e249d78345..a423ef3cc62 100644 --- a/apps/common/auth/authenticate.py +++ b/apps/common/auth/authenticate.py @@ -52,6 +52,7 @@ def new_instance_by_class_path(class_path: str): handles = [new_instance_by_class_path(class_path) for class_path in settings.AUTH_HANDLES] chat_handles = [new_instance_by_class_path(class_path) for class_path in settings.CHAT_AUTH_HANDLES] +all_handles = handles + chat_handles class TokenDetails: @@ -120,3 +121,29 @@ def authenticate(self, request): AppApiException): raise e raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user')) + + +class AllTokenAuth(TokenAuthentication): + keyword = "Bearer" + + # 重新 authenticate 方法,自定义认证规则 + def authenticate(self, request): + auth = request.META.get('HTTP_AUTHORIZATION') + # 未认证 + if auth is None: + raise AppAuthenticationFailed(1003, _('Not logged in, please log in first')) + if not auth.startswith("Bearer "): + raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user')) + try: + token = auth[7:] + token_details = TokenDetails(token) + for handle in all_handles: + if handle.support(request, token, token_details.get_token_details): + return handle.handle(request, token, token_details.get_token_details) + raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user')) + except Exception as e: + maxkb_logger.error(f'Exception: {e}', exc_info=True) + if isinstance(e, AppEmbedIdentityFailed) or isinstance(e, AppChatNumOutOfBoundsFailed) or isinstance(e, + AppApiException): + raise e + raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user')) diff --git a/apps/oss/views/file.py b/apps/oss/views/file.py index e50ad05e502..ff0b9bf8aa8 100644 --- a/apps/oss/views/file.py +++ b/apps/oss/views/file.py @@ -4,7 +4,7 @@ from rest_framework.parsers import MultiPartParser from rest_framework.views import APIView from rest_framework.views import Request -from common.auth import TokenAuth +from common.auth import TokenAuth, AllTokenAuth from common.log.log import log from common.result import result from knowledge.api.file import FileUploadAPI, FileGetAPI @@ -29,7 +29,7 @@ def get(self, request: Request, file_id: str): class FileView(APIView): - authentication_classes = [TokenAuth] + authentication_classes = [AllTokenAuth] parser_classes = [MultiPartParser] @extend_schema( @@ -80,4 +80,4 @@ class GetUrlView(APIView): def get(self, request: Request, application_id: str): url = request.query_params.get('url') result_data = get_url_content(url, application_id) - return result.success(result_data) \ No newline at end of file + return result.success(result_data)