| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
from django.urls import reverse |
| 5 |
|
| 6 |
from allauth.account import app_settings |
| 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 |
from allauth.utils import build_absolute_uri |
| 15 |
|
| 16 |
from .client import FeishuOAuth2Client |
| 17 |
|
| 18 |
|
| 19 |
class FeishuOAuth2Adapter(OAuth2Adapter): |
| 20 |
provider_id = "feishu" |
| 21 |
|
| 22 |
authorization_url = "https://open.feishu.cn/open-apis/authen/v1/index" |
| 23 |
access_token_url = ( |
| 24 |
"https://open.feishu.cn/open-apis/authen/v1/access_token" # nosec |
| 25 |
) |
| 26 |
app_access_token_url = ( |
| 27 |
"https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal/" # nosec |
| 28 |
) |
| 29 |
user_info_url = "https://open.feishu.cn/open-apis/authen/v1/user_info" |
| 30 |
|
| 31 |
@property |
| 32 |
def authorize_url(self): |
| 33 |
settings = self.get_provider().get_settings() |
| 34 |
url = settings.get("AUTHORIZE_URL", self.authorization_url) |
| 35 |
return url |
| 36 |
|
| 37 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 38 |
headers = { |
| 39 |
"Content-Type": "application/json", |
| 40 |
"Authorization": f"Bearer {token.token}", |
| 41 |
} |
| 42 |
with get_adapter().get_requests_session() as sess: |
| 43 |
resp = sess.get(self.user_info_url, headers=headers) |
| 44 |
resp.raise_for_status() |
| 45 |
extra_data = resp.json() |
| 46 |
if extra_data["code"] != 0: |
| 47 |
raise OAuth2Error(f"Error retrieving code: {resp.content}") |
| 48 |
extra_data = extra_data["data"] |
| 49 |
|
| 50 |
return self.get_provider().sociallogin_from_response(request, extra_data) |
| 51 |
|
| 52 |
def get_client(self, request: HttpRequest, app): |
| 53 |
callback_url = reverse(f"{self.provider_id}_callback") |
| 54 |
protocol = self.redirect_uri_protocol or app_settings.DEFAULT_HTTP_PROTOCOL |
| 55 |
callback_url = build_absolute_uri(request, callback_url, protocol=protocol) |
| 56 |
client = FeishuOAuth2Client( |
| 57 |
request, |
| 58 |
app.client_id, |
| 59 |
app.secret, |
| 60 |
self.access_token_method, |
| 61 |
self.access_token_url, |
| 62 |
callback_url, |
| 63 |
) |
| 64 |
return client |
| 65 |
|
| 66 |
|
| 67 |
oauth2_login = OAuth2LoginView.adapter_view(FeishuOAuth2Adapter) |
| 68 |
oauth2_callback = OAuth2CallbackView.adapter_view(FeishuOAuth2Adapter) |