| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from http import HTTPStatus |
| 4 |
|
| 5 |
from allauth.socialaccount import app_settings |
| 6 |
from allauth.socialaccount.adapter import get_adapter |
| 7 |
from allauth.socialaccount.providers.oauth2.client import OAuth2Client, OAuth2Error |
| 8 |
|
| 9 |
|
| 10 |
class UntappdOAuth2Client(OAuth2Client): |
| 11 |
""" |
| 12 |
Custom client because Untappd: |
| 13 |
* uses redirect_url instead of redirect_uri |
| 14 |
* nests access_token inside an extra 'response' object |
| 15 |
""" |
| 16 |
|
| 17 |
def get_access_token(self, code, pkce_code_verifier=None): |
| 18 |
from allauth.socialaccount.providers.untappd.provider import UntappdProvider |
| 19 |
|
| 20 |
data = { |
| 21 |
"client_id": self.consumer_key, |
| 22 |
"redirect_url": self.callback_url, |
| 23 |
"grant_type": "authorization_code", |
| 24 |
"response_type": "code", |
| 25 |
"client_secret": self.consumer_secret, |
| 26 |
"code": code, |
| 27 |
} |
| 28 |
params = None |
| 29 |
self._strip_empty_keys(data) |
| 30 |
url = self.access_token_url |
| 31 |
if self.access_token_method == "GET": # nosec |
| 32 |
params = data |
| 33 |
data = None |
| 34 |
if data and pkce_code_verifier: |
| 35 |
data["code_verifier"] = pkce_code_verifier |
| 36 |
# Allow custom User Agent to comply with Untappd API |
| 37 |
settings = app_settings.PROVIDERS.get(UntappdProvider.id, {}) |
| 38 |
headers = {"User-Agent": settings.get("USER_AGENT", "django-allauth")} |
| 39 |
# TODO: Proper exception handling |
| 40 |
with get_adapter().get_requests_session() as sess: |
| 41 |
resp = sess.request( |
| 42 |
self.access_token_method, |
| 43 |
url, |
| 44 |
params=params, |
| 45 |
data=data, |
| 46 |
headers=headers, |
| 47 |
) |
| 48 |
access_token = None |
| 49 |
if resp.status_code == HTTPStatus.OK: |
| 50 |
access_token = resp.json()["response"] |
| 51 |
if not access_token or "access_token" not in access_token: |
| 52 |
raise OAuth2Error(f"Error retrieving access token: {resp.content}") |
| 53 |
return access_token |