[Django]-Django-rest-auth – Facebook social login raises unique constraint violation for existing email

5πŸ‘

I solved the issue by creating a social adapter that connects the existing account to the social account.
Please make sure you’re aware of the risks before using it – if the email address is not verified in one of the accounts a malicious user might take control of the account by signing up before the social signup (for example).

class MySocialAccountAdapter(DefaultSocialAccountAdapter):
    def pre_social_login(self, request, sociallogin):

        user = sociallogin.user
        if user.id:
            return
        if not user.email:
            return

        try:
            user = User.objects.get(email=user.email)  # if user exists, connect the account to the existing account and login
            sociallogin.connect(request, user)
        except User.DoesNotExist:
            pass
        except Exception as e:
            logger.exception('Social adapter failure - {}'.format(e))

You need to set the path to the adapter in the settings.py:

SOCIALACCOUNT_ADAPTER = 'path.to.MySocialAccountAdapter'
πŸ‘€Rani

2πŸ‘

The latest version of django-rest-auth v0.9.3 now includes social connect views, which allow you to link existing account to a social account.

In order to use them you need to be authenticated via existing account, due to security issues outlined in the previous answer. More info in the docs: Additional Social Connect Views

Unique constraint 500 error is fixed as well.

Leave a comment