| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import requests |
| 4 |
import secrets |
| 5 |
from typing import Any |
| 6 |
|
| 7 |
from django.conf import settings |
| 8 |
from django.core.exceptions import PermissionDenied, ValidationError |
| 9 |
from django.http import HttpRequest |
| 10 |
from django.utils.decorators import method_decorator |
| 11 |
from django.views.decorators.csrf import csrf_exempt |
| 12 |
from django.views.generic import View |
| 13 |
|
| 14 |
from allauth.account.internal.decorators import login_not_required |
| 15 |
from allauth.socialaccount.adapter import get_adapter |
| 16 |
from allauth.socialaccount.helpers import ( |
| 17 |
complete_social_login, |
| 18 |
render_authentication_error, |
| 19 |
) |
| 20 |
from allauth.socialaccount.internal import jwtkit |
| 21 |
from allauth.socialaccount.providers.oauth2.client import OAuth2Error |
| 22 |
from allauth.socialaccount.providers.oauth2.views import ( |
| 23 |
OAuth2Adapter, |
| 24 |
OAuth2CallbackView, |
| 25 |
OAuth2LoginView, |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
CERTS_URL = ( |
| 30 |
getattr(settings, "SOCIALACCOUNT_PROVIDERS", {}) |
| 31 |
.get("google", {}) |
| 32 |
.get("CERTS_URL", "https://www.googleapis.com/oauth2/v1/certs") |
| 33 |
) |
| 34 |
|
| 35 |
IDENTITY_URL = ( |
| 36 |
getattr(settings, "SOCIALACCOUNT_PROVIDERS", {}) |
| 37 |
.get("google", {}) |
| 38 |
.get("IDENTITY_URL", "https://www.googleapis.com/oauth2/v2/userinfo") |
| 39 |
) |
| 40 |
|
| 41 |
ACCESS_TOKEN_URL = ( |
| 42 |
getattr(settings, "SOCIALACCOUNT_PROVIDERS", {}) |
| 43 |
.get("google", {}) |
| 44 |
.get("ACCESS_TOKEN_URL", "https://oauth2.googleapis.com/token") |
| 45 |
) |
| 46 |
|
| 47 |
AUTHORIZE_URL = ( |
| 48 |
getattr(settings, "SOCIALACCOUNT_PROVIDERS", {}) |
| 49 |
.get("google", {}) |
| 50 |
.get("AUTHORIZE_URL", "https://accounts.google.com/o/oauth2/v2/auth") |
| 51 |
) |
| 52 |
|
| 53 |
ID_TOKEN_ISSUER = ( |
| 54 |
getattr(settings, "SOCIALACCOUNT_PROVIDERS", {}) |
| 55 |
.get("google", {}) |
| 56 |
.get("ID_TOKEN_ISSUER", "https://accounts.google.com") |
| 57 |
) |
| 58 |
|
| 59 |
FETCH_USERINFO = ( |
| 60 |
getattr(settings, "SOCIALACCOUNT_PROVIDERS", {}) |
| 61 |
.get("google", {}) |
| 62 |
.get("FETCH_USERINFO", False) |
| 63 |
) |
| 64 |
|
| 65 |
|
| 66 |
def _verify_and_decode(app, credential, verify_signature=True): |
| 67 |
return jwtkit.verify_and_decode( |
| 68 |
credential=credential, |
| 69 |
keys_url=CERTS_URL, |
| 70 |
issuer=ID_TOKEN_ISSUER, |
| 71 |
audience=app.client_id, |
| 72 |
lookup_kid=jwtkit.lookup_kid_pem_x509_certificate, |
| 73 |
verify_signature=verify_signature, |
| 74 |
) |
| 75 |
|
| 76 |
|
| 77 |
class GoogleOAuth2Adapter(OAuth2Adapter): |
| 78 |
provider_id = "google" |
| 79 |
access_token_url = ACCESS_TOKEN_URL |
| 80 |
authorize_url = AUTHORIZE_URL |
| 81 |
id_token_issuer = ID_TOKEN_ISSUER |
| 82 |
identity_url = IDENTITY_URL |
| 83 |
fetch_userinfo = FETCH_USERINFO |
| 84 |
|
| 85 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 86 |
response = kwargs["response"] |
| 87 |
data = None |
| 88 |
id_token = response.get("id_token") |
| 89 |
if id_token: |
| 90 |
data = self._decode_id_token(app, id_token) |
| 91 |
if self.fetch_userinfo and "picture" not in data: |
| 92 |
info = self._fetch_user_info(token.token) |
| 93 |
picture = info.get("picture") |
| 94 |
if picture: |
| 95 |
data["picture"] = picture |
| 96 |
else: |
| 97 |
data = self._fetch_user_info(token.token) |
| 98 |
login = self.get_provider().sociallogin_from_response(request, data) |
| 99 |
return login |
| 100 |
|
| 101 |
def _decode_id_token(self, app, id_token): |
| 102 |
""" |
| 103 |
If the token was received by direct communication protected by |
| 104 |
TLS between this library and Google, we are allowed to skip checking the |
| 105 |
token signature according to the OpenID Connect Core 1.0 specification. |
| 106 |
|
| 107 |
https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation |
| 108 |
""" |
| 109 |
verify_signature = not self.did_fetch_access_token |
| 110 |
return _verify_and_decode(app, id_token, verify_signature=verify_signature) |
| 111 |
|
| 112 |
def _fetch_user_info(self, access_token): |
| 113 |
headers = {"Authorization": f"Bearer {access_token}"} |
| 114 |
with get_adapter().get_requests_session() as sess: |
| 115 |
resp = sess.get(self.identity_url, headers=headers) |
| 116 |
if not resp.ok: |
| 117 |
raise OAuth2Error("Request to user info failed") |
| 118 |
return resp.json() |
| 119 |
|
| 120 |
|
| 121 |
oauth2_login = OAuth2LoginView.adapter_view(GoogleOAuth2Adapter) |
| 122 |
oauth2_callback = OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter) |
| 123 |
|
| 124 |
|
| 125 |
class LoginByTokenView(View): |
| 126 |
@method_decorator(login_not_required) |
| 127 |
def dispatch(self, request: HttpRequest): |
| 128 |
self.adapter = get_adapter() |
| 129 |
self.provider = self.adapter.get_provider( |
| 130 |
request, GoogleOAuth2Adapter.provider_id |
| 131 |
) |
| 132 |
try: |
| 133 |
return super().dispatch(request) |
| 134 |
except ( |
| 135 |
OAuth2Error, |
| 136 |
requests.RequestException, |
| 137 |
PermissionDenied, |
| 138 |
ValidationError, |
| 139 |
) as exc: |
| 140 |
return render_authentication_error(request, self.provider, exception=exc) |
| 141 |
|
| 142 |
def get(self, request: HttpRequest): |
| 143 |
# If we leave out get() it will return a response with a 405, but |
| 144 |
# we really want to show an authentication error. |
| 145 |
raise PermissionDenied("405") |
| 146 |
|
| 147 |
def post(self, request: HttpRequest, *args: Any, **kwargs: Any): |
| 148 |
self.check_csrf(request) |
| 149 |
|
| 150 |
credential = request.POST.get("credential") |
| 151 |
login = self.provider.verify_token(request, {"id_token": credential}) |
| 152 |
return complete_social_login(request, login) |
| 153 |
|
| 154 |
def check_csrf(self, request: HttpRequest) -> None: |
| 155 |
csrf_token_cookie = request.COOKIES.get("g_csrf_token") |
| 156 |
if not csrf_token_cookie: |
| 157 |
raise PermissionDenied("No CSRF token in Cookie.") |
| 158 |
csrf_token_body = request.POST.get("g_csrf_token") |
| 159 |
if not csrf_token_body: |
| 160 |
raise PermissionDenied("No CSRF token in post body.") |
| 161 |
if not secrets.compare_digest(csrf_token_cookie, csrf_token_body): |
| 162 |
raise PermissionDenied("Failed to verify double submit cookie.") |
| 163 |
|
| 164 |
|
| 165 |
login_by_token = csrf_exempt(LoginByTokenView.as_view()) |