Debian Codegraph @

allauth/headless/account/inputs.py

raw
1 from __future__ import annotations
2
3 from django.core.exceptions import ValidationError
4 from django.core.validators import validate_email
5
6 from allauth.account import app_settings as account_settings
7 from allauth.account.adapter import get_adapter as get_account_adapter
8 from allauth.account.fields import PhoneField
9 from allauth.account.forms import (
10 AddEmailForm,
11 BaseSignupForm,
12 ChangeEmailForm,
13 ChangePhoneForm,
14 ConfirmLoginCodeForm,
15 ReauthenticateForm,
16 RequestLoginCodeForm,
17 ResetPasswordForm,
18 UserTokenForm,
19 VerifyPhoneForm,
20 )
21 from allauth.account.internal import flows
22 from allauth.account.models import EmailAddress, Login, get_emailconfirmation_model
23 from allauth.core import context
24 from allauth.core.internal.cryptokit import compare_user_code
25 from allauth.headless.adapter import get_adapter
26 from allauth.headless.internal.restkit import inputs
27
28
29 class SignupInput(BaseSignupForm, inputs.Input):
30 password = inputs.CharField()
31
32 def __init__(self, *args, **kwargs) -> None:
33 super().__init__(*args, **kwargs)
34 password = account_settings.SIGNUP_FIELDS.get("password1")
35 if not password:
36 del self.fields["password"]
37 else:
38 self.fields["password"].required = password["required"]
39
40 def clean_password(self):
41 password = self.cleaned_data["password"]
42 if password:
43 return get_account_adapter().clean_password(password)
44 return password
45
46
47 class LoginInput(inputs.Input):
48 username = inputs.CharField(required=False)
49 email = inputs.EmailField(required=False)
50 # NOTE: Always require E164, no need to use adapter.phone_form_field
51 phone = PhoneField(required=False)
52 password = inputs.CharField()
53
54 def __init__(self, *args, **kwargs) -> None:
55 super().__init__(*args, **kwargs)
56 for field in ["username", "email", "phone"]:
57 if field not in account_settings.LOGIN_METHODS:
58 del self.fields[field]
59 if len(account_settings.LOGIN_METHODS) == 1:
60 self.fields[next(iter(account_settings.LOGIN_METHODS))].required = True
61
62 def clean(self):
63 cleaned_data = super().clean()
64 if self.errors:
65 return cleaned_data
66 credentials = {}
67 for login_method in account_settings.LOGIN_METHODS:
68 value = cleaned_data.get(login_method)
69 if value is not None and login_method in self.data.keys():
70 credentials[login_method] = value
71 if len(credentials) != 1:
72 raise get_account_adapter().validation_error("invalid_login")
73 password = cleaned_data.get("password")
74 if password:
75 auth_method = next(iter(credentials.keys()))
76 credentials["password"] = password
77 user = get_account_adapter().authenticate(context.request, **credentials)
78 if user:
79 self.login = Login(user=user, email=credentials.get("email"))
80 if flows.login.is_login_rate_limited(context.request, self.login):
81 raise get_account_adapter().validation_error(
82 "too_many_login_attempts"
83 )
84 else:
85 error_code = f"{auth_method.value}_password_mismatch"
86 self.add_error(
87 "password", get_account_adapter().validation_error(error_code)
88 )
89 return cleaned_data
90
91
92 class VerifyEmailInput(inputs.Input):
93 key = inputs.CharField()
94
95 def __init__(self, *args, **kwargs) -> None:
96 self.process = kwargs.pop("process", None)
97 super().__init__(*args, **kwargs)
98
99 def clean_key(self):
100 key = self.cleaned_data["key"]
101 if self.process:
102 if not compare_user_code(actual=key, expected=self.process.code):
103 raise get_account_adapter().validation_error("incorrect_code")
104 valid = True
105 email_address = self.process.email_address
106 else:
107 model = get_emailconfirmation_model()
108 verification = model.from_key(key)
109 valid = verification and not verification.key_expired()
110 if not valid:
111 raise get_account_adapter().validation_error(
112 "incorrect_code"
113 if account_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED
114 else "invalid_or_expired_key"
115 )
116 email_address = verification.email_address
117 self.verification = verification
118 if valid and not email_address.can_set_verified():
119 raise get_account_adapter().validation_error("email_taken")
120 return key
121
122
123 class RequestPasswordResetInput(ResetPasswordForm, inputs.Input):
124 pass
125
126
127 class ResetPasswordKeyInput(inputs.Input):
128 key = inputs.CharField()
129
130 def __init__(self, *args, **kwargs) -> None:
131 self.user = kwargs.pop("user", None)
132 self.code = kwargs.pop("code", None)
133 super().__init__(*args, **kwargs)
134
135 def clean_key(self):
136 if account_settings.PASSWORD_RESET_BY_CODE_ENABLED:
137 return self._clean_key_code()
138 else:
139 return self._clean_key_link()
140
141 def _clean_key_code(self):
142 key = self.cleaned_data["key"]
143 if not compare_user_code(actual=key, expected=self.code):
144 raise get_account_adapter().validation_error("incorrect_code")
145 return key
146
147 def _clean_key_link(self):
148 key = self.cleaned_data["key"]
149 uidb36, _, subkey = key.partition("-")
150 token_form = UserTokenForm(data={"uidb36": uidb36, "key": subkey})
151 if not token_form.is_valid():
152 raise get_account_adapter().validation_error("invalid_password_reset")
153 self.user = token_form.reset_user
154 return key
155
156
157 class ResetPasswordInput(ResetPasswordKeyInput):
158 password = inputs.CharField()
159
160 def clean(self):
161 cleaned_data = super().clean()
162 password = self.cleaned_data.get("password")
163 if self.user and password is not None:
164 try:
165 get_account_adapter().clean_password(password, user=self.user)
166 except ValidationError as e:
167 self.add_error("password", e)
168 return cleaned_data
169
170
171 class ChangePasswordInput(inputs.Input):
172 current_password = inputs.CharField(required=False)
173 new_password = inputs.CharField()
174
175 def __init__(self, *args, **kwargs) -> None:
176 self.user = kwargs.pop("user")
177 super().__init__(*args, **kwargs)
178 self.fields["current_password"].required = self.user.has_usable_password()
179
180 def clean_current_password(self):
181 current_password = self.cleaned_data["current_password"]
182 if current_password:
183 if not self.user.check_password(current_password):
184 raise get_account_adapter().validation_error("enter_current_password")
185 return current_password
186
187 def clean_new_password(self):
188 new_password = self.cleaned_data["new_password"]
189 adapter = get_account_adapter()
190 return adapter.clean_password(new_password, user=self.user)
191
192
193 class AddEmailInput(AddEmailForm, inputs.Input):
194 pass
195
196
197 class SelectEmailInput(inputs.Input):
198 email = inputs.CharField()
199
200 def __init__(self, *args, **kwargs) -> None:
201 self.user = kwargs.pop("user")
202 super().__init__(*args, **kwargs)
203
204 def clean_email(self):
205 self.process = None
206 email = self.cleaned_data["email"]
207 validate_email(email)
208
209 # Select a database backed email...
210 try:
211 return EmailAddress.objects.get_for_user(user=self.user, email=email)
212 except EmailAddress.DoesNotExist:
213 pass
214
215 # Or, if email verification by code is active, try the pending email
216 request = context.request
217 self.process = flows.email_verification_by_code.EmailVerificationProcess.resume(
218 request
219 )
220 if self.process:
221 email_address = self.process.email_address
222 if email_address.email.lower() == email.lower() and (
223 request.user.is_anonymous or email_address.user_id == request.user.pk
224 ):
225 return email_address
226
227 raise get_adapter().validation_error("unknown_email")
228
229
230 class DeleteEmailInput(SelectEmailInput):
231 def clean_email(self):
232 email = super().clean_email()
233 if not flows.manage_email.can_delete_email(email):
234 raise get_account_adapter().validation_error("cannot_remove_primary_email")
235 return email
236
237
238 class MarkAsPrimaryEmailInput(SelectEmailInput):
239 primary = inputs.BooleanField(required=True)
240
241 def clean_email(self):
242 email = super().clean_email()
243 if not flows.manage_email.can_mark_as_primary(email):
244 raise get_account_adapter().validation_error("unverified_primary_email")
245 return email
246
247
248 class ResendEmailVerificationInput(SelectEmailInput):
249 pass
250
251
252 class ReauthenticateInput(ReauthenticateForm, inputs.Input):
253 pass
254
255
256 class RequestLoginCodeInput(RequestLoginCodeForm, inputs.Input):
257 pass
258
259
260 class ConfirmLoginCodeInput(ConfirmLoginCodeForm, inputs.Input):
261 pass
262
263
264 class VerifyPhoneInput(VerifyPhoneForm, inputs.Input):
265 pass
266
267
268 class ChangePhoneInput(ChangePhoneForm, inputs.Input):
269 pass
270
271
272 class ChangeEmailInput(ChangeEmailForm, inputs.Input):
273 pass