Debian Codegraph @

allauth/socialaccount/providers/battlenet/views.py

raw
1 """
2 from __future__ import annotations
3
4 OAuth2 Adapter for Battle.net
5
6 Resources:
7
8 * Battle.net OAuth2 documentation:
9 https://dev.battle.net/docs/read/oauth
10 * Battle.net API documentation:
11 https://dev.battle.net/io-docs
12 * Original announcement:
13 https://us.battle.net/en/forum/topic/13979297799
14 * The Battle.net API forum:
15 https://us.battle.net/en/forum/15051532/
16 """
17
18 from http import HTTPStatus
19
20 from django.conf import settings
21 from django.http import HttpRequest
22
23 from allauth.socialaccount.adapter import get_adapter
24 from allauth.socialaccount.providers.oauth2.client import OAuth2Error
25 from allauth.socialaccount.providers.oauth2.views import (
26 OAuth2Adapter,
27 OAuth2CallbackView,
28 OAuth2LoginView,
29 )
30
31
32 class Region:
33 APAC = "apac"
34 CN = "cn"
35 EU = "eu"
36 KR = "kr"
37 SEA = "sea"
38 TW = "tw"
39 US = "us"
40
41
42 def _check_errors(response):
43 try:
44 data = response.json()
45 except ValueError: # JSONDecodeError on py3
46 raise OAuth2Error(f"Invalid JSON from Battle.net API: {response.text!r}")
47
48 if response.status_code >= HTTPStatus.BAD_REQUEST or "error" in data:
49 # For errors, we expect the following format:
50 # {"error": "error_name", "error_description": "Oops!"}
51 # For example, if the token is not valid, we will get:
52 # {
53 # "error": "invalid_token",
54 # "error_description": "Invalid access token: abcdef123456"
55 # }
56 # For the profile API, this may also look like the following:
57 # {"code": 403, "type": "Forbidden", "detail": "Account Inactive"}
58 error = data.get("error", "") or data.get("type", "")
59 desc = data.get("error_description", "") or data.get("detail", "")
60
61 raise OAuth2Error(f"Battle.net error: {error} ({desc})")
62
63 # The expected output from the API follows this format:
64 # {"id": 12345, "battletag": "Example#12345"}
65 # The battletag is optional.
66 if "id" not in data:
67 # If the id is not present, the output is not usable (no UID)
68 raise OAuth2Error(f"Invalid data from Battle.net API: {data!r}")
69
70 return data
71
72
73 class BattleNetOAuth2Adapter(OAuth2Adapter):
74 """
75 OAuth2 adapter for Battle.net
76 https://dev.battle.net/docs/read/oauth
77
78 Region is set to us by default, but can be overridden with the
79 `region` GET parameter when performing a login.
80 Can be any of eu, us, kr, sea, tw or cn
81 """
82
83 provider_id = "battlenet"
84
85 valid_regions = (
86 Region.APAC,
87 Region.CN,
88 Region.EU,
89 Region.KR,
90 Region.SEA,
91 Region.TW,
92 Region.US,
93 )
94
95 @property
96 def battlenet_region(self):
97 # Check by URI query parameter first.
98 region = self.request.GET.get("region", "").lower()
99 if region == Region.SEA:
100 # South-East Asia uses the same region as US everywhere
101 return Region.US
102 if region in self.valid_regions:
103 return region
104
105 # Second, check the provider settings.
106 region = (
107 getattr(settings, "SOCIALACCOUNT_PROVIDERS", {})
108 .get("battlenet", {})
109 .get("REGION", "us")
110 )
111
112 if region in self.valid_regions:
113 return region
114
115 return Region.US
116
117 @property
118 def battlenet_base_url(self):
119 region = self.battlenet_region
120 if region == Region.CN:
121 return "https://oauth.battlenet.com.cn"
122 return "https://oauth.battle.net"
123
124 @property
125 def access_token_url(self):
126 return f"{self.battlenet_base_url}/token"
127
128 @property
129 def authorize_url(self):
130 return f"{self.battlenet_base_url}/authorize"
131
132 @property
133 def profile_url(self):
134 return f"{self.battlenet_base_url}/userinfo"
135
136 def complete_login(self, request: HttpRequest, app, token, **kwargs):
137 headers = {"authorization": f"Bearer {token.token}"}
138 with get_adapter().get_requests_session() as sess:
139 response = sess.get(self.profile_url, headers=headers)
140 data = _check_errors(response)
141
142 # Add the region to the data so that we can have it in `extra_data`.
143 data["region"] = self.battlenet_region
144
145 return self.get_provider().sociallogin_from_response(request, data)
146
147 def get_callback_url(self, request: HttpRequest, app):
148 r = super().get_callback_url(request, app)
149 region = request.GET.get("region", "").lower()
150 # Pass the region down to the callback URL if we specified it
151 if region and region in self.valid_regions:
152 r += f"?region={region}"
153 return r
154
155
156 oauth2_login = OAuth2LoginView.adapter_view(BattleNetOAuth2Adapter)
157 oauth2_callback = OAuth2CallbackView.adapter_view(BattleNetOAuth2Adapter)