Debian Codegraph @

allauth/socialaccount/providers/twitch/views.py

raw
1 from __future__ import annotations
2
3 from http import HTTPStatus
4
5 from django.http import HttpRequest
6
7 from allauth.socialaccount.adapter import get_adapter
8 from allauth.socialaccount.providers.oauth2.client import OAuth2Error
9 from allauth.socialaccount.providers.oauth2.views import (
10 OAuth2Adapter,
11 OAuth2CallbackView,
12 OAuth2LoginView,
13 )
14
15
16 class TwitchOAuth2Adapter(OAuth2Adapter):
17 provider_id = "twitch"
18 access_token_url = "https://id.twitch.tv/oauth2/token" # nosec
19 authorize_url = "https://id.twitch.tv/oauth2/authorize"
20 profile_url = "https://api.twitch.tv/helix/users"
21
22 def complete_login(self, request: HttpRequest, app, token, **kwargs):
23 headers = {
24 "Authorization": f"Bearer {token.token}",
25 "Client-ID": app.client_id,
26 }
27 with get_adapter().get_requests_session() as sess:
28 response = sess.get(self.profile_url, headers=headers)
29 data = response.json()
30 if response.status_code >= HTTPStatus.BAD_REQUEST:
31 error = data.get("error", "")
32 message = data.get("message", "")
33 raise OAuth2Error(f"Twitch API Error: {error} ({message})")
34
35 try:
36 user_info = data.get("data", [])[0]
37 except IndexError:
38 raise OAuth2Error(f"Invalid data from Twitch API: {data}")
39
40 if "id" not in user_info:
41 raise OAuth2Error(f"Invalid data from Twitch API: {user_info}")
42
43 return self.get_provider().sociallogin_from_response(request, user_info)
44
45
46 oauth2_login = OAuth2LoginView.adapter_view(TwitchOAuth2Adapter)
47 oauth2_callback = OAuth2CallbackView.adapter_view(TwitchOAuth2Adapter)