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

Fix social login under database constraints #553

Closed c-w closed 8 months ago

c-w commented 9 months ago

It's a common practice to model the user email as case insensitive by adding a unique constraint on the email field using something similar to the snippet below (as a matter of fact, allauth already models the EmailAddress as case-insensitive by using email__iexact everywhere for lookup).

# example of user model with case insensitive email
class User(AbstractUser):
    class Meta(AbstractUser.Meta):
        constraints = [
            models.UniqueConstraint(
                Upper("email"),
                name="user_email_unique_index",
            ),
        ]

In the case insensitive scenario, dj-rest-auth currently crashes during social signup with an integrity error as the account existence check (see snippet below) doesn't consider a case insensitive scenario.

# current existence check: doesn't consider case sensitivity
account_exists = get_user_model().objects.filter(
    email=login.user.email,
).exists()

More generally, the current approach also has a race condition where we will crash with an integrity error if the existence check is still running while another request logs in with the same email address.

To solve the issues outlined above, this PR proposes to add an additional check around the login save method to catch the integrity error: if such an error occurs, we failed to save the user thus the user must be a duplicate.

More generally, I opened this pull request to draw attention to the described issues. I'm not particularly wedded to this implementation but I'd like to open a discussion about how to best address this scenario and work on the best fix together. For example, an alternative implementation could factor out the email existence check into a method so that subclasses can override the logic to for example inject a case-insensitive check.

Looking forward to your inputs :raised_hands:

c-w commented 8 months ago

Thanks for the merge :raised_hands: