Untitled
unknown
plain_text
2 years ago
3.1 kB
29
Indexable
def get_messages(request):
if request.method == 'GET':
auth_header = request.headers.get('Authorization', '')
if not auth_header.startswith('Bearer '):
return JsonResponse({'error': 'Authorization token not provided or invalid'}, status=401)
token = auth_header.split('Bearer ')[1]
try:
# Validate the token
decoded_token = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM], audience=EXPECTED_AUDIENCE)
# Continue if the token is valid
chat_session_id = request.GET.get('chat_session_id')
if not chat_session_id:
return JsonResponse({'error': 'Missing chat session ID'}, status=400)
if not is_valid_numeric_id(chat_session_id):
return JsonResponse({'error': 'Invalid chat_session_id format'}, status=400)
# Fetch messages for the specified chat session ID
url = f'{os.getenv("SUPABASE_URL")}/rest/v1/decrypted_messages?chat_session_id=eq.{chat_session_id}&select=id,decrypted_message,user_id,sender_type'
headers = {
'Authorization': f'Bearer {token}',
'apikey': os.getenv("SUPABASE_KEY")
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
messages = response.json()
if not isinstance(messages, list) or not all(isinstance(msg, dict) for msg in messages):
return JsonResponse({'error': 'Unexpected data format'}, status=500)
required_keys = {'id', 'decrypted_message', 'user_id', 'sender_type'}
if not all(required_keys.issubset(msg.keys()) for msg in messages):
return JsonResponse({'error': 'Missing required message fields'}, status=500)
validated_messages = filter(is_valid_message, messages)
formatted_messages = [
{
'id': msg['id'],
'text': msg['decrypted_message'], # Use decrypted_message here
'user_id': msg['user_id'],
'sender_type': msg['sender_type']
}
for msg in messages
]
return JsonResponse({'messages': formatted_messages})
else:
return JsonResponse({'error': 'Failed to fetch messages'}, status=response.status_code)
except jwt.ExpiredSignatureError:
return JsonResponse({'error': 'JWT Token expired'}, status=401)
except jwt.InvalidAudienceError:
return JsonResponse({'error': 'Invalid audience in JWT Token'}, status=401)
except jwt.InvalidTokenError:
return JsonResponse({'error': 'Invalid JWT Token'}, status=401)
except Exception as e:
return JsonResponse({'error': str(e)}, status=500)
else:
return JsonResponse({'error': 'Invalid request method'}, status=405)Editor is loading...
Leave a Comment