iMerica / dj-rest-auth

Authentication for Django Rest Framework
https://dj-rest-auth.readthedocs.io/en/latest/index.html
MIT License
1.68k stars 315 forks source link

Registration with existing email address raises Integrity exception #552

Open mahdianyoones opened 1 year ago

mahdianyoones commented 1 year ago

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?

MatejMijoski commented 1 year ago

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.

hassan404 commented 6 months ago

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.

gabn88 commented 1 week ago

This is a bug and the fix is okay. But to be compatible with django-allauth we should do something like:

    def clean_email(self):
        value = self.cleaned_data["email"].lower()
        value = get_adapter().clean_email(value)
        if value and app_settings.UNIQUE_EMAIL:
            value = self.validate_unique_email(value)
        return value

    def validate_unique_email(self, value):
        adapter = get_adapter()
        assessment = flows.manage_email.assess_unique_email(value)
        if assessment is True:
            # All good.
            pass
        elif assessment is False:
            # Fail right away.
            raise adapter.validation_error("email_taken")
        else:
            assert assessment is None
            self.account_already_exists = True
        return adapter.validate_unique_email(value)

(taken from the BaseSignupForm from django-allauth)