检查当前用户是否使用任何Django社交认证提供程序登录

8
我想检查用户是否通过社交认证或使用django默认身份验证登录。
类似于
如果用户.social_auth = true?

很长时间没有可行的答案了... - Andrew Polukhin
7个回答

4

经过一些研究,我想到了这个解决方案,可以确保用户是否使用任何社交提供程序或仅使用默认的Django身份验证进行身份验证。请在此处查看更多信息..

 {% if user.is_authenticated and not backends.associated %}

 #Do or show something if user is not authenticated with social provider but default auth

 {% elif user.is_authenticated and backends.associated %}

  #Do or show something if user is authenticated with social provider

 {% else %}

 #Do or show something if none of both

 {% endif %}

嗨,谢谢回复。我明天也会尝试这种方法。 - vinCi

2

我在搜索相关信息,解决方法是user.social_auth.exists(), 如果用户存在于数据库中,则返回True,否则返回false。


1

来自Python:

user.social_auth.exists()

如果用户是社交用户,将返回True,否则返回False

从模板中:

{% if not backends.associated %}
    <code if user is NOT social>
{% else %}
    <code if user is social>
{% endif %}

当你在Django项目的配置中包含python-social-auth应用程序时,backends上下文变量将自动设置在Django模板中。

1
from social_auth.models import UserSocialAuth

try:
    UserSocialAuth.objects.get(user_id=user.id)
except UserSocialAuth.DoesNotExist:
    print "user is logged in using the django default authentication"
else:
    print "user is logged in via social authentication"

您可能需要向用户模型添加一个方法。

0

目前,django-social-auth已被弃用。您可以使用python-social-auth代替。

在这种情况下,您应该使用:

user.social_auth.filter(provider='BACKEND_NAME')

例如,如果当前用户已通过Google帐户进行身份验证:
if user.is_authenticated:
    if user.social_auth.filter(provider='google-oauth2'):
        print 'user is using Google Account!'
    else:
        print 'user is using Django default authentication or another social provider'

0

我也遇到了与python-social-auth相同的问题,无法识别社交登录用户。我需要在导航栏中指定一个单独的标签页,让他们完成个人资料页面的编辑。当然,如果用户通过社交认证进行了登录,那么他\她在数据库中没有设置密码。因此,我使用has_usable_password()方法(django.contrib.auth)来解决这个问题。例如:

{% if user.has_usable_password %}
  <a class="dropdown-item" href="{% url 'password_change' %}">Change password</a>
{% elif not user.has_usable_password %}
  <a class="dropdown-item" href="{% url 'set_pass' %}">Set password</a>

很明显,只要用户没有设置密码,这个提示就会有帮助。

0

您可以从UserSocialAuth应用程序中按如下方式查询所有使用社交认证的用户:

from social_django.models import UserSocialAuth

if user in [u.user for u in UserSocialAuth.objects.all()]:
     #dosomething

请不要仅仅发布代码作为答案,还要提供解释您的代码是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Mark Rotteveel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接