Djangoallauth社交帐户登录时连接到现有帐户

2024-04-27 03:04:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个自定义的用户模型,我使用django allauth进行社会注册和登录。 当用户使用已使用电子邮件注册的社交帐户登录时,我正在尝试将现有用户连接到新的社交帐户。我找到这个link

def pre_social_login(self, request, sociallogin):
    user = sociallogin.account.user
    if user.id:
        return
    try:
        customer = Customer.objects.get(email=user.email)
    except Customer.DoesNotExist:
        pass
    else:
        perform_login(request, customer, 'none')

但当我试图通过社交帐户登录时,我遇到了一个错误。

RelatedObjectDoesNotExist at /accounts/facebook/login/callback/
SocialAccount has no user.

任何帮助都将不胜感激。

我也知道这里面的安全问题。但我还是想试试这个。


Tags: django用户模型电子邮件emailrequestlogin帐户
2条回答

我找到了下面的解决方案here,它还检查电子邮件地址是否已验证。

from allauth.account.models import EmailAddress

def pre_social_login(self, request, sociallogin):

        # social account already exists, so this is just a login
        if sociallogin.is_existing:
            return

        # some social logins don't have an email address
        if not sociallogin.email_addresses:
            return

        # find the first verified email that we get from this sociallogin
        verified_email = None
        for email in sociallogin.email_addresses:
            if email.verified:
                verified_email = email
                break

        # no verified emails found, nothing more to do
        if not verified_email:
            return

        # check if given email address already exists as a verified email on
        # an existing user's account
        try:
            existing_email = EmailAddress.objects.get(email__iexact=email.email, verified=True)
        except EmailAddress.DoesNotExist:
            return

        # if it does, connect this new social login to the existing user
        sociallogin.connect(request, existing_email.user)

如果您更愿意跳过验证步骤,我认为此解决方案更好:

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

我通过稍微更改适配器的代码来实现这一点。

适配器.py

from allauth.socialaccount.adapter import DefaultSocialAccountAdapter

class MySocialAccountAdapter(DefaultSocialAccountAdapter):
    def pre_social_login(self, request, sociallogin): 
        user = sociallogin.user
        if user.id:  
            return          
        try:
            customer = Customer.objects.get(email=user.email)  # if user exists, connect the account to the existing account and login
            sociallogin.state['process'] = 'connect'                
            perform_login(request, customer, 'none')
        except Customer.DoesNotExist:
            pass

如果子类化DefaultSocialAccountAdapter,我们必须在settings.py文件中指定SOCIALACCOUNT_ADAPTER = 'myapp.my_adapter.MySocialAccountAdapter'

相关问题 更多 >