Noel-Teens commited on
Commit
116dc2c
Β·
1 Parent(s): 6b6a264

implemented resend api

Browse files
admin_app/management/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Empty init file
admin_app/management/commands/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Empty init file
admin_app/management/commands/cleanup_invitations.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.core.management.base import BaseCommand
2
+ from django.utils import timezone
3
+ from admin_app.models import Invitation
4
+ from auth_app.models import User
5
+
6
+ class Command(BaseCommand):
7
+ help = 'Clean up duplicate and expired invitations'
8
+
9
+ def add_arguments(self, parser):
10
+ parser.add_argument(
11
+ '--dry-run',
12
+ action='store_true',
13
+ help='Show what would be cleaned up without making changes',
14
+ )
15
+ parser.add_argument(
16
+ '--delete-expired',
17
+ action='store_true',
18
+ help='Delete expired invitations (instead of just marking as accepted)',
19
+ )
20
+
21
+ def handle(self, *args, **options):
22
+ dry_run = options['dry_run']
23
+ delete_expired = options['delete_expired']
24
+
25
+ self.stdout.write(
26
+ self.style.SUCCESS('=== Invitation Cleanup Command ===')
27
+ )
28
+
29
+ if dry_run:
30
+ self.stdout.write(
31
+ self.style.WARNING('DRY RUN MODE - No changes will be made')
32
+ )
33
+
34
+ # Get all invitations
35
+ all_invitations = Invitation.objects.all().order_by('email', '-created_at')
36
+ self.stdout.write(f"Total invitations found: {all_invitations.count()}")
37
+
38
+ # Track emails and their invitations
39
+ email_groups = {}
40
+ for invitation in all_invitations:
41
+ email = invitation.email.lower()
42
+ if email not in email_groups:
43
+ email_groups[email] = []
44
+ email_groups[email].append(invitation)
45
+
46
+ deleted_count = 0
47
+ updated_count = 0
48
+
49
+ for email, invitations in email_groups.items():
50
+ # Check if user already exists
51
+ if User.objects.filter(email__iexact=email).exists():
52
+ self.stdout.write(f"πŸ”„ User exists for {email}, marking all invitations as accepted")
53
+ for invitation in invitations:
54
+ if not dry_run:
55
+ invitation.is_accepted = True
56
+ invitation.save()
57
+ updated_count += 1
58
+ continue
59
+
60
+ # If more than one invitation for same email
61
+ if len(invitations) > 1:
62
+ self.stdout.write(f"πŸ“§ Found {len(invitations)} invitations for {email}")
63
+
64
+ # Keep the most recent non-expired invitation
65
+ # Delete others
66
+ invitations.sort(key=lambda x: x.created_at, reverse=True)
67
+
68
+ keeper = None
69
+ for invitation in invitations:
70
+ if not invitation.is_expired() and not invitation.is_accepted:
71
+ keeper = invitation
72
+ break
73
+
74
+ if not keeper:
75
+ # All are expired/accepted, keep the most recent one
76
+ keeper = invitations[0]
77
+ self.stdout.write(f" πŸ“ All invitations expired/accepted, keeping most recent: {keeper.token}")
78
+ else:
79
+ self.stdout.write(f" βœ… Keeping active invitation: {keeper.token}")
80
+
81
+ # Delete the others
82
+ for invitation in invitations:
83
+ if invitation != keeper:
84
+ self.stdout.write(f" πŸ—‘οΈ Deleting duplicate: {invitation.token} (created: {invitation.created_at})")
85
+ if not dry_run:
86
+ invitation.delete()
87
+ deleted_count += 1
88
+
89
+ # Handle expired invitations if requested
90
+ elif delete_expired and len(invitations) == 1:
91
+ invitation = invitations[0]
92
+ if invitation.is_expired() and not invitation.is_accepted:
93
+ self.stdout.write(f"πŸ—‘οΈ Deleting expired invitation: {email}")
94
+ if not dry_run:
95
+ invitation.delete()
96
+ deleted_count += 1
97
+
98
+ self.stdout.write(
99
+ self.style.SUCCESS(f'\\nπŸ“Š Cleanup Summary:')
100
+ )
101
+ self.stdout.write(f" - Updated (marked as accepted): {updated_count}")
102
+ self.stdout.write(f" - Deleted (duplicates/expired): {deleted_count}")
103
+
104
+ if not dry_run:
105
+ remaining_count = Invitation.objects.count()
106
+ self.stdout.write(f" - Remaining invitations: {remaining_count}")
107
+
108
+ if dry_run:
109
+ self.stdout.write(
110
+ self.style.WARNING('\\nNo changes were made. Run without --dry-run to apply changes.')
111
+ )
admin_app/models.py CHANGED
@@ -45,6 +45,10 @@ class Invitation(models.Model):
45
  is_accepted = models.BooleanField(default=False)
