| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
from collections import OrderedDict |
| 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 FeishuOAuth2Client(OAuth2Client): |
| 13 |
app_access_token_url = ( |
| 14 |
"https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal/" # nosec |
| 15 |
) |
| 16 |
|
| 17 |
def get_redirect_url(self, authorization_url, scope, extra_params): |
| 18 |
scope = self.scope_delimiter.join(set(scope)) |
| 19 |
params = { |
| 20 |
"app_id": self.consumer_key, |
| 21 |
"redirect_uri": self.callback_url, |
| 22 |
"scope": scope, |
| 23 |
"response_type": "code", |
| 24 |
} |
| 25 |
if self.state: |
| 26 |
params["state"] = self.state |
| 27 |
params.update(extra_params) |
| 28 |
sorted_params = OrderedDict() |
| 29 |
for param in sorted(params): |
| 30 |
sorted_params[param] = params[param] |
| 31 |
return f"{authorization_url}?{urlencode(sorted_params)}" |
| 32 |
|
| 33 |
def app_access_token(self): |
| 34 |
data = { |
| 35 |
"app_id": self.consumer_key, |
| 36 |
"app_secret": self.consumer_secret, |
| 37 |
} |
| 38 |
|
| 39 |
self._strip_empty_keys(data) |
| 40 |
url = self.app_access_token_url |
| 41 |
|
| 42 |
# TODO: Proper exception handling |
| 43 |
with get_adapter().get_requests_session() as sess: |
| 44 |
resp = sess.request("POST", url, data=data) |
| 45 |
resp.raise_for_status() |
| 46 |
access_token = resp.json() |
| 47 |
if not access_token or "app_access_token" not in access_token: |
| 48 |
raise OAuth2Error(f"Error retrieving app access token: {resp.content}") |
| 49 |
return access_token["app_access_token"] |
| 50 |
|
| 51 |
def get_access_token(self, code, pkce_code_verifier=None): |
| 52 |
data = { |
| 53 |
"grant_type": "authorization_code", |
| 54 |
"code": code, |
| 55 |
"app_access_token": self.app_access_token(), |
| 56 |
} |
| 57 |
params = None |
| 58 |
self._strip_empty_keys(data) |
| 59 |
url = self.access_token_url |
| 60 |
if self.access_token_method == "GET": # nosec |
| 61 |
params = data |
| 62 |
data = None |
| 63 |
if data and pkce_code_verifier: |
| 64 |
data["code_verifier"] = pkce_code_verifier |
| 65 |
# TODO: Proper exception handling |
| 66 |
with get_adapter().get_requests_session() as sess: |
| 67 |
resp = sess.request( |
| 68 |
self.access_token_method, |
| 69 |
url, |
| 70 |
params=params, |
| 71 |
data=json.dumps(data), |
| 72 |
headers={"Content-Type": "application/json"}, |
| 73 |
) |
| 74 |
resp.raise_for_status() |
| 75 |
access_token = resp.json() |
| 76 |
if ( |
| 77 |
not access_token |
| 78 |
or "data" not in access_token |
| 79 |
or "access_token" not in access_token["data"] |
| 80 |
): |
| 81 |
raise OAuth2Error(f"Error retrieving access token: {resp.content}") |
| 82 |
return access_token["data"] |