Debian Codegraph @

allauth/socialaccount/providers/weixin/client.py

raw
1 from __future__ import annotations
2
3 from collections import OrderedDict
4 from http import HTTPStatus
5
6 from django.utils.http import urlencode
7
8 from allauth.socialaccount.adapter import get_adapter
9 from allauth.socialaccount.providers.oauth2.client import OAuth2Client, OAuth2Error
10
11
12 class WeixinOAuth2Client(OAuth2Client):
13 def get_redirect_url(self, authorization_url, scope, extra_params):
14 scope = self.scope_delimiter.join(set(scope))
15 params = {
16 "appid": self.consumer_key,
17 "redirect_uri": self.callback_url,
18 "scope": scope,
19 "response_type": "code",
20 }
21 if self.state:
22 params["state"] = self.state
23 params.update(extra_params)
24 sorted_params = OrderedDict()
25 for param in sorted(params):
26 sorted_params[param] = params[param]
27 return f"{authorization_url}?{urlencode(sorted_params)}"
28
29 def get_access_token(self, code, pkce_code_verifier=None):
30 data = {
31 "appid": self.consumer_key,
32 "grant_type": "authorization_code",
33 "secret": self.consumer_secret,
34 "code": code,
35 }
36 params = None
37 self._strip_empty_keys(data)
38 url = self.access_token_url
39 if self.access_token_method == "GET": # nosec
40 params = data
41 data = None
42 if data and pkce_code_verifier:
43 data["code_verifier"] = pkce_code_verifier
44 # TODO: Proper exception handling
45 with get_adapter().get_requests_session() as sess:
46 resp = sess.request(self.access_token_method, url, params=params, data=data)
47 access_token = None
48 if resp.status_code == HTTPStatus.OK:
49 access_token = resp.json()
50 if not access_token or "access_token" not in access_token:
51 raise OAuth2Error(f"Error retrieving access token: {resp.content}")
52 return access_token