添加演示环境中间件

This commit is contained in:
xie7654
2025-07-05 10:09:23 +08:00
parent e14730bee7
commit 98060beea9
8 changed files with 81 additions and 7 deletions

View File

@@ -25,6 +25,9 @@ SECRET_KEY = 'django-insecure-m4@pv814c_m^pgpyhz^i96a@mcqh_@m9ccu(17*895t!79e!nb
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv('DEBUG', 'False') == 'True'
# 演示环境配置
DEMO_MODE = os.getenv('DEMO_MODE', 'False') == 'False'
ALLOWED_HOSTS = [
'*',
]
@@ -64,6 +67,10 @@ MIDDLEWARE = [
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 演示环境中间件 - 全局禁止修改和删除操作
if DEMO_MODE:
MIDDLEWARE.append('utils.middleware.DemoModeMiddleware')
AUTH_USER_MODEL = 'system.User'
ROOT_URLCONF = 'backend.urls'

View File

@@ -16,8 +16,12 @@ Including another URLconf
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('api/system/', include('system.urls')),
]
# 演示环境下禁用 admin 路由
if not settings.DEMO_MODE:
urlpatterns.insert(0, path('admin/', admin.site.urls))

View File

@@ -0,0 +1,43 @@
import json
from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from rest_framework import status
class DemoModeMiddleware(MiddlewareMixin):
"""
演示环境中间件
全局禁止修改和删除操作
"""
def process_request(self, request):
# 只处理 API 请求
if not request.path.startswith('/api/'):
return None
# 禁止的 HTTP 方法
forbidden_methods = ['POST', 'PUT', 'PATCH', 'DELETE']
if request.method in forbidden_methods:
# 检查是否是登录接口,登录接口允许 POST
if request.path.endswith('/login/') or request.path.endswith('/auth/login/'):
return None
# 检查是否是登出接口,登出接口允许 POST
if request.path.endswith('/logout/') or request.path.endswith('/auth/logout/'):
return None
# 其他修改/删除操作一律禁止
response_data = {
'code': 403,
'message': '演示环境禁止修改和删除操作',
'data': None
}
return JsonResponse(
response_data,
status=status.HTTP_403_FORBIDDEN,
content_type='application/json'
)
return None