Noel-Teens commited on
Commit
85ff68e
·
1 Parent(s): a2bc5f2

feat(invitation): add role choices and enhance invitation validation and logging

Browse files

- Define ROLE_CHOICES for Invitation model and enforce role field constraints
- Add validate_role and validate_email methods to InvitationSerializer
- Normalize and validate email input for invitations
- Improve invite_user view with detailed logging and validation error handling
- Detect and log attempts to invite existing users
- Log creation and update of invitations and success of email sending
- Set default FRONTEND_URL in settings with fallback for local development

admin_app/models.py CHANGED
@@ -31,8 +31,13 @@ class PaperWork(models.Model):
31
 
32
 
33
  class Invitation(models.Model):
 
 
 
 
 
34
  email = models.EmailField(unique=True)
35
- role = models.CharField(max_length=50, default="RESEARCHER")
36
  token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
37
  invited_by = models.ForeignKey(
38
  settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name="sent_invitations"
 
31
 
32
 
33
  class Invitation(models.Model):
34
+ ROLE_CHOICES = (
35
+ ('ADMIN', 'Admin'),
36
+ ('RESEARCHER', 'Researcher'),
37
+ )
38
+
39
  email = models.EmailField(unique=True)
40
+ role = models.CharField(max_length=50, choices=ROLE_CHOICES, default="RESEARCHER")
41
  token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
42
  invited_by = models.ForeignKey(
43
  settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name="sent_invitations"
admin_app/serializers.py CHANGED
@@ -32,6 +32,19 @@ class InvitationSerializer(serializers.ModelSerializer):
32
  class Meta:
33
  model = Invitation
34
  fields = ("email", "role")
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
 
37
  class AcceptInvitationSerializer(serializers.Serializer):
 
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"""
38
+ valid_roles = [choice[0] for choice in Invitation.ROLE_CHOICES]
39
+ if value not in valid_roles:
40
+ raise serializers.ValidationError(f"Invalid role. Must be one of: {', '.join(valid_roles)}")
41
+ return value
42
+
43
+ def validate_email(self, value):
44
+ """Validate that the email is properly formatted and not empty"""
45
+ if not value or not value.strip():
46
+ raise serializers.ValidationError("Email cannot be empty")
47
+ return value.strip().lower()
48
 
49
 
50
  class AcceptInvitationSerializer(serializers.Serializer):
admin_app/views.py CHANGED
@@ -114,14 +114,22 @@ def _send_invite_email(email: str, invite_link: str, inviter: str = None):
114
  @permission_classes([IsAuthenticated, IsAdmin])
115
  def invite_user(request):
116
  """Admin endpoint to create Invitation and send email"""
 
 
 
117
  serializer = InvitationSerializer(data=request.data)
118
- serializer.is_valid(raise_exception=True)
 
 
119
 
120
  email = serializer.validated_data["email"].lower()
121
  role = serializer.validated_data.get("role", "RESEARCHER")
 
 
122
 
123
  # Prevent inviting an email that already has a user
124
  if User.objects.filter(email__iexact=email).exists():
 
125
  return Response({"error": "A user with this email already exists."}, status=status.HTTP_400_BAD_REQUEST)
126
 
127
  # If there's an existing pending invite, update it
@@ -136,12 +144,16 @@ def invite_user(request):
136
  invitation.invited_by = request.user
137
  invitation.is_accepted = False
138
  invitation.save()
 
 
 
139
 
140
  invite_link = _build_invite_link(invitation.token)
141
 
142
  # Send email with error handling
143
  try:
144
  _send_invite_email(email, invite_link, inviter=getattr(request.user, "username", None))
 
145
  return Response({"message": "Invitation sent successfully."}, status=status.HTTP_201_CREATED)
146
  except Exception as e:
147
  # If email fails, we should clean up the invitation or mark it as failed
 
114
  @permission_classes([IsAuthenticated, IsAdmin])
115
  def invite_user(request):
116
  """Admin endpoint to create Invitation and send email"""
117
+ logger.info(f"Invite user request from {request.user.username} ({request.user.role})")
118
+ logger.info(f"Request data: {request.data}")
119
+
120
  serializer = InvitationSerializer(data=request.data)
121
+ if not serializer.is_valid():
122
+ logger.error(f"Serializer validation failed: {serializer.errors}")
123
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
124
 
125
  email = serializer.validated_data["email"].lower()
126
  role = serializer.validated_data.get("role", "RESEARCHER")
127
+
128
+ logger.info(f"Processing invitation for {email} with role {role}")
129
 
130
  # Prevent inviting an email that already has a user
131
  if User.objects.filter(email__iexact=email).exists():
132
+ logger.warning(f"Attempted to invite existing user: {email}")
133
  return Response({"error": "A user with this email already exists."}, status=status.HTTP_400_BAD_REQUEST)
134
 
135
  # If there's an existing pending invite, update it
 
144
  invitation.invited_by = request.user
145
  invitation.is_accepted = False
146
  invitation.save()
147
+ logger.info(f"Updated existing invitation for {email}")
148
+ else:
149
+ logger.info(f"Created new invitation for {email}")
150
 
151
  invite_link = _build_invite_link(invitation.token)
152
 
153
  # Send email with error handling
154
  try:
155
  _send_invite_email(email, invite_link, inviter=getattr(request.user, "username", None))
156
+ logger.info(f"Successfully sent invitation email to {email}")
157
  return Response({"message": "Invitation sent successfully."}, status=status.HTTP_201_CREATED)
158
  except Exception as e:
159
  # If email fails, we should clean up the invitation or mark it as failed
pms_server/settings.py CHANGED
@@ -325,4 +325,5 @@ CORS_ALLOW_PRIVATE_NETWORK = True
325
 
326
  APPEND_SLASH=False
327
 
328
- FRONTEND_URL = os.environ.get("FRONTEND_URL")
 
 
325
 
326
  APPEND_SLASH=False
327
 
328
+ # Frontend URL for invitation links
329
+ FRONTEND_URL = os.getenv("FRONTEND_URL", "http://localhost:3000")