Skip to content

Commit 9108971

Browse files
authored
fix: Swagger warning(#2909)
1 parent 4c23b9a commit 9108971

File tree

3 files changed

+28
-37
lines changed

3 files changed

+28
-37
lines changed

apps/common/auth/authenticate.py

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from django.core import cache
1414
from django.core import signing
1515
from django.utils.translation import gettext_lazy as _
16+
from drf_spectacular.extensions import OpenApiAuthenticationExtension
1617
from rest_framework.authentication import TokenAuthentication
1718

1819
from common.exception.app_exception import AppAuthenticationFailed, AppEmbedIdentityFailed, AppChatNumOutOfBoundsFailed, \
@@ -26,6 +27,20 @@ def authenticate(self, request):
2627
return None, None
2728

2829

30+
class AnonymousAuthenticationScheme(OpenApiAuthenticationExtension):
31+
target_class = AnonymousAuthentication # 绑定到你的自定义认证类
32+
name = "AnonymousAuth" # 自定义认证名称(显示在 Swagger UI 中)
33+
34+
def get_security_definition(self, auto_schema):
35+
# 定义认证方式,这里假设匿名认证不需要凭证
36+
return {
37+
}
38+
39+
def get_security_requirement(self, auto_schema):
40+
# 返回安全要求(空字典表示无需认证)
41+
return {}
42+
43+
2944
def new_instance_by_class_path(class_path: str):
3045
parts = class_path.rpartition('.')
3146
package_path = parts[0]
@@ -54,39 +69,23 @@ def get_token_details(self):
5469
return self.token_details
5570

5671

57-
class OpenAIKeyAuth(TokenAuthentication):
58-
def authenticate(self, request):
59-
auth = request.META.get('HTTP_AUTHORIZATION')
60-
auth = auth.replace('Bearer ', '')
61-
# 未认证
62-
if auth is None:
63-
raise AppAuthenticationFailed(1003, _('Not logged in, please log in first'))
64-
try:
65-
token_details = TokenDetails(auth)
66-
for handle in handles:
67-
if handle.support(request, auth, token_details.get_token_details):
68-
return handle.handle(request, auth, token_details.get_token_details)
69-
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user'))
70-
except Exception as e:
71-
traceback.format_exc()
72-
if isinstance(e, AppEmbedIdentityFailed) or isinstance(e, AppChatNumOutOfBoundsFailed) or isinstance(e,
73-
AppApiException):
74-
raise e
75-
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user'))
76-
77-
7872
class TokenAuth(TokenAuthentication):
73+
keyword = "Bearer"
74+
7975
# 重新 authenticate 方法,自定义认证规则
8076
def authenticate(self, request):
8177
auth = request.META.get('HTTP_AUTHORIZATION')
8278
# 未认证
8379
if auth is None:
8480
raise AppAuthenticationFailed(1003, _('Not logged in, please log in first'))
81+
if not auth.startswith("Bearer "):
82+
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user'))
8583
try:
86-
token_details = TokenDetails(auth)
84+
token = auth[7:]
85+
token_details = TokenDetails(token)
8786
for handle in handles:
88-
if handle.support(request, auth, token_details.get_token_details):
89-
return handle.handle(request, auth, token_details.get_token_details)
87+
if handle.support(request, token, token_details.get_token_details):
88+
return handle.handle(request, token, token_details.get_token_details)
9089
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user'))
9190
except Exception as e:
9291
traceback.format_exc()

apps/maxkb/urls.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,11 @@
1515
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
1616
"""
1717
from django.urls import path, re_path, include
18-
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
19-
from rest_framework import permissions
20-
from common.auth import AnonymousAuthentication
2118
from django.views import static
19+
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
2220

2321
from maxkb import settings
2422

25-
SpectacularSwaggerView.permission_classes = [permissions.AllowAny]
26-
SpectacularSwaggerView.authentication_classes = [AnonymousAuthentication]
27-
SpectacularAPIView.permission_classes = [permissions.AllowAny]
28-
SpectacularAPIView.authentication_classes = [AnonymousAuthentication]
29-
SpectacularRedocView.permission_classes = [permissions.AllowAny]
30-
SpectacularRedocView.authentication_classes = [AnonymousAuthentication]
3123
urlpatterns = [
3224
path("api/", include("users.urls")),
3325
path("api/", include("tools.urls"))

apps/users/views/user.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
@date:2025/4/14 19:25
77
@desc:
88
"""
9-
from drf_spectacular.utils import extend_schema
10-
from rest_framework.views import APIView
119
from django.utils.translation import gettext_lazy as _
10+
from drf_spectacular.utils import extend_schema
1211
from rest_framework.request import Request
12+
from rest_framework.views import APIView
1313

14-
from common.auth import TokenAuth
14+
from common.auth.authenticate import TokenAuth
1515
from common.auth.authentication import has_permissions
1616
from common.constants.permission_constants import PermissionConstants
1717
from common.result import result
@@ -36,7 +36,7 @@ class TestPermissionsUserView(APIView):
3636

3737
@extend_schema(methods=['GET'],
3838
description=_("Get current user information"),
39-
operation_id=_("Get current user information"),
39+
operation_id="测试",
4040
tags=[_("User management")],
4141
responses=UserProfileAPI.get_response())
4242
@has_permissions(PermissionConstants.USER_EDIT)

0 commit comments

Comments
 (0)