I have some code found elsewhere on SO to get django-rest-auth
to work with social login when there is an existing email account:
def pre_social_login(self, request, sociallogin):
"""
Invoked just after a user successfully authenticates via a
social provider, but before the login is actually processed
(and before the pre_social_login signal is emitted).
We're trying to solve different use cases:
- social account already exists, just go on
- social account has no email or email is unknown, just go on
- social account's email exists, link social account to existing user
"""
# Ignore existing social accounts, just do this stuff for new ones
if sociallogin.is_existing:
return
# some social logins don't have an email address, e.g. facebook accounts
# with mobile numbers only, but allauth takes care of this case so just
# ignore it
if 'email' not in sociallogin.account.extra_data:
return
# check if given email address already exists.
# Note: __iexact is used to ignore cases
try:
email = sociallogin.account.extra_data['email'].lower()
id = sociallogin.account.extra_data['id']
email_address = EmailAddress.objects.get(email__iexact=email)
# if it does not, let allauth take care of this new social account
except EmailAddress.DoesNotExist:
return
# if it does, connect this new social login to the existing user
user = email_address.user
profile = Profile.objects.get(email__iexact=email)
url = "http://graph.facebook.com/{}/picture?type=normal".format(id)
profile.media_url = url
profile.save() # suppose to persist to db, but isn't!!!
sociallogin.connect(request, user)
In the last few lines there before connecting the accounts, I get the profile pic of the FB account and try to save it to the database. For the life of me, I can't understand why it won't save the url. If I do the same commands using django shell, it saves with no problem. The media_url
field is a URLField
if that helps.