| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Any |
| 4 |
|
| 5 |
from django import forms |
| 6 |
from django.core.exceptions import ValidationError |
| 7 |
from django.forms import widgets |
| 8 |
from django.utils.translation import gettext as _ |
| 9 |
|
| 10 |
from allauth.account.adapter import get_adapter as get_account_adapter |
| 11 |
from allauth.account.models import EmailAddress |
| 12 |
from allauth.core import context |
| 13 |
from allauth.core.internal import ratelimit |
| 14 |
from allauth.idp.oidc import app_settings |
| 15 |
from allauth.idp.oidc.adapter import get_adapter |
| 16 |
from allauth.idp.oidc.internal.clientkit import ( |
| 17 |
clean_post_logout_redirect_uri, |
| 18 |
lookup_client, |
| 19 |
) |
| 20 |
from allauth.idp.oidc.internal.oauthlib import device_codes |
| 21 |
from allauth.idp.oidc.internal.tokens import decode_jwt_token |
| 22 |
from allauth.idp.oidc.models import Client |
| 23 |
|
| 24 |
|
| 25 |
class AuthorizationForm(forms.Form): |
| 26 |
request = forms.CharField(widget=widgets.HiddenInput) |
| 27 |
|
| 28 |
def __init__(self, *args, **kwargs) -> None: |
| 29 |
user = kwargs.pop("user") |
| 30 |
requested_scopes = kwargs.pop("requested_scopes") |
| 31 |
super().__init__(*args, **kwargs) |
| 32 |
adapter = get_adapter() |
| 33 |
choices = [(rs, adapter.scope_display.get(rs, rs)) for rs in requested_scopes] |
| 34 |
choices = sorted(choices, key=lambda ch: ch[1]) |
| 35 |
self.fields["scopes"] = forms.MultipleChoiceField( |
| 36 |
choices=choices, |
| 37 |
label=_("Grant permissions"), |
| 38 |
widget=forms.CheckboxSelectMultiple, |
| 39 |
initial=requested_scopes, |
| 40 |
required=True, |
| 41 |
) |
| 42 |
emails = list( |
| 43 |
EmailAddress.objects.filter(user=user, verified=True) |
| 44 |
.order_by("-primary", "email") |
| 45 |
.values_list("email", flat=True) |
| 46 |
) |
| 47 |
if "email" in requested_scopes and len(emails) > 1: |
| 48 |
self.fields["email"] = forms.ChoiceField( |
| 49 |
label=_("Email"), |
| 50 |
choices=[(email, email) for email in emails], |
| 51 |
required=False, |
| 52 |
) |
| 53 |
|
| 54 |
|
| 55 |
class ConfirmCodeForm(forms.Form): |
| 56 |
code = forms.CharField( |
| 57 |
label=_("Code"), |
| 58 |
required=True, |
| 59 |
widget=forms.TextInput( |
| 60 |
attrs={"placeholder": _("Code"), "autocomplete": "one-time-code"}, |
| 61 |
), |
| 62 |
) |
| 63 |
|
| 64 |
def __init__(self, *args, **kwargs) -> None: |
| 65 |
self.code = kwargs.pop("code", None) |
| 66 |
super().__init__(*args, **kwargs) |
| 67 |
|
| 68 |
def clean_code(self) -> str: |
| 69 |
code = self.cleaned_data["code"] |
| 70 |
if not ratelimit.consume( |
| 71 |
context.request, |
| 72 |
action="device_user_code", |
| 73 |
config=app_settings.RATE_LIMITS, |
| 74 |
limit_get=True, |
| 75 |
): |
| 76 |
raise get_account_adapter().validation_error("rate_limited") |
| 77 |
|
| 78 |
self.device_code, self.client = device_codes.validate_user_code(code) |
| 79 |
return code |
| 80 |
|
| 81 |
|
| 82 |
class DeviceAuthorizationForm(forms.Form): |
| 83 |
action = forms.CharField(required=False) |
| 84 |
|
| 85 |
|
| 86 |
class RPInitiatedLogoutForm(forms.Form): |
| 87 |
""" |
| 88 |
We don't throw validation errors in case of wrong inputs: |
| 89 |
|
| 90 |
> If any of the validation procedures defined in this specification fail, |
| 91 |
> any operations requiring the information that failed to correctly validate |
| 92 |
> MUST be aborted and the information that failed to validate MUST NOT be |
| 93 |
> used. |
| 94 |
|
| 95 |
""" |
| 96 |
|
| 97 |
action = forms.CharField(required=False, widget=forms.HiddenInput) |
| 98 |
|
| 99 |
# RECOMMENDED. ID Token previously issued by the OP to the RP passed to the |
| 100 |
# Logout Endpoint as a hint about the End-User's current authenticated |
| 101 |
# session with the Client. This is used as an indication of the identity of |
| 102 |
# the End-User that the RP is requesting be logged out by the OP. |
| 103 |
id_token_hint = forms.CharField(required=False, widget=forms.HiddenInput) |
| 104 |
|
| 105 |
# OPTIONAL. Hint to the Authorization Server about the End-User that is |
| 106 |
# logging out. The value and meaning of this parameter is left up to the |
| 107 |
# OP's discretion. For instance, the value might contain an email address, |
| 108 |
# phone number, username, or session identifier pertaining to the RP's |
| 109 |
# session with the OP for the End-User. |
| 110 |
logout_hint = forms.CharField(required=False, widget=forms.HiddenInput) |
| 111 |
|
| 112 |
# OPTIONAL. OAuth 2.0 Client Identifier valid at the Authorization |
| 113 |
# Server. When both client_id and id_token_hint are present, the OP MUST |
| 114 |
# verify that the Client Identifier matches the one used when issuing the ID |
| 115 |
# Token. The most common use case for this parameter is to specify the |
| 116 |
# Client Identifier when post_logout_redirect_uri is used but id_token_hint |
| 117 |
# is not. Another use is for symmetrically encrypted ID Tokens used as |
| 118 |
# id_token_hint values that require the Client Identifier to be specified by |
| 119 |
# other means, so that the ID Tokens can be decrypted by the OP. |
| 120 |
client_id = forms.CharField(required=False, widget=forms.HiddenInput) |
| 121 |
|
| 122 |
# OPTIONAL. URI to which the RP is requesting that the End-User's User Agent |
| 123 |
# be redirected after a logout has been performed. |
| 124 |
post_logout_redirect_uri = forms.CharField(required=False, widget=forms.HiddenInput) |
| 125 |
|
| 126 |
# OPTIONAL. Opaque value used by the RP to maintain state between the logout |
| 127 |
# request and the callback to the endpoint specified by the |
| 128 |
# post_logout_redirect_uri parameter. If included in the logout request, the |
| 129 |
# OP passes this value back to the RP using the state parameter when |
| 130 |
# redirecting the User Agent back to the RP. |
| 131 |
state = forms.CharField(required=False, widget=forms.HiddenInput) |
| 132 |
|
| 133 |
# End-User's preferred languages and scripts for the user interface, |
| 134 |
# represented as a space-separated list of BCP47 [RFC5646] language tag |
| 135 |
# values, ordered by preference. For instance, the value "fr-CA fr en" |
| 136 |
# represents a preference for French as spoken in Canada, then French |
| 137 |
# (without a region designation), followed by English (without a region |
| 138 |
# designation). An error SHOULD NOT result if some or all of the requested |
| 139 |
# locales are not supported by the OpenID Provider. |
| 140 |
ui_locales = forms.CharField(required=False, widget=forms.HiddenInput) |
| 141 |
|
| 142 |
def clean_id_token_hint(self) -> dict | None: |
| 143 |
value = self.cleaned_data["id_token_hint"] |
| 144 |
if not value: |
| 145 |
return None |
| 146 |
payload = decode_jwt_token(value, verify_exp=False, verify_iss=True) |
| 147 |
return payload |
| 148 |
|
| 149 |
def clean(self) -> dict[str, Any] | None: |
| 150 |
cleaned_data = super().clean() |
| 151 |
if not cleaned_data: |
| 152 |
return cleaned_data |
| 153 |
post_logout_redirect_uri = cleaned_data.get("post_logout_redirect_uri") |
| 154 |
|
| 155 |
client: Client | None = None |
| 156 |
client_id = cleaned_data.get("client_id") |
| 157 |
id_token_hint = cleaned_data.get("id_token_hint") |
| 158 |
aud: str | None = None |
| 159 |
if id_token_hint: |
| 160 |
aud = id_token_hint.get("aud") |
| 161 |
if aud and client_id and aud != client_id: |
| 162 |
# aud doesn't match client_id, don't trust any of these. |
| 163 |
id_token_hint = cleaned_data["id_token_hint"] = None |
| 164 |
client_id = cleaned_data["client_id"] = None |
| 165 |
aud = None |
| 166 |
elif aud and not client_id: |
| 167 |
client_id = aud |
| 168 |
|
| 169 |
if client_id: |
| 170 |
client = lookup_client(client_id) |
| 171 |
if not client: |
| 172 |
# Wipe invalid inputs. |
| 173 |
client_id = cleaned_data["client_id"] = None |
| 174 |
if aud: |
| 175 |
id_token_hint = cleaned_data["id_token_hint"] = None |
| 176 |
|
| 177 |
try: |
| 178 |
cleaned_data["post_logout_redirect_uri"] = clean_post_logout_redirect_uri( |
| 179 |
post_logout_redirect_uri, client |
| 180 |
) |
| 181 |
except ValidationError as e: |
| 182 |
self.add_error("post_logout_redirect_uri", e) |
| 183 |
cleaned_data["client"] = client |
| 184 |
return cleaned_data |
| 185 |
|
| 186 |
|
| 187 |
class ClientRegistrationForm(forms.Form): |
| 188 |
client_name = Client._meta.get_field("name").formfield(required=False) |
| 189 |
redirect_uris = forms.JSONField(required=True) |
| 190 |
post_logout_redirect_uris = forms.JSONField(required=False) |
| 191 |
grant_types = forms.JSONField(required=False) |
| 192 |
response_types = forms.JSONField(required=False) |
| 193 |
token_endpoint_auth_method = forms.CharField(required=False) |
| 194 |
scope = forms.CharField(required=False) |
| 195 |
|
| 196 |
def clean_client_name(self) -> str: |
| 197 |
value = self.cleaned_data.get("client_name") or "" |
| 198 |
if "<" in value or ">" in value: |
| 199 |
raise forms.ValidationError("Client name must not contain '<' or '>'.") |
| 200 |
return value.strip() |
| 201 |
|
| 202 |
def _clean_string_list(self, field_name: str) -> list[str]: |
| 203 |
value = self.cleaned_data.get(field_name) |
| 204 |
if value is None: |
| 205 |
return [] |
| 206 |
if not isinstance(value, list) or not all( |
| 207 |
isinstance(item, str) for item in value |
| 208 |
): |
| 209 |
raise forms.ValidationError(f"{field_name} must be an array of strings.") |
| 210 |
return value |
| 211 |
|
| 212 |
def clean_redirect_uris(self) -> list[str]: |
| 213 |
uris = self._clean_string_list("redirect_uris") |
| 214 |
if not uris: |
| 215 |
raise forms.ValidationError( |
| 216 |
"redirect_uris is required and must be a non-empty array." |
| 217 |
) |
| 218 |
return uris |
| 219 |
|
| 220 |
def clean_post_logout_redirect_uris(self) -> list[str]: |
| 221 |
return self._clean_string_list("post_logout_redirect_uris") |
| 222 |
|
| 223 |
def clean_grant_types(self) -> list[str]: |
| 224 |
grant_types = self._clean_string_list("grant_types") or ["authorization_code"] |
| 225 |
valid = {gt.value for gt in Client.GrantType} |
| 226 |
invalid = set(grant_types) - valid |
| 227 |
if invalid: |
| 228 |
raise forms.ValidationError( |
| 229 |
f"Unsupported grant type(s): {', '.join(sorted(invalid))}" |
| 230 |
) |
| 231 |
return grant_types |
| 232 |
|
| 233 |
def clean_response_types(self) -> list[str]: |
| 234 |
response_types = self._clean_string_list("response_types") or ["code"] |
| 235 |
valid = {rt.value for rt in Client.ResponseType} |
| 236 |
invalid = set(response_types) - valid |
| 237 |
if invalid: |
| 238 |
raise forms.ValidationError( |
| 239 |
f"Unsupported response type(s): {', '.join(sorted(invalid))}" |
| 240 |
) |
| 241 |
return response_types |
| 242 |
|
| 243 |
def clean_scope(self) -> list[str]: |
| 244 |
value = self.cleaned_data.get("scope", "") |
| 245 |
if isinstance(value, str): |
| 246 |
scopes = value.split() |
| 247 |
elif isinstance(value, (list, tuple)): |
| 248 |
scopes = [str(s).strip() for s in value] |
| 249 |
else: |
| 250 |
scopes = [] |
| 251 |
return scopes or ["openid"] |
| 252 |
|
| 253 |
def clean_token_endpoint_auth_method(self) -> str: |
| 254 |
# If unspecified or omitted, the default is "client_secret_basic", |
| 255 |
# denoting the HTTP Basic authentication scheme as specified in Section |
| 256 |
# 2.3.1 of OAuth 2.0 |
| 257 |
value = ( |
| 258 |
self.cleaned_data.get("token_endpoint_auth_method") |
| 259 |
or Client.AuthenticationMethod.CLIENT_SECRET_BASIC |
| 260 |
) |
| 261 |
valid = {am.value for am in Client.AuthenticationMethod} |
| 262 |
if value not in valid: |
| 263 |
raise forms.ValidationError( |
| 264 |
f"Unsupported token endpoint auth method: {value}" |
| 265 |
) |
| 266 |
return value |
| 267 |
|
| 268 |
def save(self, commit: bool = True) -> Client: |
| 269 |
data = self.cleaned_data |
| 270 |
kwargs = { |
| 271 |
"name": data["client_name"], |
| 272 |
"type": ( |
| 273 |
Client.Type.PUBLIC |
| 274 |
if data["token_endpoint_auth_method"] |
| 275 |
== Client.AuthenticationMethod.NONE |
| 276 |
else Client.Type.CONFIDENTIAL |
| 277 |
), |
| 278 |
} |
| 279 |
client = Client(**kwargs) |
| 280 |
client.set_grant_types(data["grant_types"]) |
| 281 |
client.set_response_types(data["response_types"]) |
| 282 |
client.set_scopes(data["scope"]) |
| 283 |
client.set_redirect_uris(data["redirect_uris"]) |
| 284 |
if commit: |
| 285 |
client.save() |
| 286 |
return client |