46
  created_at = models.DateTimeField(auto_now_add=True)
47
  expires_at = models.DateTimeField(default=default_expiry)
 
 
 
 
48
 
49
  class Meta:
50
  ordering = ["-created_at"]
@@ -57,3 +61,46 @@ class Invitation(models.Model):
57
 
58
  def time_remaining(self):
59
  return max(self.expires_at - timezone.now(), timedelta(seconds=0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  is_accepted = models.BooleanField(default=False)
46
  created_at = models.DateTimeField(auto_now_add=True)
47
  expires_at = models.DateTimeField(default=default_expiry)
48
+ # Email sending tracking fields
49
+ email_attempts = models.PositiveIntegerField(default=0)
50
+ last_email_attempt = models.DateTimeField(null=True, blank=True)
51
+ email_sent_successfully = models.BooleanField(default=False)
52
 
53
  class Meta:
54
  ordering = ["-created_at"]
 
61
 
62
  def time_remaining(self):
63
  return max(self.expires_at - timezone.now(), timedelta(seconds=0))
64
+
65
+ def can_send_email(self, max_attempts=5):
66
+ """Check if we can send another email invitation.
67
+
68
+ Args:
69
+ max_attempts: Maximum number of email attempts allowed (default: 5)
70
+
71
+ Returns:
72
+ bool: True if another email can be sent, False otherwise
73
+ """
74
+ # If already accepted, no need to send more emails
75
+ if self.is_accepted:
76
+ return False
77
+
78
+ # If expired, no point in sending more emails
79
+ if self.is_expired():
80
+ return False
81
+
82
+ # Check if we haven't exceeded max attempts
83
+ if self.email_attempts >= max_attempts:
84
+ return False
85
+
86
+ # If email was sent successfully, don't send again unless it's been a while
87
+ # (you can adjust this logic based on your needs)
88
+ if self.email_sent_successfully and self.last_email_attempt:
89
+ # Only allow resending if it's been more than 1 hour since last successful send
90
+ time_since_last = timezone.now() - self.last_email_attempt
91
+ if time_since_last < timedelta(hours=1):
92
+ return False
93
+
94
+ return True
95
+
96
+ def record_email_attempt(self, success=False):
97
+ """Record an email sending attempt.
98
+
99
+ Args:
100
+ success: Whether the email was sent successfully
101
+ """
102
+ self.email_attempts += 1
103
+ self.last_email_attempt = timezone.now()
104
+ if success:
105
+ self.email_sent_successfully = True
106
+ self.save()
admin_app/serializers.py CHANGED
@@ -28,10 +28,10 @@ class PaperWorkDeadlineUpdateSerializer(serializers.ModelSerializer):
28
  fields = ['deadline']
29
 
30
 
31
- class InvitationSerializer(serializers.ModelSerializer):
32
- class Meta:
33
- model = Invitation
34
- fields = ("email", "role")
35
 
36
  def validate_role(self, value):
37
  """Validate that the role is one of the valid choices"""
 
28
  fields = ['deadline']
29
 
30
 
31
+ class InvitationSerializer(serializers.Serializer):
32
+ email = serializers.EmailField()
33
+ role = serializers.ChoiceField(choices=Invitation.ROLE_CHOICES, default="RESEARCHER")
34
+ force_resend = serializers.BooleanField(default=False, write_only=True)
35
 
36
  def validate_role(self, value):
37
  """Validate that the role is one of the valid choices"""
admin_app/urls.py CHANGED
@@ -11,6 +11,8 @@ urlpatterns = [
11
  path('invite/', views.invite_user, name='invite-user'),
12
  path('accept-invite/<uuid:token>/', views.accept_invite, name='accept-invite'),
13
  path('verify-invite/<uuid:token>/', views.verify_invite, name='verify-invite'),
 
 
14
 
15
  # Paperwork management
16
  path('paperworks/', views.assign_paperwork, name='assign_paperwork'),
 
11
  path('invite/', views.invite_user, name='invite-user'),
12
  path('accept-invite/<uuid:token>/', views.accept_invite, name='accept-invite'),
13
  path('verify-invite/<uuid:token>/', views.verify_invite, name='verify-invite'),
14
+ path('retry-invite/<uuid:token>/', views.retry_invitation, name='retry-invitation'),
15
+ path('pending-invitations/', views.pending_invitations, name='pending-invitations'),
16
 
17
  # Paperwork management
18
  path('paperworks/', views.assign_paperwork, name='assign_paperwork'),
admin_app/views.py CHANGED
@@ -78,7 +78,7 @@ def _send_invite_email(email: str, invite_link: str, inviter: str = None):
78
  if not api_key:
79
  raise Exception("RESEND_API_KEY not set in settings.")
80
 
81
- from_email = getattr(settings, 'FROM_EMAIL', 'PMS <noreply@neurostack.com>')
82
 
83
  # Resend API payload
84
  payload = {
@@ -119,7 +119,7 @@ def _send_invite_email(email: str, invite_link: str, inviter: str = None):
119
  @api_view(["POST"])
120
  @permission_classes([IsAuthenticated, IsAdmin])
121
  def invite_user(request):
122
- """Admin endpoint to create Invitation and send email"""
123
  logger.info(f"Invite user request from {request.user.username} ({request.user.role})")
124
  logger.info(f"Request data: {request.data}")
125
 
@@ -130,6 +130,7 @@ def invite_user(request):
130
 
131
  email = serializer.validated_data["email"].lower()
132
  role = serializer.validated_data.get("role", "RESEARCHER")
 
133
 
134
  logger.info(f"Processing invitation for {email} with role {role}")
135
 
@@ -138,39 +139,86 @@ def invite_user(request):
138
  logger.warning(f"Attempted to invite existing user: {email}")
139
  return Response({"error": "A user with this email already exists."}, status=status.HTTP_400_BAD_REQUEST)
140
 
141
- # If there's an existing pending invite, update it
142
- invitation, created = Invitation.objects.get_or_create(
143
- email=email,
144
- defaults={"role": role, "invited_by": request.user}
145
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  if not created:
147
- # Update expiry and role if you want
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  invitation.role = role
149
- invitation.expires_at = timezone.now() + timezone.timedelta(hours=48)
150
  invitation.invited_by = request.user
151
  invitation.is_accepted = False
 
 
 
 
 
152
  invitation.save()
153
- logger.info(f"Updated existing invitation for {email}")
154
  else:
155
  logger.info(f"Created new invitation for {email}")
156
 
157
  invite_link = _build_invite_link(invitation.token)
158
 
159
- # Send email with error handling
160
  try:
161
  _send_invite_email(email, invite_link, inviter=getattr(request.user, "username", None))
162
- logger.info(f"Successfully sent invitation email to {email}")
163
- return Response({"message": "Invitation sent successfully."}, status=status.HTTP_201_CREATED)
 
 
 
 
 
 
 
 
 
 
164
  except Exception as e:
165
- # If email fails, we should clean up the invitation or mark it as failed
166
- logger.error(f"Failed to send invitation email to {email}: {str(e)}")
167
- # Optionally delete the invitation if email failed
168
- if created:
169
- invitation.delete()
170
- return Response(
171
- {"error": "Failed to send invitation email. Please check the email address and try again."},
172
- status=status.HTTP_500_INTERNAL_SERVER_ERROR
173
- )
 
 
 
 
174
 
175
 
176
  @csrf_exempt
@@ -211,6 +259,95 @@ def accept_invite(request, token):
211
  return Response({"message": "User created successfully."}, status=status.HTTP_201_CREATED)
212
 
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  @api_view(["GET"])
215
  @permission_classes([AllowAny])
216
  def verify_invite(request, token):
 
78
  if not api_key:
79
  raise Exception("RESEND_API_KEY not set in settings.")
80
 
81
+ from_email = getattr(settings, 'FROM_EMAIL', 'PMS <onboarding@resend.dev>')
82
 
83
  # Resend API payload
84
  payload = {
 
119
  @api_view(["POST"])
120
  @permission_classes([IsAuthenticated, IsAdmin])
121
  def invite_user(request):
122
+ """Admin endpoint to create Invitation and send email with retry support"""
123
  logger.info(f"Invite user request from {request.user.username} ({request.user.role})")
124
  logger.info(f"Request data: {request.data}")
125
 
 
130
 
131
  email = serializer.validated_data["email"].lower()
132
  role = serializer.validated_data.get("role", "RESEARCHER")
133
+ force_resend = serializer.validated_data.get("force_resend", False)
134
 
135
  logger.info(f"Processing invitation for {email} with role {role}")
136
 
 
139
  logger.warning(f"Attempted to invite existing user: {email}")
140
  return Response({"error": "A user with this email already exists."}, status=status.HTTP_400_BAD_REQUEST)
141
 
142
+ # Handle existing invitations with retry logic
143
+ try:
144
+ invitation = Invitation.objects.get(email=email)
145
+ created = False
146
+
147
+ # If invitation was already accepted but user doesn't exist (data inconsistency), mark as not accepted
148
+ if invitation.is_accepted and not User.objects.filter(email__iexact=email).exists():
149
+ invitation.is_accepted = False
150
+ invitation.save()
151
+ logger.info(f"Reset accepted status for invitation {email} - user doesn't exist")
152
+
153
+ except Invitation.DoesNotExist:
154
+ invitation = Invitation.objects.create(
155
+ email=email,
156
+ role=role,
157
+ invited_by=request.user
158
+ )
159
+ created = True
160
+
161
  if not created:
162
+ # Check if we can send another email
163
+ if not force_resend and not invitation.can_send_email():
164
+ reason = "already accepted" if invitation.is_accepted else "expired" if invitation.is_expired() else "maximum attempts reached"
165
+ logger.warning(f"Cannot send invitation to {email}: {reason}")
166
+ return Response({
167
+ "error": f"Cannot send invitation: {reason}",
168
+ "details": {
169
+ "attempts": invitation.email_attempts,
170
+ "last_attempt": invitation.last_email_attempt,
171
+ "email_sent_successfully": invitation.email_sent_successfully,
172
+ "expires_at": invitation.expires_at,
173
+ "is_expired": invitation.is_expired()
174
+ }
175
+ }, status=status.HTTP_400_BAD_REQUEST)
176
+
177
+ # Update invitation details if needed
178
  invitation.role = role
 
179
  invitation.invited_by = request.user
180
  invitation.is_accepted = False
181
+
182
+ # Extend expiry if it's expired or about to expire
183
+ if invitation.is_expired() or invitation.time_remaining() < timezone.timedelta(hours=24):
184
+ invitation.expires_at = timezone.now() + timezone.timedelta(hours=48)
185
+
186
  invitation.save()
187
+ logger.info(f"Updated existing invitation for {email} (attempt #{invitation.email_attempts + 1})")
188
  else:
189
  logger.info(f"Created new invitation for {email}")
190
 
191
  invite_link = _build_invite_link(invitation.token)
192
 
193
+ # Send email with error handling and attempt tracking
194
  try:
195
  _send_invite_email(email, invite_link, inviter=getattr(request.user, "username", None))
196
+ invitation.record_email_attempt(success=True)
197
+ logger.info(f"Successfully sent invitation email to {email} (attempt #{invitation.email_attempts})")
198
+
199
+ return Response({
200
+ "message": "Invitation sent successfully.",
201
+ "details": {
202
+ "attempt_number": invitation.email_attempts,
203
+ "remaining_attempts": max(0, 5 - invitation.email_attempts),
204
+ "expires_at": invitation.expires_at
205
+ }
206
+ }, status=status.HTTP_201_CREATED)
207
+
208
  except Exception as e:
209
+ invitation.record_email_attempt(success=False)
210
+ logger.error(f"Failed to send invitation email to {email} (attempt #{invitation.email_attempts}): {str(e)}")
211
+
212
+ # Don't delete the invitation on failure - allow retries
213
+ return Response({
214
+ "error": "Failed to send invitation email. You can try again.",
215
+ "details": {
216
+ "attempt_number": invitation.email_attempts,
217
+ "remaining_attempts": max(0, 5 - invitation.email_attempts),
218
+ "can_retry": invitation.can_send_email(),
219
+ "error_message": str(e)
220
+ }
221
+ }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
222
 
223
 
224
  @csrf_exempt
 
259
  return Response({"message": "User created successfully."}, status=status.HTTP_201_CREATED)
260
 
261
 
262
+ @csrf_exempt
263
+ @api_view(["POST"])
264
+ @permission_classes([IsAuthenticated, IsAdmin])
265
+ def retry_invitation(request, token):
266
+ """Admin endpoint to retry sending an invitation email"""
267
+ try:
268
+ invitation = Invitation.objects.get(token=token, is_accepted=False)
269
+ except Invitation.DoesNotExist:
270
+ return Response({"error": "Invitation not found or already accepted."}, status=status.HTTP_404_NOT_FOUND)
271
+
272
+ logger.info(f"Retry invitation request for {invitation.email} from {request.user.username}")
273
+
274
+ # Check if we can send another email
275
+ if not invitation.can_send_email():
276
+ reason = "expired" if invitation.is_expired() else "maximum attempts reached"
277
+ logger.warning(f"Cannot retry invitation to {invitation.email}: {reason}")
278
+ return Response({
279
+ "error": f"Cannot retry invitation: {reason}",
280
+ "details": {
281
+ "attempts": invitation.email_attempts,
282
+ "last_attempt": invitation.last_email_attempt,
283
+ "email_sent_successfully": invitation.email_sent_successfully,
284
+ "expires_at": invitation.expires_at,
285
+ "is_expired": invitation.is_expired()
286
+ }
287
+ }, status=status.HTTP_400_BAD_REQUEST)
288
+
289
+ invite_link = _build_invite_link(invitation.token)
290
+
291
+ # Send email with error handling and attempt tracking
292
+ try:
293
+ _send_invite_email(invitation.email, invite_link, inviter=getattr(request.user, "username", None))
294
+ invitation.record_email_attempt(success=True)
295
+ logger.info(f"Successfully retried invitation email to {invitation.email} (attempt #{invitation.email_attempts})")
296
+
297
+ return Response({
298
+ "message": "Invitation retry sent successfully.",
299
+ "details": {
300
+ "attempt_number": invitation.email_attempts,
301
+ "remaining_attempts": max(0, 5 - invitation.email_attempts),
302
+ "expires_at": invitation.expires_at
303
+ }
304
+ }, status=status.HTTP_200_OK)
305
+
306
+ except Exception as e:
307
+ invitation.record_email_attempt(success=False)
308
+ logger.error(f"Failed to retry invitation email to {invitation.email} (attempt #{invitation.email_attempts}): {str(e)}")
309
+
310
+ return Response({
311
+ "error": "Failed to retry invitation email.",
312
+ "details": {
313
+ "attempt_number": invitation.email_attempts,
314
+ "remaining_attempts": max(0, 5 - invitation.email_attempts),
315
+ "can_retry": invitation.can_send_email(),
316
+ "error_message": str(e)
317
+ }
318
+ }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
319
+
320
+
321
+ @api_view(["GET"])
322
+ @permission_classes([IsAuthenticated, IsAdmin])
323
+ def pending_invitations(request):
324
+ """Admin endpoint to list all pending invitations with retry status"""
325
+ invitations = Invitation.objects.filter(is_accepted=False).order_by('-created_at')
326
+
327
+ invitation_data = []
328
+ for invitation in invitations:
329
+ invitation_data.append({
330
+ "token": str(invitation.token),
331
+ "email": invitation.email,
332
+ "role": invitation.role,
333
+ "invited_by": invitation.invited_by.username if invitation.invited_by else None,
334
+ "created_at": invitation.created_at,
335
+ "expires_at": invitation.expires_at,
336
+ "is_expired": invitation.is_expired(),
337
+ "time_remaining": str(invitation.time_remaining()),
338
+ "email_attempts": invitation.email_attempts,
339
+ "last_email_attempt": invitation.last_email_attempt,
340
+ "email_sent_successfully": invitation.email_sent_successfully,
341
+ "can_retry": invitation.can_send_email(),
342
+ "remaining_attempts": max(0, 5 - invitation.email_attempts)
343
+ })
344
+
345
+ return Response({
346
+ "invitations": invitation_data,
347
+ "total_count": len(invitation_data)
348
+ })
349
+
350
+
351
  @api_view(["GET"])
352
  @permission_classes([AllowAny])
353
  def verify_invite(request, token):
debug_ssl.py DELETED
@@ -1,155 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- SSL Connection Debugging Script for Aiven MySQL
4
- This script helps debug SSL connection issues with PyMySQL and Aiven
5
- """
6
- import os
7
- import sys
8
- import tempfile
9
- from dotenv import load_dotenv
10
-
11
- # Load environment variables
12
- load_dotenv()
13
-
14
- def test_ssl_configurations():
15
- """Test different SSL configurations to find what works"""
16
-
17
- print("=" * 60)
18
- print("SSL Connection Debugging for Aiven MySQL")
19
- print("=" * 60)
20
-
21
- # Get connection parameters
22
- db_config = {
23
- 'host': os.getenv('AIVEN_DB_HOST'),
24
- 'user': os.getenv('AIVEN_DB_USER'),
25
- 'password': os.getenv('AIVEN_DB_PASSWORD'),
26
- 'database': os.getenv('AIVEN_DB_NAME'),
27
- 'port': int(os.getenv('AIVEN_DB_PORT', '16000'))
28
- }
29
-
30
- # Check if all required parameters are present
31
- missing = [k for k, v in db_config.items() if not v]
32
- if missing:
33
- print(f"❌ Missing required parameters: {missing}")
34
- return
35
-
36
- print(f"βœ… Connection parameters loaded:")
37
- print(f" Host: {db_config['host']}")
38
- print(f" Database: {db_config['database']}")
39
- print(f" Port: {db_config['port']}")
40
- print()
41
-
42
- try:
43
- import pymysql
44
- print("βœ… PyMySQL imported successfully")
45
- except ImportError as e:
46
- print(f"❌ Failed to import PyMySQL: {e}")
47
- return
48
-
49
- # Test configurations
50
- test_configs = [
51
- {
52
- "name": "No SSL",
53
- "ssl": None
54
- },
55
- {
56
- "name": "Basic SSL (no verification)",
57
- "ssl": {
58
- 'ssl': True,
59
- 'ssl_verify_cert': False,
60
- 'ssl_verify_identity': False
61
- }
62
- },
63
- {
64
- "name": "SSL with disabled verification",
65
- "ssl": {
66
- 'ssl_disabled': False,
67
- 'ssl_verify_cert': False,
68
- 'ssl_verify_identity': False
69
- }
70
- },
71
- {
72
- "name": "Minimal SSL",
73
- "ssl": {'ssl': {}}
74
- }
75
- ]
76
-
77
- # Add certificate-based config if certificate is available
78
- cert_content = os.getenv('AIVEN_CA_CERT')
79
- if cert_content:
80
- print(f"βœ… SSL Certificate found (length: {len(cert_content)} chars)")
81
-
82
- # Create temporary certificate file
83
- try:
84
- ca_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pem")
85
- ca_file.write(cert_content)
86
- ca_file.flush()
87
- ca_file.close()
88
-
89
- test_configs.append({
90
- "name": "SSL with CA certificate",
91
- "ssl": {
92
- 'ssl_ca': ca_file.name,
93
- 'ssl_verify_cert': False,
94
- 'ssl_verify_identity': False
95
- }
96
- })
97
- print(f"βœ… Temporary certificate file created: {ca_file.name}")
98
- except Exception as e:
99
- print(f"⚠️ Failed to create certificate file: {e}")
100
- else:
101
- print("⚠️ No SSL certificate found in AIVEN_CA_CERT")
102
-
103
- print()
104
-
105
- # Test each configuration
106
- for i, config in enumerate(test_configs, 1):
107
- print(f"Test {i}: {config['name']}")
108
- print("-" * 40)
109
-
110
- try:
111
- # Prepare connection parameters
112
- conn_params = db_config.copy()
113
- if config['ssl'] is not None:
114
- conn_params.update(config['ssl'])
115
-
116
- print(f"Connection params: {conn_params}")
117
-
118
- # Attempt connection
119
- connection = pymysql.connect(**conn_params)
120
-
121
- # Test query
122
- with connection.cursor() as cursor:
123
- cursor.execute("SELECT 1 as test")
124
- result = cursor.fetchone()
125
-
126
- connection.close()
127
-
128
- print(f"βœ… SUCCESS: {config['name']} works!")
129
- print(f" Query result: {result}")
130
-
131
- # If this works, show the Django configuration
132
- print(f"\n🎯 Django configuration for this setup:")
133
- if config['ssl']:
134
- print(f" OPTIONS: {config['ssl']}")
135
- else:
136
- print(f" OPTIONS: {{}}")
137
-
138
- print()
139
- break
140
-
141
- except Exception as e:
142
- print(f"❌ FAILED: {e}")
143
- print()
144
- continue
145
-
146
- else:
147
- print("❌ All SSL configurations failed!")
148
- print("\nπŸ”§ Troubleshooting suggestions:")
149
- print("1. Check if your IP is whitelisted in Aiven")
150
- print("2. Verify your database credentials")
151
- print("3. Check if the database service is running")
152
- print("4. Try connecting without SSL from a different client")
153
-
154
- if __name__ == "__main__":
155
- test_ssl_configurations()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ssl_debug_patch.py DELETED
@@ -1,34 +0,0 @@
1
- # Temporary SSL Disable Patch for Debugging
2
- #
3
- # This file provides a quick fix to disable SSL temporarily while we debug the certificate issue.
4
- #
5
- # INSTRUCTIONS:
6
- # 1. Copy the content below
7
- # 2. Replace the ssl_options section in your settings.py (around line 138-152)
8
- # 3. This will allow the application to start while we investigate the SSL certificate problem
9
- #
10
- # WARNING: This is NOT for production use - only for debugging!
11
-
12
- # Load from env
13
- AIVEN_CA_CERT = os.getenv("AIVEN_CA_CERT")
14
-
15
- # TEMPORARY FIX: Disable SSL for debugging
16
- # This allows the app to start while we investigate the certificate issue
17
- ssl_options = {
18
- "ssl_disabled": True
19
- }
20
-
21
- # TODO: Re-enable SSL once certificate issue is resolved
22
- # ssl_options = {}
23
- # if AIVEN_CA_CERT:
24
- # ca_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pem")
25
- # ca_file.write(AIVEN_CA_CERT.strip())
26
- # ca_file.flush()
27
- # ca_file.close()
28
- # ssl_options = {
29
- # "ssl_ca": ca_file.name,
30
- # "ssl_verify_cert": True,
31
- # "ssl_verify_identity": False
32
- # }
33
- # else:
34
- # ssl_options = {"ssl_disabled": True}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_bb_upload.py DELETED
@@ -1,89 +0,0 @@
1
- # Test script to check B2 storage configuration and force reinitialize storage
2
- import os
3
- import django
4
- from pathlib import Path
5
- from dotenv import load_dotenv
6
-
7
- # Load environment variables FIRST
8
- load_dotenv()
9
-
10
- # Set up Django environment
11
- os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pms_server.settings')
12
- django.setup()
13
-
14
- from django.conf import settings
15
- from django.core.files.storage import default_storage
16
- from django.core.files.base import ContentFile
17
-
18
- # Check if all B2 environment variables are loaded
19
- print("=== B2 Configuration Check ===")
20
- print(f"B2_KEY_ID: {'βœ…' if os.getenv('B2_KEY_ID') else '❌'} {os.getenv('B2_KEY_ID', 'NOT SET')}")
21
- print(f"B2_APP_KEY: {'βœ…' if os.getenv('B2_APP_KEY') else '❌'} {'***HIDDEN***' if os.getenv('B2_APP_KEY') else 'NOT SET'}")
22
- print(f"B2_BUCKET_NAME: {'βœ…' if os.getenv('B2_BUCKET_NAME') else '❌'} {os.getenv('B2_BUCKET_NAME', 'NOT SET')}")
23
- print(f"B2_ENDPOINT_URL: {'βœ…' if os.getenv('B2_ENDPOINT_URL') else '❌'} {os.getenv('B2_ENDPOINT_URL', 'NOT SET')}")
24
-
25
- # Check Django settings AWS variables
26
- print(f"\n=== Django AWS Settings ===")
27
- print(f"AWS_ACCESS_KEY_ID: {'βœ…' if settings.AWS_ACCESS_KEY_ID else '❌'} {settings.AWS_ACCESS_KEY_ID or 'NOT SET'}")
28
- print(f"AWS_SECRET_ACCESS_KEY: {'βœ…' if settings.AWS_SECRET_ACCESS_KEY else '❌'} {'***HIDDEN***' if settings.AWS_SECRET_ACCESS_KEY else 'NOT SET'}")
29
- print(f"AWS_STORAGE_BUCKET_NAME: {'βœ…' if settings.AWS_STORAGE_BUCKET_NAME else '❌'} {settings.AWS_STORAGE_BUCKET_NAME or 'NOT SET'}")
30
- print(f"AWS_S3_ENDPOINT_URL: {'βœ…' if settings.AWS_S3_ENDPOINT_URL else '❌'} {settings.AWS_S3_ENDPOINT_URL or 'NOT SET'}")
31
-
32
- print(f"\nDEFAULT_FILE_STORAGE: {settings.DEFAULT_FILE_STORAGE}")
33
- print(f"default_storage class: {default_storage.__class__.__name__}")
34
-
35
- # Direct S3 storage test
36
- try:
37
- from storages.backends.s3boto3 import S3Boto3Storage
38
-
39
- # Create S3 storage instance directly
40
- s3_storage = S3Boto3Storage()
41
- print(f"\n=== Direct S3 Storage Test ===")
42
- print(f"S3 storage class: {s3_storage.__class__.__name__}")
43
-
44
- test_content = ContentFile(b"Test file content for direct S3 upload")
45
- test_path = "test_files/direct_s3_test.txt"
46
-
47
- saved_path = s3_storage.save(test_path, test_content)
48
- print(f"βœ… File saved to: {saved_path}")
49
-
50
- if s3_storage.exists(saved_path):
51
- print(f"βœ… File exists in S3 storage")
52
- print(f"File URL: {s3_storage.url(saved_path)}")
53
-
54
- # Clean up test file
55
- s3_storage.delete(saved_path)
56
- print(f"βœ… Test file cleaned up")
57
- else:
58
- print(f"❌ File not found in S3 storage")
59
-
60
- except Exception as e:
61
- print(f"❌ Direct S3 storage test failed: {str(e)}")
62
- import traceback
63
- print(f"Full error: {traceback.format_exc()}")
64
-
65
- # Test with default_storage
66
- try:
67
- print(f"\n=== Testing with default_storage ===")
68
- print(f"default_storage class: {default_storage.__class__.__name__}")
69
-
70
- test_content2 = ContentFile(b"Test file content for default storage")
71
- test_path2 = "test_files/default_storage_test.txt"
72
-
73
- saved_path2 = default_storage.save(test_path2, test_content2)
74
- print(f"βœ… File saved to: {saved_path2}")
75
-
76
- if default_storage.exists(saved_path2):
77
- print(f"βœ… File exists in storage")
78
- print(f"File URL: {default_storage.url(saved_path2)}")
79
-
80
- # Clean up test file
81
- default_storage.delete(saved_path2)
82
- print(f"βœ… Test file cleaned up")
83
- else:
84
- print(f"❌ File not found in storage")
85
-
86
- except Exception as e:
87
- print(f"❌ Default storage test failed: {str(e)}")
88
- import traceback
89
- print(f"Full error: {traceback.format_exc()}")