fix: Swagger warning(#2909)
Some checks are pending
sync2gitee / repo-sync (push) Waiting to run

This commit is contained in:
shaohuzhang1 2025-04-17 14:27:58 +08:00 committed by GitHub
parent 4c23b9aded
commit 9108971fdc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 28 additions and 37 deletions

View File

@ -13,6 +13,7 @@ from django.conf import settings
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 @@ class AnonymousAuthentication(TokenAuthentication):
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 @@ class TokenDetails:
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()

View File

@ -15,19 +15,11 @@ Including another URLconf
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")),
path("api/", include("tools.urls"))

View File

@ -6,12 +6,12 @@
@date2025/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)