| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
from datetime import timedelta |
| 5 |
|
| 6 |
from django.http import HttpRequest, HttpResponseNotAllowed, HttpResponseRedirect |
| 7 |
from django.urls import reverse |
| 8 |
from django.utils import timezone |
| 9 |
from django.utils.http import urlencode |
| 10 |
from django.views.decorators.csrf import csrf_exempt |
| 11 |
|
| 12 |
from allauth.account.internal.decorators import login_not_required |
| 13 |
from allauth.socialaccount.internal import jwtkit |
| 14 |
from allauth.socialaccount.models import SocialToken |
| 15 |
from allauth.socialaccount.providers.oauth2.views import ( |
| 16 |
OAuth2Adapter, |
| 17 |
OAuth2CallbackView, |
| 18 |
OAuth2LoginView, |
| 19 |
) |
| 20 |
from allauth.utils import build_absolute_uri, get_request_param |
| 21 |
|
| 22 |
from .apple_session import get_apple_session |
| 23 |
from .client import AppleOAuth2Client |
| 24 |
|
| 25 |
|
| 26 |
class AppleOAuth2Adapter(OAuth2Adapter): |
| 27 |
client_class = AppleOAuth2Client |
| 28 |
provider_id = "apple" |
| 29 |
access_token_url = "https://appleid.apple.com/auth/token" # nosec |
| 30 |
authorize_url = "https://appleid.apple.com/auth/authorize" |
| 31 |
public_key_url = "https://appleid.apple.com/auth/keys" |
| 32 |
|
| 33 |
@classmethod |
| 34 |
def get_verified_identity_data(cls, provider, id_token): |
| 35 |
data = jwtkit.verify_and_decode( |
| 36 |
credential=id_token, |
| 37 |
keys_url=cls.public_key_url, |
| 38 |
issuer="https://appleid.apple.com", |
| 39 |
audience=provider.get_auds(), |
| 40 |
lookup_kid=jwtkit.lookup_kid_jwk, |
| 41 |
) |
| 42 |
return data |
| 43 |
|
| 44 |
def parse_token(self, data): |
| 45 |
token = SocialToken( |
| 46 |
token=data["access_token"], |
| 47 |
) |
| 48 |
token.token_secret = data.get("refresh_token", "") |
| 49 |
|
| 50 |
expires_in = data.get(self.expires_in_key) |
| 51 |
if expires_in: |
| 52 |
token.expires_at = timezone.now() + timedelta(seconds=int(expires_in)) |
| 53 |
|
| 54 |
# `user_data` is a big flat dictionary with the parsed JWT claims |
| 55 |
# access_tokens, and user info from the apple post. |
| 56 |
identity_data = AppleOAuth2Adapter.get_verified_identity_data( |
| 57 |
self.get_provider(), data["id_token"] |
| 58 |
) |
| 59 |
token.user_data = {**data, **identity_data} |
| 60 |
|
| 61 |
return token |
| 62 |
|
| 63 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 64 |
extra_data = token.user_data |
| 65 |
login = self.get_provider().sociallogin_from_response( |
| 66 |
request=request, response=extra_data |
| 67 |
) |
| 68 |
login.state["id_token"] = token.user_data |
| 69 |
|
| 70 |
# We can safely remove the apple login session now |
| 71 |
# Note: The cookie will remain, but it's set to delete on browser close |
| 72 |
get_apple_session(request).delete() |
| 73 |
return login |
| 74 |
|
| 75 |
def get_user_scope_data(self, request: HttpRequest): |
| 76 |
user_scope_data = request.apple_login_session.get( # type:ignore[attr-defined] |
| 77 |
"user", |
| 78 |
"", |
| 79 |
) |
| 80 |
try: |
| 81 |
return json.loads(user_scope_data) |
| 82 |
except json.JSONDecodeError: |
| 83 |
# We do not care much about user scope data as it maybe blank |
| 84 |
# so return blank dictionary instead |
| 85 |
return {} |
| 86 |
|
| 87 |
def get_access_token_data( |
| 88 |
self, request: HttpRequest, app, client, pkce_code_verifier=None |
| 89 |
): |
| 90 |
"""We need to gather the info from the apple specific login""" |
| 91 |
apple_session = get_apple_session(request) |
| 92 |
|
| 93 |
# Exchange `code` |
| 94 |
code = get_request_param(request, "code") |
| 95 |
access_token_data = client.get_access_token( |
| 96 |
code, pkce_code_verifier=pkce_code_verifier |
| 97 |
) |
| 98 |
|
| 99 |
id_token = access_token_data.get("id_token", None) |
| 100 |
# In case of missing id_token in access_token_data |
| 101 |
if id_token is None: |
| 102 |
id_token = apple_session.store.get("id_token") |
| 103 |
|
| 104 |
return { |
| 105 |
**access_token_data, |
| 106 |
**self.get_user_scope_data(request), |
| 107 |
"id_token": id_token, |
| 108 |
} |
| 109 |
|
| 110 |
|
| 111 |
@csrf_exempt |
| 112 |
@login_not_required |
| 113 |
def apple_post_callback( |
| 114 |
request: HttpRequest, finish_endpoint_name="apple_finish_callback" |
| 115 |
): |
| 116 |
""" |
| 117 |
Apple uses a `form_post` response type, which due to |
| 118 |
CORS/Samesite-cookie rules means this request cannot access |
| 119 |
the request since the session cookie is unavailable. |
| 120 |
|
| 121 |
We work around this by storing the apple response in a |
| 122 |
separate, temporary session and redirecting to a more normal |
| 123 |
oauth flow. |
| 124 |
|
| 125 |
args: |
| 126 |
finish_endpoint_name (str): The name of a defined URL, which can be |
| 127 |
overridden in your url configuration if you have more than one |
| 128 |
callback endpoint. |
| 129 |
""" |
| 130 |
if request.method != "POST": |
| 131 |
return HttpResponseNotAllowed(["POST"]) |
| 132 |
apple_session = get_apple_session(request) |
| 133 |
|
| 134 |
# Add regular OAuth2 params to the URL - reduces the overrides required |
| 135 |
keys_to_put_in_url = ["code", "state", "error"] |
| 136 |
url_params = {} |
| 137 |
for key in keys_to_put_in_url: |
| 138 |
value = get_request_param(request, key, "") |
| 139 |
if value: |
| 140 |
url_params[key] = value |
| 141 |
|
| 142 |
# Add other params to the apple_login_session |
| 143 |
keys_to_save_to_session = ["user", "id_token"] |
| 144 |
for key in keys_to_save_to_session: |
| 145 |
apple_session.store[key] = get_request_param(request, key, "") |
| 146 |
|
| 147 |
url = build_absolute_uri(request, reverse(finish_endpoint_name)) |
| 148 |
response = HttpResponseRedirect(f"{url}?{urlencode(url_params)}") |
| 149 |
apple_session.save(response) |
| 150 |
return response |
| 151 |
|
| 152 |
|
| 153 |
oauth2_login = OAuth2LoginView.adapter_view(AppleOAuth2Adapter) |
| 154 |
oauth2_callback = apple_post_callback |
| 155 |
oauth2_finish_login = OAuth2CallbackView.adapter_view(AppleOAuth2Adapter) |