| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from allauth.socialaccount import app_settings |
| 6 |
from allauth.socialaccount.adapter import get_adapter |
| 7 |
from allauth.socialaccount.models import SocialToken |
| 8 |
from allauth.socialaccount.providers.oauth2.views import ( |
| 9 |
OAuth2Adapter, |
| 10 |
OAuth2CallbackView, |
| 11 |
OAuth2LoginView, |
| 12 |
) |
| 13 |
|
| 14 |
|
| 15 |
class AmazonCognitoOAuth2Adapter(OAuth2Adapter): |
| 16 |
provider_id = "amazon_cognito" |
| 17 |
|
| 18 |
DOMAIN_KEY_MISSING_ERROR = ( |
| 19 |
'"DOMAIN" key is missing in Amazon Cognito configuration.' |
| 20 |
) |
| 21 |
|
| 22 |
@property |
| 23 |
def settings(self): |
| 24 |
return app_settings.PROVIDERS.get(self.provider_id, {}) |
| 25 |
|
| 26 |
@property |
| 27 |
def domain(self): |
| 28 |
domain = self.settings.get("DOMAIN") |
| 29 |
|
| 30 |
if domain is None: |
| 31 |
raise ValueError(self.DOMAIN_KEY_MISSING_ERROR) |
| 32 |
|
| 33 |
return domain |
| 34 |
|
| 35 |
@property |
| 36 |
def access_token_url(self): |
| 37 |
return f"{self.domain}/oauth2/token" |
| 38 |
|
| 39 |
@property |
| 40 |
def authorize_url(self): |
| 41 |
return f"{self.domain}/oauth2/authorize" |
| 42 |
|
| 43 |
@property |
| 44 |
def profile_url(self): |
| 45 |
return f"{self.domain}/oauth2/userInfo" |
| 46 |
|
| 47 |
def complete_login(self, request: HttpRequest, app, token: SocialToken, **kwargs): |
| 48 |
headers = { |
| 49 |
"Authorization": f"Bearer {token.token}", |
| 50 |
} |
| 51 |
with get_adapter().get_requests_session() as sess: |
| 52 |
response = sess.get(self.profile_url, headers=headers) |
| 53 |
response.raise_for_status() |
| 54 |
extra_data = response.json() |
| 55 |
return self.get_provider().sociallogin_from_response(request, extra_data) |
| 56 |
|
| 57 |
|
| 58 |
oauth2_login = OAuth2LoginView.adapter_view(AmazonCognitoOAuth2Adapter) |
| 59 |
oauth2_callback = OAuth2CallbackView.adapter_view(AmazonCognitoOAuth2Adapter) |