iMerica / dj-rest-auth

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

Registration with existing email address raises Integrity exception #552

Open mahdianyoones opened 9 months ago

mahdianyoones commented 9 months 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 9 months 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 2 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.