通过Python-social-auth

时间:2015-09-15 11:30:21

标签: python django python-social-auth

我已将其包含在我的settings.py文件中:

SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']

如何在管道中访问facebook用户的电子邮件。 我正在使用pythons-social-auth

我想使用来自Facebook的用户电子邮件地址,并检查是否已有该电子邮件的用户。

2 个答案:

答案 0 :(得分:1)

您必须自定义管道方法或向管道添加新方法。

例如,您可以自定义create_user方法:

def create_user(strategy, details, user=None, *args, **kwargs):
    email = details.get('email', '')

    if UserClass.objects.filter(email=email).exists():
        // do whatever you want

    if user:
        return {'is_new': False}

    fields = dict((name, kwargs.get(name) or details.get(name))
                  for name in strategy.setting('USER_FIELDS',
                                               USER_FIELDS))
    if not fields:
        return

    return {
        'is_new': True,
        'user': strategy.create_user(**fields)
    } 

然后在您的设置文件中,指明此方法的路径:

SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.social_user',
    'social.pipeline.user.get_username',
    'path.to.your.custom.create_user',    // indicate the path here
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details'
)

希望这会有所帮助

<强>更新

如果您未在email参数中获得details,请尝试以下操作:

response管道方法中打印social_details变量:

def social_details(backend, details, response, *args, **kwargs):
    print response
    return {'details': dict(backend.get_user_details(response),
                            **details)}

在日志中查看响应是否包含email。如果它包含email,则表示email仅包含在details变量中的details参数中。

如果没有,SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']是否有效?我的意思是,Facebook是否要求您在登录时授予此范围?

如果是,请批准。如果不是,请尝试从Facebook删除您的应用,然后重新注册。它有时会发生。

答案 1 :(得分:0)

这可能是一个老问题,但答案对很多人来说都很重要。所以我们走了。

首先授予scope,然后授予harvest数据。因此,您的django settings.py文件需要这两个设置(除keysecret之外)

SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
  'locale': 'en',
  'fields': 'id, name, email,
}

请注意,在身份验证期间,即使您已经要求,用户也可能决定不提供该电子邮件。因此,不要使用response['email']使用response.get('email', None)收到电子邮件。然后处理没有提供电子邮件的情况。

相关问题