| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from allauth.socialaccount import app_settings |
| 6 |
from allauth.socialaccount.adapter import get_adapter |
| 7 |
from allauth.socialaccount.providers.oauth2.client import OAuth2Error |
| 8 |
from allauth.socialaccount.providers.oauth2.views import ( |
| 9 |
OAuth2Adapter, |
| 10 |
OAuth2CallbackView, |
| 11 |
OAuth2LoginView, |
| 12 |
) |
| 13 |
from allauth.socialaccount.providers.snapchat.constants import PROVIDER_ID, Scope |
| 14 |
|
| 15 |
|
| 16 |
class SnapchatOAuth2Adapter(OAuth2Adapter): |
| 17 |
provider_id = PROVIDER_ID |
| 18 |
|
| 19 |
access_token_url = "https://accounts.snapchat.com/accounts/oauth2/token" # nosec |
| 20 |
authorize_url = "https://accounts.snapchat.com/accounts/oauth2/auth" |
| 21 |
identity_url = "https://api.snapkit.com/v1/me" |
| 22 |
|
| 23 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 24 |
extra_data = self.get_data(token.token) |
| 25 |
return self.get_provider().sociallogin_from_response(request, extra_data) |
| 26 |
|
| 27 |
def get_data(self, token): |
| 28 |
settings = app_settings.PROVIDERS.get(self.provider_id, {}) |
| 29 |
provider_scope = settings.get( |
| 30 |
"SCOPE", |
| 31 |
"['https://auth.snapchat.com/oauth2/api/user.external_id', 'https://auth.snapchat.com/oauth2/api/user.display_name']", |
| 32 |
) |
| 33 |
|
| 34 |
hed = { |
| 35 |
"Authorization": f"Bearer {token}", |
| 36 |
"Content-Type": "application/json;charset=UTF-8", |
| 37 |
} |
| 38 |
if Scope.BITMOJI in provider_scope: |
| 39 |
data = {"query": "{ me { externalId displayName bitmoji { avatar id } } }"} |
| 40 |
else: |
| 41 |
data = {"query": "{ me { externalId displayName } }"} |
| 42 |
|
| 43 |
with get_adapter().get_requests_session() as sess: |
| 44 |
resp = sess.post(self.identity_url, headers=hed, json=data) |
| 45 |
resp.raise_for_status() |
| 46 |
data = resp.json() |
| 47 |
|
| 48 |
if not data.get("data"): |
| 49 |
raise OAuth2Error() |
| 50 |
|
| 51 |
return data |
| 52 |
|
| 53 |
|
| 54 |
oauth2_login = OAuth2LoginView.adapter_view(SnapchatOAuth2Adapter) |
| 55 |
oauth2_callback = OAuth2CallbackView.adapter_view(SnapchatOAuth2Adapter) |