| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import time |
| 4 |
from http import HTTPStatus |
| 5 |
from urllib.parse import parse_qsl, quote, urlencode |
| 6 |
|
| 7 |
from django.core.exceptions import ImproperlyConfigured |
| 8 |
|
| 9 |
from allauth.core.internal.deferred import jwt |
| 10 |
from allauth.socialaccount.adapter import get_adapter |
| 11 |
from allauth.socialaccount.providers.oauth2.client import OAuth2Client, OAuth2Error |
| 12 |
|
| 13 |
|
| 14 |
def jwt_encode(*args, **kwargs): |
| 15 |
resp = jwt.encode(*args, **kwargs) |
| 16 |
if isinstance(resp, bytes): |
| 17 |
# For PyJWT <2 |
| 18 |
resp = resp.decode("utf-8") |
| 19 |
return resp |
| 20 |
|
| 21 |
|
| 22 |
class Scope: |
| 23 |
EMAIL = "email" |
| 24 |
NAME = "name" |
| 25 |
|
| 26 |
|
| 27 |
class AppleOAuth2Client(OAuth2Client): |
| 28 |
""" |
| 29 |
Custom client because `Sign In With Apple`: |
| 30 |
* requires `response_mode` field in redirect_url |
| 31 |
* requires special `client_secret` as JWT |
| 32 |
""" |
| 33 |
|
| 34 |
def generate_client_secret(self) -> str: |
| 35 |
"""Create a JWT signed with an apple provided private key""" |
| 36 |
now = int(time.time()) |
| 37 |
app = get_adapter(self.request).get_app(self.request, "apple") |
| 38 |
if not app.key: |
| 39 |
raise ImproperlyConfigured("Apple 'key' missing") |
| 40 |
certificate_key = app.settings.get("certificate_key") |
| 41 |
if not certificate_key: |
| 42 |
raise ImproperlyConfigured("Apple 'certificate_key' missing") |
| 43 |
claims = { |
| 44 |
"iss": app.key, |
| 45 |
"aud": "https://appleid.apple.com", |
| 46 |
"sub": self.get_client_id(), |
| 47 |
"iat": now, |
| 48 |
"exp": now + 60 * 60, |
| 49 |
} |
| 50 |
headers = {"kid": self.consumer_secret, "alg": "ES256"} |
| 51 |
client_secret = jwt_encode( |
| 52 |
payload=claims, key=certificate_key, algorithm="ES256", headers=headers |
| 53 |
) |
| 54 |
return client_secret |
| 55 |
|
| 56 |
def get_client_id(self) -> str: |
| 57 |
"""We support multiple client_ids, but use the first one for api calls""" |
| 58 |
return self.consumer_key.split(",")[0] |
| 59 |
|
| 60 |
def get_access_token(self, code, pkce_code_verifier=None): |
| 61 |
url = self.access_token_url |
| 62 |
client_secret = self.generate_client_secret() |
| 63 |
data = { |
| 64 |
"client_id": self.get_client_id(), |
| 65 |
"code": code, |
| 66 |
"grant_type": "authorization_code", |
| 67 |
"redirect_uri": self.callback_url, |
| 68 |
"client_secret": client_secret, |
| 69 |
} |
| 70 |
if pkce_code_verifier: |
| 71 |
data["code_verifier"] = pkce_code_verifier |
| 72 |
self._strip_empty_keys(data) |
| 73 |
with get_adapter().get_requests_session() as sess: |
| 74 |
resp = sess.request( |
| 75 |
self.access_token_method, url, data=data, headers=self.headers |
| 76 |
) |
| 77 |
access_token = None |
| 78 |
if resp.status_code in [HTTPStatus.OK, HTTPStatus.CREATED]: |
| 79 |
try: |
| 80 |
access_token = resp.json() |
| 81 |
except ValueError: |
| 82 |
access_token = dict(parse_qsl(resp.text)) |
| 83 |
if not access_token or "access_token" not in access_token: |
| 84 |
raise OAuth2Error(f"Error retrieving access token: {resp.content}") |
| 85 |
return access_token |
| 86 |
|
| 87 |
def get_redirect_url(self, authorization_url, scope, extra_params) -> str: |
| 88 |
scope = self.scope_delimiter.join(set(scope)) |
| 89 |
params = { |
| 90 |
"client_id": self.get_client_id(), |
| 91 |
"redirect_uri": self.callback_url, |
| 92 |
"response_mode": "form_post", |
| 93 |
"scope": scope, |
| 94 |
"response_type": "code id_token", |
| 95 |
} |
| 96 |
if self.state: |
| 97 |
params["state"] = self.state |
| 98 |
params.update(extra_params) |
| 99 |
return f"{authorization_url}?{urlencode(params, quote_via=quote)}" |