| 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 LinkedInOAuth2Adapter(OAuth2Adapter): |
| 15 |
provider_id = "linkedin_oauth2" |
| 16 |
access_token_url = "https://www.linkedin.com/oauth/v2/accessToken" # nosec |
| 17 |
authorize_url = "https://www.linkedin.com/oauth/v2/authorization" |
| 18 |
profile_url = "https://api.linkedin.com/v2/me" |
| 19 |
email_url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))" # noqa |
| 20 |
access_token_method = "GET" # nosec |
| 21 |
|
| 22 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 23 |
extra_data = self.get_user_info(token) |
| 24 |
return self.get_provider().sociallogin_from_response(request, extra_data) |
| 25 |
|
| 26 |
def get_user_info(self, token): |
| 27 |
fields = self.get_provider().get_profile_fields() |
| 28 |
|
| 29 |
headers = { |
| 30 |
**self.get_provider().get_settings().get("HEADERS", {}), |
| 31 |
"Authorization": f"Bearer {token.token}", |
| 32 |
} |
| 33 |
|
| 34 |
info = {} |
| 35 |
with get_adapter().get_requests_session() as sess: |
| 36 |
if app_settings.QUERY_EMAIL: |
| 37 |
sess = get_adapter().get_requests_session() |
| 38 |
resp = sess.get(self.email_url, headers=headers) |
| 39 |
# If this response goes wrong, that is not a blocker in order to |
| 40 |
# continue. |
| 41 |
if resp.ok: |
| 42 |
info = resp.json() |
| 43 |
|
| 44 |
url = f"{self.profile_url}?projection=({','.join(fields)})" |
| 45 |
resp = sess.get(url, headers=headers) |
| 46 |
resp.raise_for_status() |
| 47 |
info.update(resp.json()) |
| 48 |
return info |
| 49 |
|
| 50 |
|
| 51 |
oauth2_login = OAuth2LoginView.adapter_view(LinkedInOAuth2Adapter) |
| 52 |
oauth2_callback = OAuth2CallbackView.adapter_view(LinkedInOAuth2Adapter) |