Skip to content

fix: email validation to remove unnecessary verification check#680

Open
Mohmmde1 wants to merge 2 commits into
iMerica:masterfrom
Mohmmde1:fix-email-validation
Open

fix: email validation to remove unnecessary verification check#680
Mohmmde1 wants to merge 2 commits into
iMerica:masterfrom
Mohmmde1:fix-email-validation

Conversation

@Mohmmde1

@Mohmmde1 Mohmmde1 commented Feb 23, 2025

Copy link
Copy Markdown

Pull Request Description

Issue Summary

The current behavior of dj-rest-auth raises a database-level unique constraint error when a user tries to register using an email that already exists but is not verified, especially when EMAIL_VERIFICATION is set to MANDATORY.

Why does this happen?
  1. The RegisterSerializer checks for email uniqueness but does not properly handle unverified emails.
  2. If an email exists but is not verified, it still passes validation.
  3. When user.save() is called, Django raises an IntegrityError due to the unique constraint on the email field in the User model.

Error Example

If a user attempts to register with an existing, unverified email, the system throws this error:

IntegrityError: UNIQUE constraint failed: auth_user.email

This results in unexpected registration failures instead of properly informing the user about the issue.


Proposed Solution

Instead of allowing the process to reach user.save() and fail due to the IntegrityError, we handle it earlier in validate_email().

  • If the email is verified, registration is blocked with a clear error message.
  • If the email exists but is unverified and EMAIL_VERIFICATION is MANDATORY, we prevent registration with an appropriate message.
  • If EMAIL_VERIFICATION is not mandatory, we allow registration to proceed.

Updated Code Implementation

from allauth.account.adapter import get_adapter
from allauth.account import app_settings as allauth_account_settings
from allauth.account.models import EmailAddress
from dj_rest_auth.registration.serializers import RegisterSerializer
from rest_framework import serializers

class CustomRegisterSerializer(RegisterSerializer):
    def validate_email(self, email):
        """Custom email validation to prevent unique constraint errors on unverified emails."""
        email = get_adapter().clean_email(email)
        if allauth_account_settings.UNIQUE_EMAIL:
            existing_email = EmailAddress.objects.filter(email=email).first()
            if existing_email:
                if not existing_email.verified and allauth_account_settings.EMAIL_VERIFICATION == \
                    allauth_account_settings.EmailVerificationMethod.MANDATORY:
                    raise serializers.ValidationError(
                        "This email is already in use but has not been verified."
                    )
                else:
                    raise serializers.ValidationError(
                        "A user is already registered with this email address."
                    )
        return email

Why This Fix Works?

  • Prevents the unique constraint error by handling the issue before user.save().
  • Provides clearer error messages to the user, improving user experience.
  • Respects the EMAIL_VERIFICATION setting, ensuring correct behavior based on project requirements.
  • Maintains email uniqueness while properly handling unverified email addresses.

This update ensures that users understand why they cannot register with a certain email and avoids unexpected system errors.

@Mohmmde1 Mohmmde1 force-pushed the fix-email-validation branch from be05ee3 to 56deb39 Compare February 27, 2025 16:57
- Remove unnecessary verification check.
- Allow registration with unverified email when verification is not mandatory.
- Prevent unique constraint errors by handling unverified emails properly.

Updated the `validate_email` method in `CustomRegisterSerializer` to:
- Allow registration if the email exists but is unverified, **only if verification is not mandatory**.
- Prevent duplicate registrations if the email is already verified.
- Improve error messages for better clarity.

This ensures smoother registration flows while maintaining email uniqueness where required.
@Mohmmde1 Mohmmde1 force-pushed the fix-email-validation branch from 56deb39 to 9e44117 Compare February 27, 2025 17:00
@stabldev

stabldev commented Mar 7, 2025

Copy link
Copy Markdown

@iMerica any update on this?

)
raise serializers.ValidationError(
_('A user is already registered with this e-mail address.'),
_('A user is already registered with this email address.')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great change but change in this message from e-mail to email will break the existing translations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants