| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import hashlib |
| 4 |
import hmac |
| 5 |
from datetime import timedelta |
| 6 |
|
| 7 |
from django.core.cache import cache |
| 8 |
from django.http import HttpRequest |
| 9 |
from django.utils import timezone |
| 10 |
|
| 11 |
from allauth.socialaccount.adapter import get_adapter |
| 12 |
from allauth.socialaccount.internal import jwtkit |
| 13 |
from allauth.socialaccount.models import SocialLogin, SocialToken |
| 14 |
from allauth.socialaccount.providers.base import Provider |
| 15 |
from allauth.socialaccount.providers.facebook.constants import GRAPH_API_URL |
| 16 |
|
| 17 |
|
| 18 |
# maps fields from the Limited Login JWT to Graph API response fields |
| 19 |
JWT_FIELD_TO_GRAPH_API_FIELD_MAP = { |
| 20 |
"sub": "id", |
| 21 |
"email": "email", |
| 22 |
"given_name": "first_name", |
| 23 |
"family_name": "last_name", |
| 24 |
"name": "name", |
| 25 |
"user_link": "link", |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
def compute_appsecret_proof(app, token) -> str: |
| 30 |
# Generate an appsecret_proof parameter to secure the Graph API call |
| 31 |
# see https://developers.facebook.com/docs/graph-api/securing-requests |
| 32 |
msg = token.token.encode("utf-8") |
| 33 |
key = app.secret.encode("utf-8") |
| 34 |
appsecret_proof = hmac.new(key, msg, digestmod=hashlib.sha256).hexdigest() |
| 35 |
return appsecret_proof |
| 36 |
|
| 37 |
|
| 38 |
def complete_login(request: HttpRequest, provider, token): |
| 39 |
with get_adapter().get_requests_session() as sess: |
| 40 |
params = { |
| 41 |
"fields": ",".join(provider.get_fields()), |
| 42 |
"access_token": token.token, |
| 43 |
"appsecret_proof": compute_appsecret_proof(provider.app, token), |
| 44 |
} |
| 45 |
resp = sess.get(f"{GRAPH_API_URL}/me", params=params) |
| 46 |
resp.raise_for_status() |
| 47 |
extra_data = resp.json() |
| 48 |
return provider.sociallogin_from_response(request, extra_data) |
| 49 |
|
| 50 |
|
| 51 |
def get_app_token(provider): |
| 52 |
app = provider.app |
| 53 |
cache_key = f"allauth.facebook.app_token[{app.client_id}]" |
| 54 |
app_token = cache.get(cache_key) |
| 55 |
if not app_token: |
| 56 |
with get_adapter().get_requests_session() as sess: |
| 57 |
params = { |
| 58 |
"client_id": app.client_id, |
| 59 |
"client_secret": app.secret, |
| 60 |
"grant_type": "client_credentials", |
| 61 |
} |
| 62 |
resp = sess.get(f"{GRAPH_API_URL}/oauth/access_token", params=params) |
| 63 |
resp.raise_for_status() |
| 64 |
data = resp.json() |
| 65 |
app_token = data["access_token"] |
| 66 |
timeout = provider.get_settings().get("APP_TOKEN_CACHE_TIMEOUT", 300) |
| 67 |
cache.set(cache_key, app_token, timeout=timeout) |
| 68 |
return app_token |
| 69 |
|
| 70 |
|
| 71 |
def inspect_token(provider, input_token) -> None: |
| 72 |
app_token = get_app_token(provider) |
| 73 |
with get_adapter().get_requests_session() as sess: |
| 74 |
resp = sess.get( |
| 75 |
f"{GRAPH_API_URL}/debug_token", |
| 76 |
params={"input_token": input_token, "access_token": app_token}, |
| 77 |
) |
| 78 |
resp.raise_for_status() |
| 79 |
data = resp.json()["data"] |
| 80 |
if not data["is_valid"]: |
| 81 |
raise get_adapter().validation_error("invalid_token") |
| 82 |
if data["app_id"] != provider.app.client_id or not data["is_valid"]: |
| 83 |
raise get_adapter().validation_error("invalid_token") |
| 84 |
|
| 85 |
|
| 86 |
def verify_token( |
| 87 |
request: HttpRequest, |
| 88 |
provider: Provider, |
| 89 |
access_token: str, |
| 90 |
auth_type: str = "", |
| 91 |
auth_nonce: str = "", |
| 92 |
) -> SocialLogin: |
| 93 |
app = provider.app |
| 94 |
inspect_token(provider, access_token) |
| 95 |
expires_at = None |
| 96 |
with get_adapter().get_requests_session() as sess: |
| 97 |
if auth_type == "reauthenticate": |
| 98 |
resp = sess.get( |
| 99 |
f"{GRAPH_API_URL}/oauth/access_token_info", |
| 100 |
params={ |
| 101 |
"client_id": app.client_id, |
| 102 |
"access_token": access_token, |
| 103 |
}, |
| 104 |
) |
| 105 |
resp.raise_for_status() |
| 106 |
info = resp.json() |
| 107 |
ok = auth_nonce and auth_nonce == info.get("auth_nonce") |
| 108 |
if not ok: |
| 109 |
raise get_adapter().validation_error("invalid_token") |
| 110 |
|
| 111 |
if provider.get_settings().get("EXCHANGE_TOKEN"): |
| 112 |
resp = sess.get( |
| 113 |
f"{GRAPH_API_URL}/oauth/access_token", |
| 114 |
params={ |
| 115 |
"grant_type": "fb_exchange_token", |
| 116 |
"client_id": app.client_id, |
| 117 |
"client_secret": app.secret, |
| 118 |
"fb_exchange_token": access_token, |
| 119 |
}, |
| 120 |
) |
| 121 |
resp.raise_for_status() |
| 122 |
info = resp.json() |
| 123 |
access_token = info["access_token"] |
| 124 |
expires_in = info.get("expires_in") |
| 125 |
if expires_in: |
| 126 |
expires_at = timezone.now() + timedelta(seconds=int(expires_in)) |
| 127 |
|
| 128 |
token = SocialToken(app=app, token=access_token, expires_at=expires_at) |
| 129 |
login = complete_login(request, provider, token) |
| 130 |
login.token = token |
| 131 |
return login |
| 132 |
|
| 133 |
|
| 134 |
def verify_limited_login_token( |
| 135 |
request: HttpRequest, provider, id_token: str |
| 136 |
) -> SocialLogin: |
| 137 |
""" |
| 138 |
Verifies a Facebook Limited Login token. |
| 139 |
See https://developers.facebook.com/docs/facebook-login/limited-login/token/validating. |
| 140 |
|
| 141 |
We validate the JWT, then convert its data/claims into |
| 142 |
a fake Facebook Graph API response, which is then passed to |
| 143 |
`provider.sociallogin_from_response` to be handled as normal. |
| 144 |
""" |
| 145 |
|
| 146 |
# note: this already does replay protection internally |
| 147 |
jwt_data = jwtkit.verify_and_decode( |
| 148 |
credential=id_token, |
| 149 |
keys_url=provider.limited_login_jwks_url, |
| 150 |
issuer=provider.limited_login_expected_jwt_issuer, |
| 151 |
audience=provider.app.client_id, |
| 152 |
lookup_kid=jwtkit.lookup_kid_jwk, |
| 153 |
) |
| 154 |
|
| 155 |
fake_response = { |
| 156 |
graph_field: jwt_data[jwt_field] |
| 157 |
for jwt_field, graph_field in JWT_FIELD_TO_GRAPH_API_FIELD_MAP.items() |
| 158 |
if jwt_field in jwt_data |
| 159 |
} |
| 160 |
|
| 161 |
return provider.sociallogin_from_response(request, fake_response) |