Debian Codegraph @

allauth/idp/oidc/internal/oauthlib/authorization_codes.py

raw
1 from __future__ import annotations
2
3 from typing import Any
4
5 from django.core.cache import cache
6
7 from oauthlib.common import Request
8
9 from allauth.account.models import EmailAddress
10 from allauth.idp.oidc import app_settings
11 from allauth.idp.oidc.adapter import get_adapter
12 from allauth.idp.oidc.internal.oauthlib.utils import get_validator_context
13 from allauth.idp.oidc.models import Client
14
15
16 def cache_key(client_id: str, code: str) -> str:
17 return f"allauth.idp.oidc.authorization_code[{client_id}:{code}]"
18
19
20 def create(client: Client, code: dict[str, Any], request: Request) -> None:
21 adapter = get_adapter()
22 ctx = get_validator_context()
23 authorization_code = {
24 "code": code,
25 "client_id": client.id,
26 "redirect_uri": request.redirect_uri,
27 "sub": adapter.get_user_sub(client, request.user),
28 "scopes": request.scopes,
29 "claims": request.claims,
30 "resources": ctx.requested_resources,
31 }
32 if email := ctx.email:
33 # Don't trouble ourselves with keeping track a specific email in case
34 # the primary was chosen.
35 if EmailAddress.objects.get_primary_email(request.user) != email.lower():
36 authorization_code["email"] = email
37 code_challenge = getattr(request, "code_challenge", None)
38 if code_challenge:
39 authorization_code["pkce"] = {
40 "code_challenge": code_challenge,
41 "code_challenge_method": request.code_challenge_method,
42 }
43 cache.set(
44 cache_key(client.id, code["code"]),
45 authorization_code,
46 timeout=app_settings.AUTHORIZATION_CODE_EXPIRES_IN,
47 )
48
49
50 def lookup(client_id: str, code: str) -> dict[str, Any] | None:
51 return cache.get(cache_key(client_id, code))
52
53
54 def invalidate(client_id: str, code: str) -> None:
55 cache.delete(cache_key(client_id, code))
56
57
58 def validate(client_id: str, code: str, request: Request) -> bool:
59 ctx = get_validator_context()
60 authorization_code = lookup(client_id, code)
61 if not authorization_code:
62 return False
63 user = get_adapter().get_user_by_sub(request.client, authorization_code["sub"])
64 if not user:
65 return False
66 request.scopes = authorization_code["scopes"]
67 ctx.granted_resources = authorization_code["resources"]
68 request.user = user
69 pkce = authorization_code.get("pkce")
70 if pkce:
71 request.code_challenge = pkce["code_challenge"]
72 request.code_challenge_method = pkce["code_challenge_method"]
73 request.claims = authorization_code["claims"]
74 ctx.email = authorization_code.get("email")
75 return True