如何使用 django-allauth 查找用户的 patreon 质押层进行身份验证

How to find user's patreon pledge tier using django-allauth for authentication

我正在使用 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}[=39 请求 currently_entitled_tiers =]

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

我目前的问题是,当我尝试从 /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,我可以向 [=45= 请求]/{id} 并得到我需要的东西,但是使用当前登录的用户获取他们的 ID 的中间步骤让我望而却步。

谢谢。

我直接改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 端点请求(仍在使用 APIv1 客户端,尚未测试它是否适用于 API v2 客户端),以及它会将承诺标题添加到社交帐户的 extra_data 字段中。

我已经更新 django-allauth,使用 Nick S 的部分回答,以启用 Patreon API v2(从 django-allauth 0.40.0 开始)。

要使用 API v2,您现在只需更改 settings.py 中 SOCIALACCOUNT_PROVIDERS 的 patreon 条目:

settings.py(最后加上)

SOCIALACCOUNT_PROVIDERS = {
    'patreon': {
        'VERSION': 'v2',
    }
}

默认情况下,这还会将质押层添加到每个用户的社交帐户中,并将其存储在extra_data['pledge_level']