检查当前用户是否使用任何django社交身份验证提供程序登录

时间:2014-11-12 03:58:43

标签: django django-socialauth python-social-auth

我想检查用户是通过社交身份验证还是使用django默认身份验证登录。

类似

如果user.social_auth = true?

7 个答案:

答案 0 :(得分:2)

在做了一些研究之后,我想出了这个解决方案,以确保用户是使用任何社交提供商进行身份验证还是仅使用默认的django身份验证。点击此处查看moreinfo..

 {% 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 %}

答案 1 :(得分: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"

您可以向用户模型添加方法。

答案 2 :(得分:1)

我正在搜索,解决方案是 user.social_auth.exists() 如果用户存在于数据库中,它将返回True,否则它将返回false。

答案 3 :(得分: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'

答案 4 :(得分:0)

来自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应用程序时,会在Django模板中自动设置backends上下文变量。

答案 5 :(得分:0)

您可以从UserSocialAuth应用中查询所有正在使用社交身份验证的用户,如下所示:

from social_django.models import UserSocialAuth

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

答案 6 :(得分:0)

我在通过 python-social-auth 识别社交登录用户时遇到了同样的问题,我应该在导航栏中为他们指定一个单独的标签来完成他们的个人资料页面。当然,如果用户通过社交身份验证登录,则 DB 中没有为他/她设置密码。所以我使用了 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>

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