From 2662d308df2acf12797525491cb135588e443399 Mon Sep 17 00:00:00 2001 From: shaohuzhang1 Date: Thu, 17 Apr 2025 14:26:25 +0800 Subject: [PATCH] fix: swagger --- apps/common/auth/authenticate.py | 47 ++++++++++++++++---------------- apps/maxkb/urls.py | 10 +------ apps/users/views/user.py | 8 +++--- 3 files changed, 28 insertions(+), 37 deletions(-) diff --git a/apps/common/auth/authenticate.py b/apps/common/auth/authenticate.py index e65e110a49e..5f0bcf81c05 100644 --- a/apps/common/auth/authenticate.py +++ b/apps/common/auth/authenticate.py @@ -13,6 +13,7 @@ from django.core import cache from django.core import signing from django.utils.translation import gettext_lazy as _ +from drf_spectacular.extensions import OpenApiAuthenticationExtension from rest_framework.authentication import TokenAuthentication from common.exception.app_exception import AppAuthenticationFailed, AppEmbedIdentityFailed, AppChatNumOutOfBoundsFailed, \ @@ -26,6 +27,20 @@ def authenticate(self, request): return None, None +class AnonymousAuthenticationScheme(OpenApiAuthenticationExtension): + target_class = AnonymousAuthentication # 绑定到你的自定义认证类 + name = "AnonymousAuth" # 自定义认证名称(显示在 Swagger UI 中) + + def get_security_definition(self, auto_schema): + # 定义认证方式,这里假设匿名认证不需要凭证 + return { + } + + def get_security_requirement(self, auto_schema): + # 返回安全要求(空字典表示无需认证) + return {} + + def new_instance_by_class_path(class_path: str): parts = class_path.rpartition('.') package_path = parts[0] @@ -54,39 +69,23 @@ def get_token_details(self): return self.token_details -class OpenAIKeyAuth(TokenAuthentication): - def authenticate(self, request): - auth = request.META.get('HTTP_AUTHORIZATION') - auth = auth.replace('Bearer ', '') - # 未认证 - if auth is None: - raise AppAuthenticationFailed(1003, _('Not logged in, please log in first')) - try: - token_details = TokenDetails(auth) - for handle in handles: - if handle.support(request, auth, token_details.get_token_details): - return handle.handle(request, auth, token_details.get_token_details) - raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user')) - except Exception as e: - traceback.format_exc() - if isinstance(e, AppEmbedIdentityFailed) or isinstance(e, AppChatNumOutOfBoundsFailed) or isinstance(e, - AppApiException): - raise e - raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user')) - - class TokenAuth(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_details = TokenDetails(auth) + token = auth[7:] + token_details = TokenDetails(token) for handle in handles: - if handle.support(request, auth, token_details.get_token_details): - return handle.handle(request, auth, token_details.get_token_details) + 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: traceback.format_exc() diff --git a/apps/maxkb/urls.py b/apps/maxkb/urls.py index 8d56f0e6adf..a613084544b 100644 --- a/apps/maxkb/urls.py +++ b/apps/maxkb/urls.py @@ -15,19 +15,11 @@ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.urls import path, re_path, include -from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView -from rest_framework import permissions -from common.auth import AnonymousAuthentication from django.views import static +from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView from maxkb import settings -SpectacularSwaggerView.permission_classes = [permissions.AllowAny] -SpectacularSwaggerView.authentication_classes = [AnonymousAuthentication] -SpectacularAPIView.permission_classes = [permissions.AllowAny] -SpectacularAPIView.authentication_classes = [AnonymousAuthentication] -SpectacularRedocView.permission_classes = [permissions.AllowAny] -SpectacularRedocView.authentication_classes = [AnonymousAuthentication] urlpatterns = [ path("api/", include("users.urls")), ] diff --git a/apps/users/views/user.py b/apps/users/views/user.py index 5eb885584f1..18964ddd123 100644 --- a/apps/users/views/user.py +++ b/apps/users/views/user.py @@ -6,12 +6,12 @@ @date:2025/4/14 19:25 @desc: """ -from drf_spectacular.utils import extend_schema -from rest_framework.views import APIView from django.utils.translation import gettext_lazy as _ +from drf_spectacular.utils import extend_schema from rest_framework.request import Request +from rest_framework.views import APIView -from common.auth import TokenAuth +from common.auth.authenticate import TokenAuth from common.auth.authentication import has_permissions from common.constants.permission_constants import PermissionConstants from common.result import result @@ -36,7 +36,7 @@ class TestPermissionsUserView(APIView): @extend_schema(methods=['GET'], description=_("Get current user information"), - operation_id=_("Get current user information"), + operation_id="测试", tags=[_("User management")], responses=UserProfileAPI.get_response()) @has_permissions(PermissionConstants.USER_EDIT)