| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from http import HTTPStatus |
| 4 |
|
| 5 |
from django.http import HttpRequest |
| 6 |
|
| 7 |
from allauth.socialaccount import app_settings |
| 8 |
from allauth.socialaccount.adapter import get_adapter |
| 9 |
from allauth.socialaccount.providers.oauth2.views import ( |
| 10 |
OAuth2Adapter, |
| 11 |
OAuth2CallbackView, |
| 12 |
OAuth2LoginView, |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
class GitHubOAuth2Adapter(OAuth2Adapter): |
| 17 |
provider_id = "github" |
| 18 |
settings = app_settings.PROVIDERS.get(provider_id, {}) |
| 19 |
|
| 20 |
if "GITHUB_URL" in settings: |
| 21 |
web_url = settings.get("GITHUB_URL").rstrip("/") |
| 22 |
api_url = f"{web_url}/api/v3" |
| 23 |
else: |
| 24 |
web_url = "https://github.com" |
| 25 |
api_url = "https://api.github.com" |
| 26 |
|
| 27 |
access_token_url = f"{web_url}/login/oauth/access_token" |
| 28 |
authorize_url = f"{web_url}/login/oauth/authorize" |
| 29 |
profile_url = f"{api_url}/user" |
| 30 |
emails_url = f"{api_url}/user/emails" |
| 31 |
|
| 32 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 33 |
headers = {"Authorization": f"token {token.token}"} |
| 34 |
with get_adapter().get_requests_session() as sess: |
| 35 |
resp = sess.get(self.profile_url, headers=headers) |
| 36 |
resp.raise_for_status() |
| 37 |
extra_data = resp.json() |
| 38 |
if app_settings.QUERY_EMAIL: |
| 39 |
if emails := self.get_emails(headers): |
| 40 |
extra_data["emails"] = emails |
| 41 |
return self.get_provider().sociallogin_from_response(request, extra_data) |
| 42 |
|
| 43 |
def get_emails(self, headers) -> list | None: |
| 44 |
with get_adapter().get_requests_session() as sess: |
| 45 |
resp = sess.get(self.emails_url, headers=headers) |
| 46 |
# https://api.github.com/user/emails -- 404 is documented to occur. |
| 47 |
if resp.status_code == HTTPStatus.NOT_FOUND: |
| 48 |
return None |
| 49 |
resp.raise_for_status() |
| 50 |
return resp.json() |
| 51 |
|
| 52 |
|
| 53 |
oauth2_login = OAuth2LoginView.adapter_view(GitHubOAuth2Adapter) |
| 54 |
oauth2_callback = OAuth2CallbackView.adapter_view(GitHubOAuth2Adapter) |