pms_server / admin_app /views.py
Noel-Teens's picture
implemented resend api
116dc2c
Raw History Blame Contribute Delete
31.1 kB
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from django.views.decorators.clickjacking import xframe_options_exempt
from rest_framework_simplejwt.tokens import AccessToken
from rest_framework_simplejwt.exceptions import TokenError
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth import get_user_model
from auth_app.utils import IsAdmin
from auth_app.models import User
from .models import PaperWork, Invitation
from .serializers import (
PaperWorkSerializer, PaperWorkDeadlineUpdateSerializer,
InvitationSerializer, AcceptInvitationSerializer
)
from auth_app.serializers import UserRegistrationSerializer, UserSerializer
from api.models import Version
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils import timezone
import os
import requests
import zipfile
import base64
from django.http import FileResponse, Http404, JsonResponse, HttpResponseNotFound
def _auth_from_query_token(request):
token = getattr(request, "query_params", {}).get("token") or request.GET.get("token")
if not token:
return None
try:
decoded = AccessToken(token)
user_id = decoded.get("user_id")
if not user_id:
return None
User = get_user_model()
user = User.objects.get(id=user_id)
request.user = user
return user
except TokenError as e:
print(f"Token authentication error: {e}")
return None
except get_user_model().DoesNotExist:
return None
except Exception as e:
print(f"Unexpected token parse error: {e}")
return None
def _build_invite_link(token: str) -> str:
# Use FRONTEND_URL so the user clicks a frontend route which then POSTs to API
return f"{settings.FRONTEND_URL}/accept-invite/{token}"
import logging
logger = logging.getLogger(__name__)
def _send_invite_email(email: str, invite_link: str, inviter: str = None):
"""Send an invitation email using Resend API."""
subject = "You're invited to join Project Management System"
html_content = render_to_string(
"emails/invite.html", {"invite_link": invite_link, "inviter": inviter}
)
text_content = (
f"You have been invited to join the Project Management System.\n\n"
f"Click the link to accept: {invite_link}"
)
# Try Resend API first
try:
api_key = getattr(settings, 'RESEND_API_KEY', None)
if not api_key:
raise Exception("RESEND_API_KEY not set in settings.")
from_email = getattr(settings, 'FROM_EMAIL', 'PMS <onboarding@resend.dev>')
# Resend API payload
payload = {
"from": from_email,
"to": [email],
"subject": subject,
"html": html_content,
"text": text_content
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
response = requests.post(
"https://api.resend.com/emails",
json=payload,
headers=headers
)
if response.status_code not in (200, 201):
logger.error(f"Resend API error {response.status_code}: {response.text}")
raise Exception(f"Resend API error {response.status_code}: {response.text}")
logger.info(f"Invitation email sent successfully to {email} via Resend API")
return {
"status_code": response.status_code,
"body": response.text,
"method": "resend_api"
}
except Exception as e:
logger.error(f"Failed to send invitation email to {email}: {str(e)}")
raise
@csrf_exempt
@api_view(["POST"])
@permission_classes([IsAuthenticated, IsAdmin])
def invite_user(request):
"""Admin endpoint to create Invitation and send email with retry support"""
logger.info(f"Invite user request from {request.user.username} ({request.user.role})")
logger.info(f"Request data: {request.data}")
serializer = InvitationSerializer(data=request.data)
if not serializer.is_valid():
logger.error(f"Serializer validation failed: {serializer.errors}")
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
email = serializer.validated_data["email"].lower()
role = serializer.validated_data.get("role", "RESEARCHER")
force_resend = serializer.validated_data.get("force_resend", False)
logger.info(f"Processing invitation for {email} with role {role}")
# Prevent inviting an email that already has a user
if User.objects.filter(email__iexact=email).exists():
logger.warning(f"Attempted to invite existing user: {email}")
return Response({"error": "A user with this email already exists."}, status=status.HTTP_400_BAD_REQUEST)
# Handle existing invitations with retry logic
try:
invitation = Invitation.objects.get(email=email)
created = False
# If invitation was already accepted but user doesn't exist (data inconsistency), mark as not accepted
if invitation.is_accepted and not User.objects.filter(email__iexact=email).exists():
invitation.is_accepted = False
invitation.save()
logger.info(f"Reset accepted status for invitation {email} - user doesn't exist")
except Invitation.DoesNotExist:
invitation = Invitation.objects.create(
email=email,
role=role,
invited_by=request.user
)
created = True
if not created:
# Check if we can send another email
if not force_resend and not invitation.can_send_email():
reason = "already accepted" if invitation.is_accepted else "expired" if invitation.is_expired() else "maximum attempts reached"
logger.warning(f"Cannot send invitation to {email}: {reason}")
return Response({
"error": f"Cannot send invitation: {reason}",
"details": {
"attempts": invitation.email_attempts,
"last_attempt": invitation.last_email_attempt,
"email_sent_successfully": invitation.email_sent_successfully,
"expires_at": invitation.expires_at,
"is_expired": invitation.is_expired()
}
}, status=status.HTTP_400_BAD_REQUEST)
# Update invitation details if needed
invitation.role = role
invitation.invited_by = request.user
invitation.is_accepted = False
# Extend expiry if it's expired or about to expire
if invitation.is_expired() or invitation.time_remaining() < timezone.timedelta(hours=24):
invitation.expires_at = timezone.now() + timezone.timedelta(hours=48)
invitation.save()
logger.info(f"Updated existing invitation for {email} (attempt #{invitation.email_attempts + 1})")
else:
logger.info(f"Created new invitation for {email}")
invite_link = _build_invite_link(invitation.token)
# Send email with error handling and attempt tracking
try:
_send_invite_email(email, invite_link, inviter=getattr(request.user, "username", None))
invitation.record_email_attempt(success=True)
logger.info(f"Successfully sent invitation email to {email} (attempt #{invitation.email_attempts})")
return Response({
"message": "Invitation sent successfully.",
"details": {
"attempt_number": invitation.email_attempts,
"remaining_attempts": max(0, 5 - invitation.email_attempts),
"expires_at": invitation.expires_at
}
}, status=status.HTTP_201_CREATED)
except Exception as e:
invitation.record_email_attempt(success=False)
logger.error(f"Failed to send invitation email to {email} (attempt #{invitation.email_attempts}): {str(e)}")
# Don't delete the invitation on failure - allow retries
return Response({
"error": "Failed to send invitation email. You can try again.",
"details": {
"attempt_number": invitation.email_attempts,
"remaining_attempts": max(0, 5 - invitation.email_attempts),
"can_retry": invitation.can_send_email(),
"error_message": str(e)
}
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
@csrf_exempt
@api_view(["POST"])
@permission_classes([AllowAny])
def accept_invite(request, token):
"""User endpoint to accept invite and create their account"""
# Validate invitation
try:
invitation = Invitation.objects.get(token=token, is_accepted=False)
except Invitation.DoesNotExist:
return Response({"error": "Invalid or already used invitation."}, status=status.HTTP_400_BAD_REQUEST)
if invitation.is_expired():
return Response({"error": "Invitation has expired."}, status=status.HTTP_400_BAD_REQUEST)
serializer = AcceptInvitationSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
username = serializer.validated_data["username"]
password = serializer.validated_data["password"]
first_name = serializer.validated_data.get("first_name", "")
last_name = serializer.validated_data.get("last_name", "")
# Create the user
user = User.objects.create_user(username=username, email=invitation.email, password=password)
user.first_name = first_name
user.last_name = last_name
# Set role from invitation
user.role = invitation.role
user.save()
# Mark invitation accepted
invitation.is_accepted = True
invitation.save()
return Response({"message": "User created successfully."}, status=status.HTTP_201_CREATED)
@csrf_exempt
@api_view(["POST"])
@permission_classes([IsAuthenticated, IsAdmin])
def retry_invitation(request, token):
"""Admin endpoint to retry sending an invitation email"""
try:
invitation = Invitation.objects.get(token=token, is_accepted=False)
except Invitation.DoesNotExist:
return Response({"error": "Invitation not found or already accepted."}, status=status.HTTP_404_NOT_FOUND)
logger.info(f"Retry invitation request for {invitation.email} from {request.user.username}")
# Check if we can send another email
if not invitation.can_send_email():
reason = "expired" if invitation.is_expired() else "maximum attempts reached"
logger.warning(f"Cannot retry invitation to {invitation.email}: {reason}")
return Response({
"error": f"Cannot retry invitation: {reason}",
"details": {
"attempts": invitation.email_attempts,
"last_attempt": invitation.last_email_attempt,
"email_sent_successfully": invitation.email_sent_successfully,
"expires_at": invitation.expires_at,
"is_expired": invitation.is_expired()
}
}, status=status.HTTP_400_BAD_REQUEST)
invite_link = _build_invite_link(invitation.token)
# Send email with error handling and attempt tracking
try:
_send_invite_email(invitation.email, invite_link, inviter=getattr(request.user, "username", None))
invitation.record_email_attempt(success=True)
logger.info(f"Successfully retried invitation email to {invitation.email} (attempt #{invitation.email_attempts})")
return Response({
"message": "Invitation retry sent successfully.",
"details": {
"attempt_number": invitation.email_attempts,
"remaining_attempts": max(0, 5 - invitation.email_attempts),
"expires_at": invitation.expires_at
}
}, status=status.HTTP_200_OK)
except Exception as e:
invitation.record_email_attempt(success=False)
logger.error(f"Failed to retry invitation email to {invitation.email} (attempt #{invitation.email_attempts}): {str(e)}")
return Response({
"error": "Failed to retry invitation email.",
"details": {
"attempt_number": invitation.email_attempts,
"remaining_attempts": max(0, 5 - invitation.email_attempts),
"can_retry": invitation.can_send_email(),
"error_message": str(e)
}
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
@api_view(["GET"])
@permission_classes([IsAuthenticated, IsAdmin])
def pending_invitations(request):
"""Admin endpoint to list all pending invitations with retry status"""
invitations = Invitation.objects.filter(is_accepted=False).order_by('-created_at')
invitation_data = []
for invitation in invitations:
invitation_data.append({
"token": str(invitation.token),
"email": invitation.email,
"role": invitation.role,
"invited_by": invitation.invited_by.username if invitation.invited_by else None,
"created_at": invitation.created_at,
"expires_at": invitation.expires_at,
"is_expired": invitation.is_expired(),
"time_remaining": str(invitation.time_remaining()),
"email_attempts": invitation.email_attempts,
"last_email_attempt": invitation.last_email_attempt,
"email_sent_successfully": invitation.email_sent_successfully,
"can_retry": invitation.can_send_email(),
"remaining_attempts": max(0, 5 - invitation.email_attempts)
})
return Response({
"invitations": invitation_data,
"total_count": len(invitation_data)
})
@api_view(["GET"])
@permission_classes([AllowAny])
def verify_invite(request, token):
"""Optional endpoint for the frontend to check token validity before rendering the sign up form."""
try:
invitation = Invitation.objects.get(token=token, is_accepted=False)
except Invitation.DoesNotExist:
return Response({"valid": False, "reason": "not_found"}, status=status.HTTP_404_NOT_FOUND)
if invitation.is_expired():
return Response({"valid": False, "reason": "expired"}, status=status.HTTP_400_BAD_REQUEST)
return Response({"valid": True, "email": invitation.email, "expires_at": invitation.expires_at})
@api_view(['PATCH'])
@permission_classes([IsAuthenticated, IsAdmin])
@csrf_exempt
def update_paperwork_deadline(request, id):
paperwork = get_object_or_404(PaperWork, id=id)
serializer = PaperWorkDeadlineUpdateSerializer(paperwork, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(PaperWorkSerializer(paperwork).data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['PATCH'])
@permission_classes([IsAuthenticated, IsAdmin])
@csrf_exempt
def update_user_status(request, username):
user = get_object_or_404(User, username=username)
if 'status' not in request.data:
return Response({'error': 'Status field is required'}, status=status.HTTP_400_BAD_REQUEST)
status_value = request.data['status']
if status_value not in dict(User.STATUS_CHOICES):
return Response({'error': 'Invalid status value'}, status=status.HTTP_400_BAD_REQUEST)
user.status = status_value
user.save()
return Response(UserSerializer(user).data)
@api_view(['POST'])
@permission_classes([IsAuthenticated, IsAdmin])
@csrf_exempt
def assign_paperwork(request):
serializer = PaperWorkSerializer(data=request.data)
if serializer.is_valid():
# Get the researcher
researcher_id = serializer.validated_data.pop('researcher_id')
researcher = get_object_or_404(User, id=researcher_id, role='RESEARCHER')
# Create the paperwork
paperwork = serializer.save(researcher=researcher)
return Response(PaperWorkSerializer(paperwork).data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET'])
@permission_classes([IsAuthenticated, IsAdmin])
def users_list(request):
"""Endpoint to list all users except admins in the system. Only accessible to admins."""
users = User.objects.exclude(role='ADMIN').only('id', 'username', 'email', 'role', 'status')
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
@api_view(['GET'])
@permission_classes([AllowAny]) # was IsAuthenticated
@xframe_options_exempt # allow rendering in <iframe>
def view_paperwork_file(request, paperwork_id, version_no, file_type):
# 1) Try auth from ?token=...
_auth_from_query_token(request)
# 2) If still unauthenticated, reject (works for either header or query-token)
if not request.user or not request.user.is_authenticated:
return Response({'detail': 'Authentication credentials were not provided.'},
status=status.HTTP_401_UNAUTHORIZED)
# Existing lookup
try:
version = Version.objects.get(
paperwork__id=paperwork_id, version_no=version_no
)
except Version.DoesNotExist:
raise Http404("Version not found")
# 3) Object-level authorization: admin OR the assigned researcher
is_admin = getattr(request.user, 'role', '').upper() == 'ADMIN'
is_owner = getattr(version.paperwork, 'researcher_id', None) == getattr(request.user, 'id', None)
if not (is_admin or is_owner):
return Response({'detail': 'Forbidden'}, status=status.HTTP_403_FORBIDDEN)
# Get the file path from the version based on file type
file_path = None
if file_type == 'pdf':
file_path = version.pdf_path
elif file_type == 'tex':
file_path = version.latex_path
elif file_type == 'zip':
file_path = version.python_path
elif file_type == 'docx':
file_path = version.docx_path
else:
return Response({'error': 'Invalid file type'}, status=status.HTTP_400_BAD_REQUEST)
if not file_path:
raise Http404(f"{file_type.capitalize()} file not found for this version")
# Use Django's default storage to access files from Backblaze B2
from django.core.files.storage import default_storage
from django.http import HttpResponse
import mimetypes
try:
# Check if file exists in storage (Backblaze B2)
if not default_storage.exists(file_path):
logger.error(f"File not found in B2 storage: {file_path}")
raise Http404("File not found in storage")
# Get the file from storage
file_obj = default_storage.open(file_path, 'rb')
# Determine content type
content_type, _ = mimetypes.guess_type(file_path)
if not content_type:
content_type = 'application/octet-stream'
# Create response with file content
response = HttpResponse(file_obj.read(), content_type=content_type)
# Set filename for download
filename = os.path.basename(file_path) or f"paper.{file_type}"
disposition = 'attachment' if request.GET.get('download') else 'inline'
response['Content-Disposition'] = f'{disposition}; filename="{filename}"'
file_obj.close()
return response
except Exception as e:
logger.error(f"Error accessing file {file_path} from B2 storage: {str(e)}")
# Fallback: try local file system as backup
filename = os.path.basename(file_path) if file_path else f"paper.{file_type}"
version_str = f"v{version_no}"
storage_full_path = os.path.join(
settings.MEDIA_ROOT, file_path
)
if os.path.exists(storage_full_path):
response = FileResponse(open(storage_full_path, 'rb'))
disposition = 'attachment' if request.GET.get('download') else 'inline'
response['Content-Disposition'] = f'{disposition}; filename="{filename}"'
return response
logger.error(f"File not found in both B2 storage and local filesystem: {file_path}")
raise Http404("File not found")
@api_view(['GET'])
@permission_classes([IsAuthenticated, IsAdmin])
def user_detail(request, user_id):
"""Endpoint to get a specific user by ID. Only accessible to admins."""
from django.shortcuts import get_object_or_404
user = get_object_or_404(User, id=user_id)
serializer = UserSerializer(user)
return Response(serializer.data)
@api_view(['GET'])
@permission_classes([AllowAny]) # was [IsAuthenticated, IsAdmin]
@xframe_options_exempt # allow rendering in <iframe>
def view_zip_contents(request, paperwork_id, version_no):
# 1) Try auth from ?token=
_auth_from_query_token(request)
# 2) Require auth
if not request.user or not request.user.is_authenticated:
return Response({'detail': 'Authentication credentials were not provided.'},
status=status.HTTP_401_UNAUTHORIZED)
# Get version from database
try:
version = Version.objects.get(
paperwork__id=paperwork_id, version_no=version_no
)
except Version.DoesNotExist:
raise Http404("Version not found")
is_admin = getattr(request.user, 'role', '').upper() == 'ADMIN'
is_owner = getattr(version.paperwork, 'researcher_id', None) == getattr(request.user, 'id', None)
if not (is_admin or is_owner):
return Response({'detail': 'Forbidden'}, status=status.HTTP_403_FORBIDDEN)
# Get the python ZIP file path
if not version.python_path:
raise Http404("ZIP file not found for this version")
# Use Django's default storage to access ZIP from Backblaze B2
from django.core.files.storage import default_storage
import tempfile
try:
# Check if file exists in storage
if not default_storage.exists(version.python_path):
raise Http404("ZIP file not found in storage")
# Download ZIP file to temporary location for processing
with default_storage.open(version.python_path, 'rb') as zip_file:
contents = []
with zipfile.ZipFile(zip_file, 'r') as z:
for name in z.namelist():
contents.append(name)
return JsonResponse({"files": contents})
except Exception as e:
logger.error(f"Error accessing ZIP file {version.python_path} from B2 storage: {str(e)}")
# Fallback to local file system
version_str = f"v{version_no}"
zip_path = os.path.join(
settings.MEDIA_ROOT,
settings.PYTHON_STORAGE_PATH,
str(paperwork_id),
version_str,
"code.zip"
)
if not os.path.exists(zip_path):
raise Http404("ZIP file not found")
contents = []
with zipfile.ZipFile(zip_path, 'r') as z:
for name in z.namelist():
contents.append(name)
return JsonResponse({"files": contents})
@api_view(['GET'])
@permission_classes([AllowAny])
@xframe_options_exempt
def view_zip_file_content(request, paperwork_id, version_no, file_path):
# 1) Try auth from ?token=...
_auth_from_query_token(request)
# 2) If still unauthenticated, reject
if not request.user or not request.user.is_authenticated:
return Response({'detail': 'Authentication credentials were not provided.'},
status=status.HTTP_401_UNAUTHORIZED)
# Get version from database
try:
version = Version.objects.get(
paperwork__id=paperwork_id, version_no=version_no
)
except Version.DoesNotExist:
raise Http404("Version not found")
# 3) Object-level authorization: admin OR the assigned researcher
is_admin = getattr(request.user, 'role', '').upper() == 'ADMIN'
is_owner = getattr(version.paperwork, 'researcher_id', None) == getattr(request.user, 'id', None)
if not (is_admin or is_owner):
return Response({'detail': 'Forbidden'}, status=status.HTTP_403_FORBIDDEN)
# Get the python ZIP file path
if not version.python_path:
raise Http404("ZIP file not found for this version")
# Use Django's default storage to access ZIP from Backblaze B2
from django.core.files.storage import default_storage
try:
# Check if file exists in storage
if not default_storage.exists(version.python_path):
raise Http404("ZIP file not found in storage")
# Access ZIP file from storage
with default_storage.open(version.python_path, 'rb') as zip_file:
with zipfile.ZipFile(zip_file, 'r') as z:
# Check if the file exists in the ZIP
if file_path not in z.namelist():
return Response({'error': 'File not found in ZIP archive'}, status=status.HTTP_404_NOT_FOUND)
# Determine content type based on file extension
file_extension = file_path.split('.')[-1].lower() if '.' in file_path else ''
content_type = 'text/plain'
is_binary = False
# Text-based files
if file_extension in ['py']:
content_type = 'text/x-python'
elif file_extension in ['ipynb']:
content_type = 'application/json'
# Image files
elif file_extension in ['png']:
content_type = 'image/png'
is_binary = True
elif file_extension in ['jpg', 'jpeg']:
content_type = 'image/jpeg'
is_binary = True
# Handle binary files (images)
if is_binary:
file_content = base64.b64encode(z.read(file_path)).decode('utf-8')
return Response({
'content': file_content,
'content_type': content_type,
'is_binary': True
})
else:
# Handle text files
file_content = z.read(file_path).decode('utf-8', errors='replace')
return Response({
'content': file_content,
'content_type': content_type,
'is_binary': False
})
except Exception as e:
logger.error(f"Error accessing ZIP file {version.python_path} from B2 storage: {str(e)}")
# Fallback to local file system
version_str = f"v{version_no}"
zip_path = os.path.join(
settings.MEDIA_ROOT,
settings.PYTHON_STORAGE_PATH,
str(paperwork_id),
version_str,
"code.zip"
)
if not os.path.exists(zip_path):
raise Http404("ZIP file not found")
try:
with zipfile.ZipFile(zip_path, 'r') as z:
# Check if the file exists in the ZIP
if file_path not in z.namelist():
return Response({'error': 'File not found in ZIP archive'}, status=status.HTTP_404_NOT_FOUND)
# Determine content type based on file extension
file_extension = file_path.split('.')[-1].lower() if '.' in file_path else ''
content_type = 'text/plain'
is_binary = False
# Text-based files
if file_extension in ['py']:
content_type = 'text/x-python'
elif file_extension in ['ipynb']:
content_type = 'application/json'
# Image files
elif file_extension in ['png']:
content_type = 'image/png'
is_binary = True
elif file_extension in ['jpg', 'jpeg']:
content_type = 'image/jpeg'
is_binary = True
# Handle binary files (images)
if is_binary:
file_content = base64.b64encode(z.read(file_path)).decode('utf-8')
return Response({
'content': file_content,
'content_type': content_type,
'is_binary': True
})
else:
# Handle text files
file_content = z.read(file_path).decode('utf-8', errors='replace')
return Response({
'content': file_content,
'content_type': content_type,
'is_binary': False
})
except Exception as e:
return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def download_paperwork_file(request, pk, version_no, file_type):
# Try token auth first
token = request.GET.get("token")
if token:
jwt_auth = JWTAuthentication()
try:
validated_token = jwt_auth.get_validated_token(token)
user = jwt_auth.get_user(validated_token)
request.user = user
except Exception:
raise AuthenticationFailed("Invalid token")
if not request.user or not request.user.is_authenticated:
return Response({"detail": "Authentication credentials were not provided."}, status=401)
paperwork = get_object_or_404(PaperWork, pk=pk)
version = get_object_or_404(paperwork.versions, version_no=version_no)
# Map file_type string to the correct model field
path_map = {
"pdf": getattr(version, "pdf_path", None),
"docx": getattr(version, "docx_path", None),
"tex": getattr(version, "latex_path", None),
"python": getattr(version, "python_path", None),
"zip": getattr(version, "zip_path", None),
}
rel_path = path_map.get(file_type)
if not rel_path:
return HttpResponseNotFound(f"Unsupported file type: {file_type}")
# Build absolute path
file_path = os.path.join(settings.MEDIA_ROOT, rel_path)
if not os.path.exists(file_path):
return HttpResponseNotFound("File not found on disk")
response = FileResponse(open(file_path, "rb"), content_type="application/octet-stream")
response["Content-Disposition"] = f"attachment; filename={os.path.basename(file_path)}"
return response