如何使用django-allauth进行身份验证来找到用户的顾客承诺层

时间:2019-05-21 00:52:27

标签: python django api django-allauth patreon

我正在使用django-allauth对用户进行身份验证(使用Patreon's API v1),这将使用以下信息向数据库添加json。如果用户的承诺与特定等级(或高于某一等级)相匹配,我想在网站上显示更多内容。

{
  "attributes": {
    "about": null,
    "can_see_nsfw": true,
    "created": "2019-05-20T20:29:02.000+00:00",
    "default_country_code": null,
    "discord_id": null,
    "email": "admin@email.com",
    "facebook": null,
    "facebook_id": null,
    "first_name": "Adm",
    "full_name": "Adm Nsm",
    "gender": 0,
    "has_password": true,
    "image_url": "https://c8.patreon.com/2/200/21383296",
    "is_deleted": false,
    "is_email_verified": false,
    "is_nuked": false,
    "is_suspended": false,
    "last_name": "Nsm",
    "social_connections": {
      "deviantart": null,
      "discord": null,
      "facebook": null,
      "instagram": null,
      "reddit": null,
      "spotify": null,
      "twitch": null,
      "twitter": null,
      "youtube": null
    },
    "thumb_url": "https://c8.patreon.com/2/200/21383296",
    "twitch": null,
    "twitter": null,
    "url": "https://www.patreon.com/user?u=21383296",
    "vanity": null,
    "youtube": null
  },
  "id": "21383296",
  "relationships": {
    "pledges": {
      "data": [
        {
          "id": "24461189",
          "type": "pledge"
        }
      ]
    }
  },
  "type": "user"
}

起初,我虽然Relationships.pledges.data.id会具有当前层的ID,然后我设法为特定用户添加了额外的内容块,但是显然这只是一厢情愿;在使用第二个帐户测试后,我虽然是质押级别的ID似乎每次都不同。我想我可能需要从Patreon's API请求更多信息,但不确定如何找回我需要的东西。

编辑:

根据我的收集,我需要从 / api / oauth2 / v2 / members / {id}

请求 current_entitled_tiers

问题是用户登录后所需的ID与我获得的ID不同。因此,我首先需要使用生成的oauth访问令牌和GET / api / oauth2 / v2 /身份作为长ID号。

我当前的问题是,当我尝试从/ api / oauth2 / v2 / identity获取ID时,我收到401错误代码:

<Response [401]>
{'errors': [{'code': 1, 'code_name': 'Unauthorized', 'detail': "The server could not verify that you are authorized to access the URL requested.  You either supplied the wrong credentia
ls (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.", 'id': 'b298d8b1-73db-46ab-b3f4-545e6f934599', 'status': '401', 'title': 'Unauthori
zed'}]}

我要发送的是:

headers = {"authorization": "Bearer " + str(access_token)}  # User's Access Token
req = requests.get("https://patreon.com/api/oauth2/v2/identity?include=memberships", headers=headers)

如果我通过 / api / oauth2 / v2 / campaigns / {campaign_id} / members 获得了正确的ID,则可以从 / api / oauth2 / v2 / members / {id}请求并得到我需要的东西,但是使用当前登录用户获取其ID的中间步骤使我难以理解。

谢谢。

1 个答案:

答案 0 :(得分:2)

我设法通过直接更改django-allauth获得了承诺。由于它使用API​​ v1,因此您需要更改范围才能从API v2端点获取信息。为此,我不得不修改patreon提供程序和allauth的视图。

这只是我在python中的第二个项目,所以请原谅可能是混乱或不理想的代码:

provider.py

    # Change
    def get_default_scope(self):
        return ['pledges-to-me', 'users', 'my-campaign']

    # to
    def get_default_scope(self):
        return ['identity', 'identity[email]', 'campaigns', 'campaigns.members']

views.py

"""
Views for PatreonProvider
https://www.patreon.com/platform/documentation/oauth
"""

import requests

from allauth.socialaccount.providers.oauth2.views import (
    OAuth2Adapter,
    OAuth2CallbackView,
    OAuth2LoginView,
)

from .provider import PatreonProvider


class PatreonOAuth2Adapter(OAuth2Adapter):
    provider_id = PatreonProvider.id
    access_token_url = 'https://www.patreon.com/api/oauth2/token'
    authorize_url = 'https://www.patreon.com/oauth2/authorize'
    profile_url = 'https://www.patreon.com/api/oauth2/v2/identity?include=memberships&fields[user]=email,first_name,full_name,image_url,last_name,social_connections,thumb_url,url,vanity'


    def complete_login(self, request, app, token, **kwargs):
        resp = requests.get(self.profile_url,
                            headers={'Authorization': 'Bearer ' + token.token})
        extra_data = resp.json().get('data')

        try:
            member_id = extra_data['relationships']['memberships']['data'][0]['id']
            member_url = f'https://www.patreon.com/api/oauth2/v2/members/{member_id}?include=currently_entitled_tiers&fields%5Btier%5D=title'
            resp_member = requests.get(member_url,
                                headers={'Authorization': 'Bearer ' + token.token})
            pledge_title = resp_member.json()['included'][0]['attributes']['title']
            extra_data["pledge_level"] = pledge_title

        except (KeyError, IndexError):
            extra_data["pledge_level"] = None
            pass


        return self.get_provider().sociallogin_from_response(request,
                                                             extra_data)


oauth2_login = OAuth2LoginView.adapter_view(PatreonOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(PatreonOAuth2Adapter)

这样,您可以从API v2端点请求(仍在使用API​​v1客户端,尚未测试它是否适用于API v2客户端),并且它将质押标题添加到社交帐户的extra_data字段中。