| 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.providers.oauth2.views import ( |
| 8 |
OAuth2Adapter, |
| 9 |
OAuth2CallbackView, |
| 10 |
OAuth2LoginView, |
| 11 |
) |
| 12 |
|
| 13 |
|
| 14 |
class BitbucketOAuth2Adapter(OAuth2Adapter): |
| 15 |
provider_id = "bitbucket_oauth2" |
| 16 |
access_token_url = "https://bitbucket.org/site/oauth2/access_token" # nosec |
| 17 |
authorize_url = "https://bitbucket.org/site/oauth2/authorize" |
| 18 |
profile_url = "https://api.bitbucket.org/2.0/user" |
| 19 |
emails_url = "https://api.bitbucket.org/2.0/user/emails" |
| 20 |
|
| 21 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 22 |
headers = {"Authorization": f"Bearer {token.token}"} |
| 23 |
with get_adapter().get_requests_session() as sess: |
| 24 |
resp = sess.get(self.profile_url, headers=headers) |
| 25 |
extra_data = resp.json() |
| 26 |
if app_settings.QUERY_EMAIL: |
| 27 |
if email := self.get_email(headers): |
| 28 |
extra_data["email"] = email |
| 29 |
return self.get_provider().sociallogin_from_response(request, extra_data) |
| 30 |
|
| 31 |
def get_email(self, headers) -> str: |
| 32 |
"""Fetches email address from email API endpoint""" |
| 33 |
with get_adapter().get_requests_session() as sess: |
| 34 |
resp = sess.get(self.emails_url, headers=headers) |
| 35 |
emails = resp.json().get("values", []) |
| 36 |
email = "" |
| 37 |
try: |
| 38 |
email = emails[0].get("email") |
| 39 |
primary_emails = [e for e in emails if e.get("is_primary", False)] |
| 40 |
email = primary_emails[0].get("email") |
| 41 |
except (IndexError, TypeError, KeyError): |
| 42 |
pass |
| 43 |
return email |
| 44 |
|
| 45 |
|
| 46 |
oauth_login = OAuth2LoginView.adapter_view(BitbucketOAuth2Adapter) |
| 47 |
oauth_callback = OAuth2CallbackView.adapter_view(BitbucketOAuth2Adapter) |