Skip to content

Commit

Permalink
fix(socialaccount): Pass email to populate_user()
Browse files Browse the repository at this point in the history
  • Loading branch information
pennersr committed Aug 29, 2024
1 parent 7e99f3e commit 58db2be
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
14 changes: 12 additions & 2 deletions allauth/socialaccount/providers/base/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,13 @@ def sociallogin_from_response(self, request, response):
provider=self.sub_id,
)
email_addresses = self.extract_email_addresses(response)
self.cleanup_email_addresses(
email = self.cleanup_email_addresses(
common_fields.get("email"),
email_addresses,
email_verified=common_fields.get("email_verified"),
)
if email:
common_fields["email"] = email
sociallogin = SocialLogin(
account=socialaccount, email_addresses=email_addresses
)
Expand Down Expand Up @@ -165,7 +167,9 @@ def extract_common_fields(self, data):
"""
return {}

def cleanup_email_addresses(self, email, addresses, email_verified=False):
def cleanup_email_addresses(
self, email: Optional[str], addresses: list, email_verified: bool = False
) -> Optional[str]:
# Avoid loading models before adapters have been registered.
from allauth.account.models import EmailAddress

Expand All @@ -181,6 +185,12 @@ def cleanup_email_addresses(self, email, addresses, email_verified=False):
if adapter.is_email_verified(self, address.email):
address.verified = True

# Sort in order of importance (primary, verified...)
addresses.sort(key=lambda a: (a.primary, a.verified, a.email), reverse=True)
if not email and addresses:
email = addresses[0].email
return email

def extract_email_addresses(self, data):
"""
For example:
Expand Down
9 changes: 8 additions & 1 deletion allauth/socialaccount/providers/github/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from unittest.mock import patch

from allauth.account.models import EmailAddress
from allauth.socialaccount.models import SocialAccount
from allauth.socialaccount.tests import OAuth2TestsMixin
Expand Down Expand Up @@ -95,7 +97,12 @@ def test_account_name_null(self):
""",
),
]
self.login(mocks)
with patch(
"allauth.socialaccount.adapter.DefaultSocialAccountAdapter.populate_user"
) as populate_mock:
self.login(mocks)
populate_data = populate_mock.call_args[0][2]
assert populate_data["email"] == "octocat@github.com"
socialaccount = SocialAccount.objects.get(uid="201022")
self.assertIsNone(socialaccount.extra_data.get("name"))
account = socialaccount.get_provider_account()
Expand Down

0 comments on commit 58db2be

Please sign in to comment.