django-allauth:如果社交帐户存在,则在登录时重定向到注册页面

问题描述 投票:0回答:1

我想在我的 Django 项目中创建一个 Google Login 身份验证方法。因此,当用户第一次访问我的网站时,它将在我的数据库中创建一个新用户,然后登录该用户。如果使用此电子邮件地址的用户已经存在,该用户只需登录即可。

我的目标的第一部分按预期工作(当用户第一次访问我的网站时,它将在我的数据库中创建一个新用户,然后登录该用户),但是如果我尝试以现有用户身份登录用户,django-allauth 将我重定向到

/accounts/social/signup/

我尝试使用 CustomSocialAccountAdapter 修复它,但它并没有真正帮助我。 您能帮我解决我的问题吗?

这是我的

settings.py

# allauth
AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "APP": {
            "client_id": os.environ.get("GOOGLE_CLIENT_ID", ""),
            "secret": os.environ.get("GOOGLE_CLIENT_SECRET", ""),
        },
        "SCOPE": [
            "profile",
            "email",
        ],
        "AUTH_PARAMS": {
            "access_type": "offline",
        },
    },
}
ACCOUNT_LOGIN_REDIRECT_URL = "home"
ACCOUNT_LOGOUT_REDIRECT_URL = "home"
SOCIALACCOUNT_LOGIN_ON_GET = True
SOCIALACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
SOCIALACCOUNT_AUTO_SIGNUP = True
ACCOUNT_LOGOUT_ON_GET = True
SOCIALACCOUNT_ADAPTER = "user.adapters.CustomSocialAccountAdapter"

我的

adapters.py

class CustomSocialAccountAdapter(DefaultSocialAccountAdapter):
    def pre_social_login(self, request, sociallogin):
        user = sociallogin.user
        if not CustomUser.objects.filter(email=user.email).exists():
            extra_data = sociallogin.account.extra_data
            user.first_name = extra_data.get('given_name')
            user.last_name = extra_data.get('family_name')
            user.is_active = True
            user.save()

        else:
            perform_login(request, user, 'none')

        return super().pre_social_login(request, sociallogin)

我的 HTML 代码:

<a
  class="login-social__link"
  href="{% provider_login_url 'google' process='login' method='oauth2'>
  <svg class="login__icon login-google">
  <use
      xlink:href="{% static 'images/sprite-icons.svg' %}#icon-google"
  ></use>
  </svg>
</a>
django django-models django-views django-forms django-templates
1个回答
0
投票

您尝试过 ChatGPT 或文档吗?

© www.soinside.com 2019 - 2024. All rights reserved.