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 ') # 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