dj-rest-auth icon indicating copy to clipboard operation
dj-rest-auth copied to clipboard

Registration with existing email address raises Integrity exception

Open mahdianyoones opened this issue 1 year ago • 2 comments

Hi. Thanks for the great app!

It appears that the registration endpoint does not check for existing email address. The following exception is raised:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_user_email_key"
DETAIL:  Key (email)=(mah***@gmail.com) already exists.

This can be fixed via altering the create endpoint like this.

        try:
            user = self.perform_create(serializer)
        except django.db.utils.IntegrityError:
            return Response(status=status.HTTP_400_BAD_REQUEST)

Am I missing something or this is really an issue?

mahdianyoones avatar Sep 28 '23 11:09 mahdianyoones

I also encountered this error and it seems it's because in the registration serializer, the validate_email function checks whether the email exists AND is verified, however it doesn't handle the issue where the email exists but is not verified.

You can override the serializer:

from allauth.account.adapter import get_adapter
from allauth.account.models import EmailAddress
from dj_rest_auth.registration.serializers import RegisterSerializer
from django.conf import settings
from rest_framework import serializers

class UserRegistrationSerializer(RegisterSerializer):
    def validate_email(self, email):
        email = get_adapter().clean_email(email)
        if settings.ACCOUNT_UNIQUE_EMAIL:
            if email and EmailAddress.objects.filter(email__iexact=email).exists():
                raise serializers.ValidationError(
                    'A user is already registered with this e-mail address.',
                )
        return email

and then add it in settings.py:

REST_AUTH = {
     ...
    'REGISTER_SERIALIZER': 'your_module_name.serializers.UserRegistrationSerializer'
}

I think the default behaviour should be to only filter by email, and if a not verified email is used to register, just send a verification email.

MatejMijoski avatar Sep 29 '23 10:09 MatejMijoski

it's because in the registration serializer, the validate_email function checks whether the email exists AND is verified, however it doesn't handle the issue where the email exists but is not verified.

That is exactly the case. Thank you for providing a quick fix.

I think we can probably call it a bug as the case of the email existing but is not verified should be gracefully handled instead of code breaking.

hassan404 avatar May 10 '24 12:05 hassan404