认证不需要上传文件

This commit is contained in:
wanjia 2025-06-03 15:06:48 +08:00
parent f220c59c5a
commit e707cfd4e8
2 changed files with 22 additions and 124 deletions

View File

@ -35,83 +35,32 @@ class GmailAuthInitiateView(APIView):
API 视图用于启动 Gmail OAuth2 认证流程
"""
permission_classes = [IsAuthenticated] # 限制访问,仅允许已认证用户
def post(self, request):
"""
处理 POST 请求启动 Gmail OAuth2 认证并返回授权 URL
支持两种方式提供客户端密钥:
1. 在请求体中提供client_secret_json字段
2. 上传名为client_secret_file的JSON文件
直接使用系统中已配置的客户端密钥文件
Args:
request: Django REST Framework 请求对象包含客户端密钥 JSON 数据或文件
request: Django REST Framework 请求对象
Returns:
Response: 包含授权 URL JSON 响应成功时或错误信息失败时
Status Codes:
200: 成功生成授权 URL
400: 请求数据无效
500: 服务器内部错误如认证服务失败
"""
logger.debug(f"Received auth initiate request: {request.data}")
logger.debug(f"Received auth initiate request from user {request.user.id}")
# 检查是否是文件上传方式
client_secret_json = None
if 'client_secret_file' in request.FILES:
try:
# 读取上传的JSON文件内容
client_secret_file = request.FILES['client_secret_file']
client_secret_json = json.loads(client_secret_file.read().decode('utf-8'))
logger.info(f"从上传文件读取到客户端密钥JSON")
except json.JSONDecodeError as e:
logger.error(f"解析客户端密钥JSON文件失败: {str(e)}")
return Response({
'code': 400,
'message': f'无效的JSON文件格式: {str(e)}',
'data': None
}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
logger.error(f"处理上传文件失败: {str(e)}")
return Response({
'code': 500,
'message': f'处理上传文件失败: {str(e)}',
'data': None
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# 直接使用系统中已配置的客户端密钥文件
client_secret_path = 'media/secret/client_secret_266164728215-v84lngbp3vgr4ulql01sqkg5vaigf4a5.apps.googleusercontent.com.json'
# 如果不是文件上传则尝试从请求数据中提取JSON
if not client_secret_json:
serializer = GmailCredentialSerializer(data=request.data, context={'request': request})
if serializer.is_valid():
try:
# 从请求数据中提取客户端密钥 JSON
client_secret_json = serializer.validated_data['client_secret_json']
except Exception as e:
logger.error(f"未提供客户端密钥JSON: {str(e)}")
return Response({
'code': 400,
'message': '请提供client_secret_json字段或上传client_secret_file文件',
'data': None
}, status=status.HTTP_400_BAD_REQUEST)
else:
# 记录无效请求数据并返回错误响应
logger.warning(f"Invalid request data: {serializer.errors}")
return Response({
'code': 400,
'message': '请求数据无效请提供client_secret_json字段或上传client_secret_file文件',
'data': serializer.errors
}, status=status.HTTP_400_BAD_REQUEST)
# 如果此时仍然没有client_secret_json返回错误
if not client_secret_json:
return Response({
'code': 400,
'message': '请提供client_secret_json字段或上传client_secret_file文件',
'data': None
}, status=status.HTTP_400_BAD_REQUEST)
try:
# 读取客户端密钥文件
with open(client_secret_path, 'r') as f:
client_secret_json = json.load(f)
# 调用 GmailService 生成授权 URL
auth_url = GmailService.initiate_authentication(request.user, client_secret_json)
logger.info(f"Generated auth URL for user {request.user.id}")
@ -135,17 +84,14 @@ class GmailAuthCompleteView(APIView):
API 视图用于完成 Gmail OAuth2 认证流程
"""
permission_classes = [IsAuthenticated] # 限制访问,仅允许已认证用户
def post(self, request):
"""
处理 POST 请求使用授权代码完成 Gmail OAuth2 认证并保存凭证
支持两种方式提供客户端密钥:
1. 在请求体中提供client_secret_json字段
2. 上传名为client_secret_file的JSON文件
直接使用系统中已配置的客户端密钥文件
Args:
request: Django REST Framework 请求对象包含授权代码和客户端密钥 JSON 或文件
request: Django REST Framework 请求对象包含授权代码
Returns:
Response: 包含已保存凭证数据的 JSON 响应成功时或错误信息失败时
@ -155,72 +101,25 @@ class GmailAuthCompleteView(APIView):
400: 请求数据无效
500: 服务器内部错误如认证失败
"""
logger.debug(f"Received auth complete request: {request.data}")
logger.debug(f"Received auth complete request from user {request.user.id}")
# 检查是否是文件上传方式
client_secret_json = None
if 'client_secret_file' in request.FILES:
try:
# 读取上传的JSON文件内容
client_secret_file = request.FILES['client_secret_file']
client_secret_json = json.loads(client_secret_file.read().decode('utf-8'))
logger.info(f"从上传文件读取到客户端密钥JSON")
except json.JSONDecodeError as e:
logger.error(f"解析客户端密钥JSON文件失败: {str(e)}")
return Response({
'code': 400,
'message': f'无效的JSON文件格式: {str(e)}',
'data': None
}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
logger.error(f"处理上传文件失败: {str(e)}")
return Response({
'code': 500,
'message': f'处理上传文件失败: {str(e)}',
'data': None
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# 直接使用系统中已配置的客户端密钥文件
client_secret_path = 'media/secret/client_secret_266164728215-v84lngbp3vgr4ulql01sqkg5vaigf4a5.apps.googleusercontent.com.json'
# 获取授权,无论是哪种方式都需要
# 获取授权代码
auth_code = request.data.get('auth_code')
if not auth_code:
return Response({
'code': 400,
'message': '必须提供授权码',
'data': None
}, status=status.HTTP_400_BAD_REQUEST)
# 如果不是文件上传则尝试从请求数据中提取JSON
if not client_secret_json:
serializer = GmailCredentialSerializer(data=request.data, context={'request': request})
if serializer.is_valid():
try:
# 从请求数据中提取客户端密钥 JSON
client_secret_json = serializer.validated_data['client_secret_json']
except Exception as e:
logger.error(f"未提供客户端密钥JSON: {str(e)}")
return Response({
'code': 400,
'message': '请提供client_secret_json字段或上传client_secret_file文件',
'data': None
}, status=status.HTTP_400_BAD_REQUEST)
else:
# 记录无效请求数据并返回错误响应
logger.warning(f"Invalid request data: {serializer.errors}")
return Response({
'code': 400,
'message': '请求数据无效请提供client_secret_json字段或上传client_secret_file文件',
'data': serializer.errors
}, status=status.HTTP_400_BAD_REQUEST)
# 如果此时仍然没有client_secret_json返回错误
if not client_secret_json:
return Response({
'code': 400,
'message': '请提供client_secret_json字段或上传client_secret_file文件',
'message': '缺少必要的授权代码',
'data': None
}, status=status.HTTP_400_BAD_REQUEST)
try:
# 读取客户端密钥文件
with open(client_secret_path, 'r') as f:
client_secret_json = json.load(f)
# 完成认证并保存凭证
credential = GmailService.complete_authentication(request.user, auth_code, client_secret_json)
# 序列化凭证数据以返回
@ -240,7 +139,6 @@ class GmailAuthCompleteView(APIView):
'data': None
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class GmailCredentialViewSet(viewsets.ModelViewSet):
"""
Gmail凭证管理视图集提供对Gmail账户凭证的完整CRUD操作

View File

@ -28,7 +28,7 @@ SECRET_KEY = 'django-insecure-aie+z75u&tnnx8@g!2ie+q)qhq1!eg&ob!c1(e1vr!eclh+xv6
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '325a-180-159-100-165.ngrok-free.app']
ALLOWED_HOSTS = ['*']
# Application definition
@ -180,7 +180,7 @@ AUTH_USER_MODEL = 'accounts.User'
API_BASE_URL = 'http://81.69.223.133:48329'
SILICON_CLOUD_API_KEY = 'sk-xqbujijjqqmlmlvkhvxeogqjtzslnhdtqxqgiyuhwpoqcjvf'
GMAIL_WEBHOOK_URL = 'https://325a-180-159-100-165.ngrok-free.app/api/gmail/webhook/'
GMAIL_WEBHOOK_URL = 'https://7403-180-159-100-165.ngrok-free.app/api/gmail/webhook/'
APPLICATION_ID = 'd5d11efa-ea9a-11ef-9933-0242ac120006'