Skip to content

Fix social login under database constraints#553

Merged
iMerica merged 1 commit into
iMerica:masterfrom
c-w:fix-case-insensitive-email
Oct 27, 2023
Merged

Fix social login under database constraints#553
iMerica merged 1 commit into
iMerica:masterfrom
c-w:fix-case-insensitive-email

Conversation

@c-w

@c-w c-w commented Sep 28, 2023

Copy link
Copy Markdown
Contributor

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 🙌

@iMerica iMerica merged commit e58c970 into iMerica:master Oct 27, 2023
@c-w c-w deleted the fix-case-insensitive-email branch October 27, 2023 18:12
@c-w

c-w commented Oct 27, 2023

Copy link
Copy Markdown
Contributor Author

Thanks for the merge 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants