Debian Codegraph @

flask_security/forms.py

raw
1 """
2 flask_security.forms
3 ~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security forms module
6
7 :copyright: (c) 2012 by Matt Wright.
8 :copyright: (c) 2017 by CERN.
9 :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
10 :license: MIT, see LICENSE for more details.
11 """
12
13 from __future__ import annotations
14
15 import inspect
16 import typing as t
17
18 from flask import current_app, request
19 from flask_login import current_user
20 from flask_wtf import FlaskForm as BaseForm
21 from markupsafe import Markup
22 from wtforms import (
23 BooleanField,
24 EmailField,
25 Field,
26 HiddenField,
27 PasswordField,
28 RadioField,
29 StringField,
30 SubmitField,
31 TelField,
32 ValidationError,
33 )
34
35 from werkzeug.datastructures import MultiDict
36 from wtforms.validators import Optional, StopValidation, EqualTo, DataRequired, Length
37
38 from .babel import is_lazy_string, make_lazy_string
39 from .confirmable import requires_confirmation
40 from .mail_util import EmailValidateException
41 from .proxies import _security
42 from .utils import (
43 _,
44 _datastore,
45 _config_value as cv,
46 do_flash,
47 get_identity_attribute,
48 get_message,
49 hash_password,
50 localize_callback,
51 _suppress_form_csrf,
52 url_for_security,
53 validate_redirect_url,
54 verify_password,
55 )
56
57 if t.TYPE_CHECKING: # pragma: no cover
58 from flask_security import UserMixin
59 from .tokens import RefreshTokenErrors, RefreshTrackerMixin
60
61 # a bit of a hack - typing mixins isn't supported very well
62 # we can't just use the BaseForm as the subclass for ValidateMixin since
63 # it will cause errors at import time.
64 _FsFormBase: type[BaseForm] = BaseForm
65 else:
66 _FsFormBase = object
67
68 _default_field_labels = {
69 "authapp_method": _(
70 "Set up using an authenticator app (e.g. google, lastpass, authy)"
71 ),
72 "change_method": _("Change Method"),
73 "change_password": _("Change Password"),
74 "code": _("Authentication Code"),
75 "delete": _("Delete"),
76 "email": _("Email Address"),
77 "email_method": _("Set up using email"),
78 "error": _("Error(s)"),
79 "identity": _("Identity"),
80 "login": _("Login"),
81 "new_password": _("New Password"),
82 "passcode": _("Passcode"),
83 "password": _("Password"),
84 "phone": _("Phone Number"),
85 "recover_password": _("Recover Password"),
86 "recover_username": _("Recover Username"),
87 "register": _("Register"),
88 "remember_me": _("Remember Me"),
89 "reset_password": _("Reset Password"),
90 "retype_password": _("Retype Password"),
91 "send_confirmation": _("Resend Confirmation Instructions"),
92 "send_login_link": _("Send Login Link"),
93 "sendcode": _("Send Code"),
94 "signin": _("Sign In"),
95 "sms_method": _("Set up using SMS"),
96 "submit": _("Submit"),
97 "submitcode": _("Submit Code"),
98 "username": _("Username"),
99 "verify_password": _("Verify Password"),
100 }
101
102 # translated methods for two-factor and us-signin. keyed by form 'choices'
103 _setup_methods_xlate = {
104 "google_authenticator": _("Google Authenticator"),
105 "authenticator": _("authenticator"),
106 "email": _("email"),
107 "mail": _("email"),
108 "sms": _("SMS"),
109 "password": _("password"),
110 "webauthn": _("passkey"),
111 None: _("none"),
112 }
113
114
115 class ValidatorMixin(_FsFormBase):
116 """
117 This is called at import time - so there is no app context.
118 Validators have state - namely self.message - but we need that
119 xlated on a per-request basis. So we want a lazy_string - but we can't create
120 that until we are in an app context.
121 """
122
123 def __init__(self, *args: t.Any, **kwargs: t.Any):
124 # If the message is available from config[MSG_xx] then it can be xlated.
125 # Otherwise, it will be used as is.
126 self.message: str | None = None
127 self._original_message: str | None = None
128 if "message" in kwargs:
129 self._original_message = kwargs["message"]
130 del kwargs["message"]
131 super().__init__(*args, **kwargs)
132
133 def __call__(self, form: Form, field: Field) -> None:
134 if self._original_message and (
135 not is_lazy_string(self.message) and not self.message
136 ):
137 # Creat on first usage within app context.
138 msg = cv("MSG_" + self._original_message, strict=False)
139 if msg:
140 self.message = make_lazy_string(_local_xlate, msg[0])
141 else:
142 self.message = self._original_message
143 return super().__call__(form, field)
144
145
146 class EqualToLocalize(ValidatorMixin, EqualTo): # type: ignore[misc]
147 pass
148
149
150 class RequiredLocalize(ValidatorMixin, DataRequired): # type: ignore[misc]
151 pass
152
153
154 class LengthLocalize(ValidatorMixin, Length): # type: ignore[misc]
155 pass
156
157
158 class IsString(ValidatorMixin):
159 def __init__(self, *args: t.Any, **kwargs: t.Any):
160 if "message" not in kwargs:
161 kwargs["message"] = "API_ERROR"
162 super().__init__(*args, **kwargs)
163
164 def __call__(self, form: Form, field: Field) -> None:
165 # Skip None so this can be combined with Optional().
166 if field.data is not None and not isinstance(field.data, str):
167 assert self._original_message
168 raise StopValidation(get_message(self._original_message)[0])
169
170
171 # OTP/2FA code fields accept int,so these fields should use this validator
172 # instead of IsString()
173 class IsStringOrInt(ValidatorMixin):
174 def __init__(self, *args: t.Any, **kwargs: t.Any):
175 if "message" not in kwargs:
176 kwargs["message"] = "API_ERROR"
177 super().__init__(*args, **kwargs)
178
179 def __call__(self, form: Form, field: Field) -> None:
180 # Skip None so this can be combined with Optional().
181 if field.data is not None and not isinstance(field.data, (str, int)):
182 assert self._original_message
183 raise StopValidation(get_message(self._original_message)[0])
184
185
186 class EmailValidation:
187 """Simple interface to email_validator.
188 N.B. Side-effect - if valid email, the field.data is set to the normalized value.
189
190 The 'verify' keyword informs the validator to perform checks to be more sure
191 that the email can actually receive an email (as well as normalize).
192 Set to False - just normalize (for use with identity purposes).
193 """
194
195 def __init__(self, *args: t.Any, **kwargs: t.Any):
196 self.verify: bool = kwargs.get("verify", False)
197
198 def __call__(self, form: Form, field: Field) -> None:
199 if field.data is None: # pragma: no cover
200 raise ValidationError(get_message("EMAIL_NOT_PROVIDED")[0])
201
202 try:
203 if self.verify:
204 field.data = _security.mail_util.validate(field.data)
205 else:
206 field.data = _security.mail_util.normalize(field.data)
207 except EmailValidateException as e:
208 # we stop further validators if email isn't valid.
209 # TODO: email_validator provides some really nice error messages - however
210 # they aren't localized. And there isn't an easy way to add multiple
211 # errors at once.
212 raise StopValidation(e.msg)
213 except ValueError:
214 # Backwards compat - mail_util no longer raises this - but app subclasses
215 # might (and we're making this change in 5.4.3).
216 msg = get_message("INVALID_EMAIL_ADDRESS")[0]
217 raise StopValidation(msg)
218
219
220 email_required: RequiredLocalize = RequiredLocalize(message="EMAIL_NOT_PROVIDED")
221 password_required: RequiredLocalize = RequiredLocalize(message="PASSWORD_NOT_PROVIDED")
222
223
224 def _local_xlate(text):
225 """LazyStrings need to be evaluated in the context of a request
226 where _security.i18_domain is available.
227 """
228 return localize_callback(text)
229
230
231 def _get_form_field_label(key: str) -> str:
232 """This is called during import since form fields are declared as part of
233 class. Thus, can't call 'localize_callback' until we need to actually
234 translate/render form.
235 """
236 return t.cast(
237 str, make_lazy_string(_local_xlate, _default_field_labels.get(key, ""))
238 )
239
240
241 def get_form_field_xlate(txt: str) -> str:
242 return t.cast(str, make_lazy_string(_local_xlate, txt))
243
244
245 def valid_user_email(form: Form, field: Field) -> None:
246 # Verify email exists in DB - be sure to normalize first.
247 # Side-effect - set form.user if field is valid
248 uia_email = get_identity_attribute("email")
249 form.user = _datastore.find_user(
250 case_insensitive=uia_email.get("case_insensitive", False), email=field.data
251 )
252 if form.user is None:
253 raise ValidationError(get_message("USER_DOES_NOT_EXIST")[0])
254
255
256 def unique_user_email(form: UniqueEmailFormMixin, field: Field) -> None:
257 # Verify email not already in DB
258 # Assumes field value already normalized - email_validator does this.
259 uia_email = get_identity_attribute("email")
260 form.existing_email_user = _datastore.find_user(
261 case_insensitive=uia_email.get("case_insensitive", False), email=field.data
262 )
263 if form.existing_email_user is not None:
264 msg = get_message("EMAIL_ALREADY_ASSOCIATED", email=field.data)[0]
265 raise ValidationError(msg)
266
267
268 def username_validator(form: BaseForm, field: Field) -> None:
269 # Side-effect - field.data is updated to normalized value.
270 msg, field.data = _security.username_util.validate(field.data)
271 if msg:
272 raise ValidationError(msg)
273
274
275 def _unique_username(form: Form, field: Field) -> None:
276 # Verify username not already in DB
277 # Assumes field value already normalized - username_validator does this.
278 uia_username = get_identity_attribute("username")
279 form.existing_username_user = _datastore.find_user(
280 case_insensitive=uia_username.get("case_insensitive", False),
281 username=field.data,
282 )
283 if form.existing_username_user is not None:
284 msg = get_message("USERNAME_ALREADY_ASSOCIATED", username=field.data)[0]
285 raise ValidationError(msg)
286
287
288 def unique_identity_attribute(form: Form, field: Field) -> None:
289 """A validator that checks the field data against all configured
290 :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`.
291 This can be used as part of registration.
292
293 Be aware that the "mapper" function likely also normalizes the input in addition
294 to validating it.
295
296 :param form:
297 :param field:
298 :return: Nothing; if field data corresponds to an existing User, ValidationError
299 is raised.
300 """
301 for mapping in cv("USER_IDENTITY_ATTRIBUTES"):
302 attr = list(mapping.keys())[0]
303 details = mapping[attr]
304 idata = details["mapper"](field.data)
305 if idata:
306 if _datastore.find_user(
307 case_insensitive=details.get("case_insensitive", False), **{attr: idata}
308 ):
309 msg = get_message(
310 "IDENTITY_ALREADY_ASSOCIATED", attr=attr, value=idata
311 )[0]
312 raise ValidationError(msg)
313
314
315 class Form(BaseForm):
316 def __init__(self, *args: t.Any, **kwargs: t.Any):
317 if current_app and current_app.testing:
318 self.TIME_LIMIT = None
319 super().__init__(*args, **kwargs)
320
321
322 def _generic_message(
323 detailed_msg: str, generic_msg: str, **kwargs: t.Any
324 ) -> tuple[str, str]:
325 if cv("RETURN_GENERIC_RESPONSES"):
326 m, c = get_message(generic_msg, **kwargs)
327 else:
328 m, c = get_message(detailed_msg, **kwargs)
329 return m, c
330
331
332 def form_errors_munge(form: Form, fields: dict[str, dict[str, str]]) -> None:
333 """
334 To support OWASP best practice on unauthenticated endpoints to avoid
335 disclosing whether a user exists or not we need to return generic error messages.
336 Furthermore, WTForms really likes to place errors on the field itself - which is
337 a dead giveaway. We need to move errors from fields to the form.form_errors, and
338 (optionally) replace then with generic msgs.
339 """
340 if not cv("RETURN_GENERIC_RESPONSES"): # pragma: no cover
341 return
342
343 for fname, rinfo in fields.items():
344 field = getattr(form, fname)
345 if field.errors:
346 field.errors = []
347 # If they want to replace that message with a generic message and place
348 # it in the generic/form level errors - do that.
349 if replace_msg := rinfo.get("replace_msg"):
350 form.form_errors.append(get_message(replace_msg)[0])
351
352
353 class UserEmailFormMixin:
354 email: EmailField = EmailField(
355 _get_form_field_label("email"),
356 render_kw={"autocomplete": "email"},
357 validators=[
358 IsString(),
359 email_required,
360 EmailValidation(verify=True),
361 valid_user_email,
362 ],
363 )
364
365
366 class UniqueEmailFormMixin:
367 email: EmailField = EmailField(
368 _get_form_field_label("email"),
369 render_kw={"autocomplete": "email"},
370 validators=[
371 IsString(),
372 email_required,
373 EmailValidation(verify=True),
374 unique_user_email,
375 ],
376 )
377
378 def __init__(self, *args: t.Any, **kwargs: t.Any):
379 super().__init__(*args, **kwargs)
380 self.existing_email_user: UserMixin | None = None
381
382
383 class PasswordFormMixin:
384 password: PasswordField = PasswordField(
385 _get_form_field_label("password"),
386 render_kw={"autocomplete": "current-password"},
387 validators=[IsString(), password_required],
388 )
389
390
391 class NewPasswordFormMixin:
392 password: PasswordField = PasswordField(
393 _get_form_field_label("password"),
394 render_kw={"autocomplete": "new-password"},
395 validators=[IsString(), password_required],
396 )
397
398
399 class PasswordConfirmFormMixin:
400 password_confirm: PasswordField = PasswordField(
401 _get_form_field_label("retype_password"),
402 render_kw={"autocomplete": "new-password"},
403 validators=[
404 IsString(),
405 EqualToLocalize("password", message="RETYPE_PASSWORD_MISMATCH"),
406 password_required,
407 ],
408 )
409
410
411 class NextFormMixin:
412 next: HiddenField = HiddenField()
413
414 def validate_next(self, field: Field) -> None:
415 if field.data and not validate_redirect_url(field.data):
416 field.data = ""
417 do_flash(*get_message("INVALID_REDIRECT"))
418 raise ValidationError(get_message("INVALID_REDIRECT")[0])
419
420
421 class CodeFormMixin:
422 code: StringField = StringField(
423 _get_form_field_label("code"),
424 render_kw={
425 "autocomplete": "one-time-code",
426 "type": "text",
427 "pattern": "[0-9]*",
428 },
429 validators=[IsStringOrInt(), RequiredLocalize()],
430 )
431
432
433 def _build_username_field(app):
434 if cv("USERNAME_REQUIRED", app=app):
435 validators = [
436 IsString(),
437 RequiredLocalize(message="USERNAME_NOT_PROVIDED"),
438 username_validator,
439 _unique_username,
440 ]
441 else:
442 validators = [IsString(), username_validator, _unique_username]
443 return StringField(
444 _get_form_field_label("username"),
445 render_kw={"autocomplete": "username"},
446 validators=validators,
447 )
448
449
450 class RegisterFormMixin:
451 submit: SubmitField = SubmitField(_get_form_field_label("register"))
452
453 # The "username" field is added in init_app if USERNAME_ENABLE is set.
454 # This is just a type hint.
455 username: t.ClassVar[Field]
456
457 def to_dict(self, only_user: bool) -> dict[str, t.Any]:
458 """
459 Return form data as dictionary
460 :param only_user: bool, if True then only fields that have
461 corresponding members in UserModel are returned
462 :return: dict
463 """
464
465 def is_field_and_user_attr(member):
466 if not isinstance(member, Field):
467 return False
468
469 # If only fields recorded on UserModel should be returned,
470 # perform check on user model, else return True
471 if only_user is True:
472 return hasattr(_datastore.user_model, member.name)
473 else:
474 return True
475
476 fields = inspect.getmembers(self, is_field_and_user_attr)
477 return {key: value.data for key, value in fields}
478
479
480 class SendConfirmationForm(Form, UserEmailFormMixin):
481 """The default send confirmation form"""
482
483 submit: SubmitField = SubmitField(_get_form_field_label("send_confirmation"))
484
485 def __init__(self, *args: t.Any, **kwargs: t.Any):
486 super().__init__(*args, **kwargs)
487 self.user: UserMixin | None = None # set by valid_user_email
488 if request and request.method == "GET":
489 self.email.data = request.args.get("email", None)
490
491 def validate(self, **kwargs: t.Any) -> bool:
492 if not super().validate(**kwargs):
493 return False
494 assert self.user is not None
495 if self.user.confirmed_at is not None:
496 assert isinstance(self.email.errors, list)
497 self.email.errors.append(get_message("ALREADY_CONFIRMED")[0])
498 return False
499 return True
500
501
502 class ForgotPasswordForm(Form, UserEmailFormMixin):
503 """The default forgot password form"""
504
505 submit: SubmitField = SubmitField(_get_form_field_label("recover_password"))
506
507 def __init__(self, *args: t.Any, **kwargs: t.Any):
508 super().__init__(*args, **kwargs)
509 self.requires_confirmation: bool = False
510 self.user: UserMixin | None = None # set by valid_user_email
511
512 def validate(self, **kwargs: t.Any) -> bool:
513 if not super().validate(**kwargs):
514 return False
515 assert self.user is not None
516 assert isinstance(self.email.errors, list)
517 if not self.user.is_active:
518 self.email.errors.append(get_message("DISABLED_ACCOUNT")[0])
519 return False
520 if self.user.is_locked(self.email.errors):
521 return False
522 self.requires_confirmation = requires_confirmation(self.user)
523 if self.requires_confirmation:
524 self.email.errors.append(get_message("CONFIRMATION_REQUIRED")[0])
525 return False
526 return True
527
528
529 class PasswordlessLoginForm(Form):
530 """The passwordless login form"""
531
532 email: EmailField = EmailField(
533 _get_form_field_label("email"),
534 render_kw={"autocomplete": "email"},
535 validators=[
536 IsString(),
537 email_required,
538 EmailValidation(verify=False),
539 valid_user_email,
540 ],
541 )
542
543 submit: SubmitField = SubmitField(_get_form_field_label("send_login_link"))
544
545 def __init__(self, *args: t.Any, **kwargs: t.Any):
546 super().__init__(*args, **kwargs)
547 self.user: UserMixin | None = None # set by valid_user_email
548
549 def validate(self, **kwargs: t.Any) -> bool:
550 if not super().validate(**kwargs):
551 return False
552 assert self.user is not None
553 assert isinstance(self.email.errors, list)
554 if not self.user.is_active:
555 self.email.errors.append(get_message("DISABLED_ACCOUNT")[0])
556 return False
557 if self.user.is_locked(self.email.errors):
558 return False
559 return True
560
561
562 class LoginForm(Form, PasswordFormMixin, NextFormMixin):
563 """The default login form.
564
565 The following fields are defined:
566 * email
567 * username (based on :py:data:`SECURITY_USERNAME_ENABLE`)
568 * password
569 * remember (checkbox)
570 * next
571 * submit
572
573 The following attributes might be useful for subclasses:
574 * ifield - If a subclass wants to handle identity, it can set self.ifield to the
575 form field that it validated. That will cause the validation logic here
576 around identity to be skipped.
577 The subclass must also set self.user to the found User.
578 * user - as stated above - if subclass does identity check it must set this
579 field.
580 """
581
582 # email field - we don't use valid_user_email since for login we must check
583 # user_identity_attributes to ensure 'email' is listed.
584 # If USERNAME_ENABLE is set - this field will be replaced to be Optional()
585 # see build_login_form()
586 email: EmailField = EmailField(
587 _get_form_field_label("email"),
588 render_kw={"autocomplete": "email"},
589 validators=[IsString(), email_required, EmailValidation(verify=False)],
590 )
591
592 # username is added dynamically based on USERNAME_ENABLED.
593 username: t.ClassVar[Field]
594 remember: BooleanField = BooleanField(
595 _get_form_field_label("remember_me"),
596 default=lambda: cv("DEFAULT_REMEMBER_ME", app=current_app),
597 )
598 submit: SubmitField = SubmitField(_get_form_field_label("login"))
599
600 def __init__(self, *args: t.Any, **kwargs: t.Any):
601 super().__init__(*args, **kwargs)
602 if request and not self.next.data:
603 self.next.data = request.args.get("next", "")
604 if _security.recoverable and not self.password.description:
605 html = Markup(
606 f'<a href="{url_for_security("forgot_password")}">'
607 f'{get_message("FORGOT_PASSWORD")[0]}</a>'
608 )
609 self.password.description = html
610 self.requires_confirmation: bool = False
611 self.user: UserMixin | None = None
612 # ifield can be set by subclasses to skip identity checks.
613 self.ifield: Field | None = None
614 # If True then user has authenticated so we can show detailed errors
615 self.user_authenticated: bool = False
616
617 def validate(self, **kwargs: t.Any) -> bool:
618 if not super().validate(**kwargs):
619 return False
620
621 assert self.password.data is not None # validator password_required
622 # Stay clear of accessing 'username' unless we added that field.
623 # Lots of applications have added their own.
624 # To make subclassing easier - if self.ifield has been set we assume
625 # subclass has validated and attempted to look up user. It is also
626 # responsible to deal with USER_IDENTITY_ATTRIBUTES if it cares.
627 if not self.ifield:
628 uia_email = get_identity_attribute("email")
629 # pedantic checks - if app subclasses form, removes email but forgets to
630 # remove "email" from identity_attributes
631 if uia_email and hasattr(self, "email") and self.email and self.email.data:
632 self.ifield = self.email
633 self.user = _datastore.find_user(
634 case_insensitive=uia_email.get("case_insensitive", False),
635 email=self.email.data,
636 )
637 elif cv("USERNAME_ENABLE"):
638 uia_username = get_identity_attribute("username")
639 if uia_username and self.username.data:
640 self.user = _datastore.find_user(
641 case_insensitive=uia_username.get("case_insensitive", False),
642 username=self.username.data,
643 )
644 self.ifield = self.username
645 else:
646 # A bit of backwards compat - the old LoginForm just had email and
647 # any errors would be set on that field.
648 if uia_email:
649 self.ifield = self.email
650
651 assert isinstance(self.password.errors, list)
652 if self.user is None:
653 msg = get_message("USER_DOES_NOT_EXIST")[0]
654 if self.ifield:
655 assert isinstance(self.ifield.errors, list)
656 self.ifield.errors.append(msg)
657 else:
658 self.form_errors.append(msg)
659 # Reduce timing variation between existing and non-existing users
660 hash_password(self.password.data)
661 return False
662 if not self.user.password:
663 # This is result of PASSWORD_REQUIRED=False and UNIFIED_SIGNIN
664 self.user.track_failed_authn("password")
665 self.password.errors.append(get_message("INVALID_PASSWORD")[0])
666 # Reduce timing variation between existing and non-existing users
667 hash_password(self.password.data)
668 return False
669 self.password.data = _security.password_util.normalize(self.password.data)
670 if not self.user.verify_and_update_password(self.password.data):
671 self.user.track_failed_authn("password")
672 self.password.errors.append(get_message("INVALID_PASSWORD")[0])
673 return False
674
675 # At this point the user has successfully authenticated - so it is fine
676 # to return detailed errors.
677 self.user_authenticated = True
678 self.requires_confirmation = requires_confirmation(self.user)
679 assert self.ifield is not None
680 assert isinstance(self.ifield.errors, list)
681 if not self.user.is_active:
682 self.ifield.errors.append(get_message("DISABLED_ACCOUNT")[0])
683 return False
684 if self.user.is_locked(self.ifield.errors):
685 return False
686 if self.requires_confirmation:
687 self.ifield.errors.append(get_message("CONFIRMATION_REQUIRED")[0])
688 return False
689 return True
690
691
692 def _build_login_form(app, fcls):
693 # Based on app configuration, add optional/configurable fields to the login form
694 # Allow app to override the field using mixins.
695 # Note this is only called (from init_app()) if form is subclassed from ours.
696 # We really don't want to touch the form unless there is a specific option
697 # requested - so that subclasses can change/do what they want (including deleting
698 # email for example).
699 if cv("USERNAME_ENABLE", app):
700 fcls.username = StringField(
701 _get_form_field_label("username"),
702 render_kw={"autocomplete": "username"},
703 validators=[IsString(), username_validator],
704 )
705 if hasattr(fcls, "email") and fcls.email:
706 # Make field Optional()
707 # let subclass easily get rid of this
708 # Note that WTForms 'del' operator actually sets this to None
709 fcls.email = EmailField(
710 _get_form_field_label("email"),
711 render_kw={"autocomplete": "email"},
712 validators=[IsString(), Optional(), EmailValidation(verify=False)],
713 )
714
715
716 class LogoutForm(Form):
717 """The logout form.
718 No data is required to logout - however, if a refresh token
719 is provided, it will be revoked.
720 Also - CSRF will be checked - whether that will cause an error is up to
721 the view.
722 """
723
724 refresh_token: HiddenField = HiddenField(
725 get_form_field_xlate(_("Refresh Token")),
726 validators=[IsString(), Optional()],
727 )
728 submit: SubmitField = SubmitField(label=_get_form_field_label("submit"))
729
730 # returned to caller
731 refresh_errors: RefreshTokenErrors | None = None
732 refresh_tracker: RefreshTrackerMixin | None = None
733
734 def __init__(self, *args: t.Any, **kwargs: t.Any):
735 super().__init__(*args, **kwargs)
736 # If cookie name set - then use that - NOT from the form
737 if request and cv("REFRESH_TOKEN") and cv("REFRESH_TOKEN_COOKIE_NAME"):
738 token = request.cookies.get(cv("REFRESH_TOKEN_COOKIE_NAME"), default=None)
739 self.refresh_token.data = token
740
741 def validate(self, **kwargs: t.Any) -> bool:
742 from .tokens import verify_refresh_token
743
744 if not super().validate(**kwargs):
745 return False
746 if not self.refresh_token.data:
747 return True
748
749 assert isinstance(self.refresh_token.errors, list)
750 self.refresh_tracker, self.refresh_errors, uid = verify_refresh_token(
751 self.refresh_token.data
752 )
753 # don't really care if valid or not - return it to view
754 return True
755
756
757 class VerifyForm(Form, PasswordFormMixin, NextFormMixin):
758 """The verify authentication form"""
759
760 submit: SubmitField = SubmitField(_get_form_field_label("verify_password"))
761
762 def __init__(self, *args: t.Any, user: UserMixin, **kwargs: t.Any):
763 super().__init__(*args, **kwargs)
764 self.user: UserMixin = user
765 if request and not self.next.data:
766 self.next.data = request.args.get("next", "")
767
768 def validate(self, **kwargs: t.Any) -> bool:
769 if not super().validate(**kwargs): # pragma: no cover
770 return False
771
772 assert self.password.data is not None
773 self.password.data = _security.password_util.normalize(self.password.data)
774 assert isinstance(self.password.errors, list)
775 if not self.user.verify_and_update_password(self.password.data):
776 self.user.track_failed_authn("password")
777 self.password.errors.append(get_message("INVALID_PASSWORD")[0])
778 return False
779 return True
780
781
782 class ConfirmRegisterForm(UniqueEmailFormMixin, Form, RegisterFormMixin):
783 """This form is used for registering when 'confirmable' is set.
784 The only difference between this and the other RegisterForm is that
785 this one doesn't require re-typing in the password...
786
787 We want to support OWASP best-practice around mitigating user enumeration.
788 To that end we run through the entire validation regardless - this allows us
789 to still return important bad-password messages.
790 In the case of an existing email or username - we set form.existing_xx so that
791 the view can decide how to match responses (e.g. json responses always return 200).
792
793 .. deprecated:: 5.6.0
794 Replaced with RegisterFormV2
795 """
796
797 # Password optional when Unified Signin enabled.
798 password: PasswordField = PasswordField(
799 _get_form_field_label("password"),
800 render_kw={"autocomplete": "new-password"},
801 validators=[IsString()],
802 )
803
804 def __init__(self, *args: t.Any, **kwargs: t.Any):
805 super().__init__(*args, **kwargs)
806 self.existing_username_user: UserMixin | None = None
807
808 def validate(self, **kwargs: t.Any) -> bool:
809 failed = False
810 if not super().validate(**kwargs):
811 failed = True
812
813 # whether a password is required is a config variable (PASSWORD_REQUIRED).
814 # For unified signin there are many other ways to authenticate
815 assert isinstance(self.password.errors, list)
816 if cv("PASSWORD_REQUIRED"):
817 if (
818 not self.password.data
819 or not isinstance(self.password.data, str)
820 or not self.password.data.strip()
821 ):
822 self.password.errors.append(get_message("PASSWORD_NOT_PROVIDED")[0])
823 failed = True
824
825 if self.password.data:
826 if not isinstance(self.password.data, str):
827 # types-WTForms declares StringField.data type is str | None. But it can
828 # actually be a dict when request body is JSON. mypy therefore
829 # mis-identifies this as unreachable.
830 failed = True # type: ignore[unreachable]
831 else:
832 # We do explicit validation here for passwords
833 # (rather than write a validator class) for 2 reasons:
834 # 1) We want to control which fields are passed -
835 # sometimes that's current_user
836 # other times it's the registration fields.
837 # 2) We want to be able to return multiple error messages.
838 rfields = {}
839 for k, v in self.data.items():
840 if hasattr(_datastore.user_model, k):
841 rfields[k] = v
842 del rfields["password"]
843 pbad, self.password.data = _security.password_util.validate(
844 self.password.data, True, **rfields
845 )
846 if pbad:
847 self.password.errors.extend(pbad)
848 failed = True
849 return not failed
850
851
852 class RegisterForm(ConfirmRegisterForm, NextFormMixin):
853 """Register Form
854
855 .. deprecated:: 5.6.0
856 Replaced with RegisterFormV2
857 """
858
859 # Password optional when Unified Signin enabled.
860 password_confirm: PasswordField = PasswordField(
861 _get_form_field_label("retype_password"),
862 validators=[
863 IsString(),
864 EqualToLocalize("password", message="RETYPE_PASSWORD_MISMATCH"),
865 Optional(),
866 ],
867 )
868
869 def validate(self, **kwargs: t.Any) -> bool:
870 if not super().validate(**kwargs):
871 return False
872 assert isinstance(self.password_confirm.errors, list)
873 if not cv("UNIFIED_SIGNIN"):
874 # password_confirm required
875 if not self.password_confirm.data or not self.password_confirm.data.strip():
876 self.password_confirm.errors.append(
877 get_message("PASSWORD_NOT_PROVIDED")[0]
878 )
879 return False
880 return True
881
882 def __init__(self, *args: t.Any, **kwargs: t.Any):
883 super().__init__(*args, **kwargs)
884 if request and not self.next.data:
885 self.next.data = request.args.get("next", "")
886
887
888 class RegisterFormV2(
889 UniqueEmailFormMixin,
890 NextFormMixin,
891 NewPasswordFormMixin,
892 PasswordConfirmFormMixin,
893 Form,
894 ):
895 """This form is used for registering.
896
897 The following fields are defined:
898 * email (required)
899 * password (required if :py:data:`SECURITY_PASSWORD_REQUIRED` is ``True``)
900 * password_confirm (based on :py:data:`SECURITY_PASSWORD_CONFIRM_REQUIRED`)
901 * username (based on :py:data:`SECURITY_USERNAME_ENABLE`)
902 * next
903
904 Since there are many configuration options that alter which fields and
905 which validators (e.g. Required), some fields are added or changed at
906 Security init_app() time by calling the internal method build_register_form().
907
908 We want to support OWASP best-practice around mitigating user enumeration.
909 To that end we run through the entire validation regardless - this allows us
910 to still return important bad-password messages.
911 In the case of an existing email or username - we set form.existing_xx so that
912 the view can decide how to match responses (e.g. json responses always return 200).
913
914 .. versionadded:: 5.6
915 """
916
917 submit: SubmitField = SubmitField(_get_form_field_label("register"))
918 username: t.ClassVar[Field]
919
920 def to_dict(self, only_user: bool) -> dict[str, t.Any]:
921 """
922 Return form data as dictionary
923 :param only_user: bool, if True then only fields that have
924 corresponding members in UserModel are returned
925 :return: dict
926 """
927
928 def is_field_and_user_attr(member):
929 if not isinstance(member, Field):
930 return False
931
932 # If only fields recorded on UserModel should be returned,
933 # perform check on user model, else return True
934 if only_user is True:
935 return hasattr(_datastore.user_model, member.name)
936 else:
937 return True
938
939 fields = inspect.getmembers(self, is_field_and_user_attr)
940 return {key: value.data for key, value in fields}
941
942 def validate(self, **kwargs: t.Any) -> bool:
943 failed = False
944 if not super().validate(**kwargs):
945 failed = True
946
947 assert isinstance(self.password.errors, list)
948 if self.password.data:
949 if not isinstance(self.password.data, str):
950 # types-WTForms declares StringField.data type is str | None. But it can
951 # actually be a dict when request body is JSON. mypy therefore
952 # mis-identifies this as unreachable.
953 failed = True # type: ignore[unreachable]
954 else:
955 # We do explicit validation here for passwords
956 # (rather than write a validator class) for 2 reasons:
957 # 1) We want to control which fields are passed -
958 # sometimes that's current_user
959 # other times it's the registration fields.
960 # 2) We want to be able to return multiple error messages.
961 rfields = {}
962 for k, v in self.data.items():
963 if hasattr(_datastore.user_model, k):
964 rfields[k] = v
965 del rfields["password"]
966 pbad, self.password.data = _security.password_util.validate(
967 self.password.data, True, **rfields
968 )
969 if pbad:
970 self.password.errors.extend(pbad)
971 failed = True
972 return not failed
973
974 def __init__(self, *args: t.Any, **kwargs: t.Any):
975 super().__init__(*args, **kwargs)
976 self.existing_username_user: UserMixin | None = None
977 if request and not self.next.data:
978 self.next.data = request.args.get("next", "")
979
980
981 def _build_register_form(app, fcls):
982 # Based on app configuration, add optional/configurable fields to the register form
983 # Allow app to override the field using mixins
984 # Note that this occurs AFTER app might have sub-classed the form
985 if not cv("PASSWORD_REQUIRED", app):
986 # mark password field as Optional
987 fcls.password = PasswordField(
988 label=_get_form_field_label("password"),
989 render_kw={"autocomplete": "new-password"},
990 validators=[IsString(), Optional()],
991 )
992 fcls.password_confirm = PasswordField(
993 _get_form_field_label("retype_password"),
994 render_kw={"autocomplete": "new-password"},
995 validators=[
996 IsString(),
997 EqualToLocalize("password", message="RETYPE_PASSWORD_MISMATCH"),
998 ],
999 )
1000 if not cv("PASSWORD_CONFIRM_REQUIRED", app=app):
1001 fcls.password_confirm = None
1002 if cv("USERNAME_ENABLE", app):
1003 fcls.username = _build_username_field(app=app)
1004
1005
1006 class ResetPasswordForm(Form, NewPasswordFormMixin, PasswordConfirmFormMixin):
1007 """The default reset password form"""
1008
1009 # filled in by caller
1010 user: UserMixin | None
1011
1012 submit: SubmitField = SubmitField(_get_form_field_label("reset_password"))
1013
1014 def validate(self, **kwargs: t.Any) -> bool:
1015 if not super().validate(**kwargs):
1016 return False
1017
1018 assert isinstance(self.password.errors, list)
1019 assert self.password.data is not None
1020 pbad, self.password.data = _security.password_util.validate(
1021 self.password.data, False, user=self.user
1022 )
1023 if pbad:
1024 self.password.errors.extend(pbad)
1025 return False
1026 return True
1027
1028
1029 class ChangePasswordForm(Form):
1030 """The default change password form"""
1031
1032 password: PasswordField = PasswordField(
1033 _get_form_field_label("password"),
1034 render_kw={"autocomplete": "current-password"},
1035 )
1036 new_password: PasswordField = PasswordField(
1037 _get_form_field_label("new_password"),
1038 render_kw={"autocomplete": "new-password"},
1039 validators=[IsString(), password_required],
1040 )
1041
1042 new_password_confirm: PasswordField = PasswordField(
1043 _get_form_field_label("retype_password"),
1044 render_kw={"autocomplete": "new-password"},
1045 validators=[
1046 IsString(),
1047 EqualToLocalize("new_password", message="RETYPE_PASSWORD_MISMATCH"),
1048 password_required,
1049 ],
1050 )
1051
1052 submit: SubmitField = SubmitField(_get_form_field_label("change_password"))
1053
1054 def validate(self, **kwargs: t.Any) -> bool:
1055 if not super().validate(**kwargs):
1056 return False
1057
1058 # If user doesn't have a password then the caller (view) has already
1059 # verified a current fresh session.
1060 assert isinstance(self.password.errors, list)
1061 assert isinstance(self.new_password.errors, list)
1062 if current_user.password:
1063 if not self.password.data or not self.password.data.strip():
1064 self.password.errors.append(get_message("PASSWORD_NOT_PROVIDED")[0])
1065 return False
1066
1067 self.password.data = _security.password_util.normalize(self.password.data)
1068 if not verify_password(self.password.data, current_user.password):
1069 self.password.errors.append(get_message("INVALID_PASSWORD")[0])
1070 return False
1071 if self.password.data == self.new_password.data:
1072 self.password.errors.append(get_message("PASSWORD_IS_THE_SAME")[0])
1073 return False
1074
1075 assert self.new_password.data is not None
1076 pbad, self.new_password.data = _security.password_util.validate(
1077 self.new_password.data, False, user=current_user
1078 )
1079 if pbad:
1080 self.new_password.errors.extend(pbad)
1081 return False
1082 return True
1083
1084
1085 class TwoFactorSetupForm(Form):
1086 """The Two-factor token validation form"""
1087
1088 setup: RadioField = RadioField(
1089 get_form_field_xlate(_("Available Methods")),
1090 choices=[
1091 ("disable", get_form_field_xlate(_("Disable two-factor authentication"))),
1092 ("email", _get_form_field_label("email_method")),
1093 (
1094 "authenticator",
1095 _get_form_field_label("authapp_method"),
1096 ),
1097 ("sms", _get_form_field_label("sms_method")),
1098 ],
1099 validate_choice=False,
1100 )
1101 phone: TelField = TelField(_get_form_field_label("phone"), validators=[IsString()])
1102 submit: SubmitField = SubmitField(_get_form_field_label("submit"))
1103
1104 def __init__(self, *args: t.Any, **kwargs: t.Any):
1105 super().__init__(*args, **kwargs)
1106 self.user: UserMixin | None = None # set by view
1107
1108 def validate(self, **kwargs: t.Any) -> bool:
1109 if not super().validate(**kwargs): # pragma: no cover
1110 return False
1111 assert self.user is not None
1112 choices = list(cv("TWO_FACTOR_ENABLED_METHODS"))
1113 assert isinstance(self.setup.errors, list)
1114 assert isinstance(self.phone.errors, list)
1115 if "email" in choices:
1116 # backwards compat
1117 choices.append("mail")
1118 if not self.user.check_tf_required_setup():
1119 choices.append("disable")
1120 if "setup" not in self.data or self.data["setup"] not in choices:
1121 self.setup.errors.append(get_message("TWO_FACTOR_METHOD_NOT_AVAILABLE")[0])
1122 return False
1123 if self.setup.data == "sms":
1124 if not self.phone.data:
1125 self.phone.errors.append(get_message("PHONE_INVALID")[0])
1126 return False
1127 msg = _security.phone_util.validate_phone_number(self.phone.data)
1128 if msg:
1129 self.phone.errors.append(msg)
1130 return False
1131
1132 return True
1133
1134
1135 class TwoFactorVerifyCodeForm(Form, CodeFormMixin):
1136 """The Two-factor token validation form"""
1137
1138 submit: SubmitField = SubmitField(
1139 _get_form_field_label("submitcode"), id="submit-code"
1140 )
1141
1142 def __init__(self, *args: t.Any, **kwargs: t.Any):
1143 super().__init__(*args, **kwargs)
1144 # These are set by view.
1145 self.window: int = 0
1146 self.primary_method: str = ""
1147 self.tf_totp_secret: str = ""
1148 self.user: UserMixin | None = None # set by view
1149 self.is_setup: bool = False
1150
1151 def validate(self, **kwargs: t.Any) -> bool:
1152 if not super().validate(**kwargs): # pragma: no cover
1153 return False
1154 if (
1155 self.primary_method == "google_authenticator"
1156 or self.primary_method == "authenticator"
1157 ):
1158 self.window = cv("TWO_FACTOR_AUTHENTICATOR_VALIDITY")
1159 elif self.primary_method == "email" or self.primary_method == "mail":
1160 self.window = cv("TWO_FACTOR_MAIL_VALIDITY")
1161 elif self.primary_method == "sms":
1162 self.window = cv("TWO_FACTOR_SMS_VALIDITY")
1163 else:
1164 return False
1165
1166 # verify entered code with user's totp secret
1167 assert self.user is not None
1168 assert self.code.data is not None
1169 assert isinstance(self.code.errors, list)
1170 if not _security.totp_factory.verify_totp(
1171 token=self.code.data,
1172 totp_secret=self.tf_totp_secret,
1173 user=self.user,
1174 window=self.window,
1175 ):
1176 if not self.is_setup:
1177 self.user.track_failed_authn("code", True)
1178 self.code.errors.append(get_message("TWO_FACTOR_INVALID_TOKEN")[0])
1179 return False
1180
1181 return True
1182
1183
1184 class TwoFactorRescueForm(Form):
1185 """The Two-factor Rescue validation form"""
1186
1187 # rescue options - additional options are generated in set_rescue_options()
1188 help_setup: RadioField = RadioField(
1189 get_form_field_xlate(_("Trouble Accessing Your Account?/Lost Mobile Device?")),
1190 choices=[
1191 ("help", get_form_field_xlate(_("Contact Administrator"))),
1192 ],
1193 )
1194 submit: SubmitField = SubmitField(_get_form_field_label("submit"), id="rescue")
1195
1196 user: UserMixin | None = None # set by view
1197
1198
1199 class UsernameRecoveryForm(ForgotPasswordForm):
1200 """The username recovery form"""
1201
1202 submit: SubmitField = SubmitField(_get_form_field_label("recover_username"))
1203
1204
1205 class DummyForm(Form):
1206 """A dummy form for json responses"""
1207
1208 def __init__(self, *args: t.Any, **kwargs: t.Any):
1209 super().__init__(*args, **kwargs)
1210 self.user: UserMixin | None = kwargs.get("user", None)
1211
1212
1213 def _build_form_from_request(form_name: str, **kwargs: dict[str, t.Any]) -> Form:
1214 # helper function for views
1215 form_data = None
1216 if request.content_length:
1217 form_data = MultiDict(request.get_json()) if request.is_json else request.form
1218 return _build_form(
1219 form_name, formdata=form_data, meta=_suppress_form_csrf(), **kwargs
1220 )
1221
1222
1223 def _build_form(form_name, **kwargs):
1224 # helper function for views
1225 kwargs.setdefault("formdata", None)
1226 return _security.forms[form_name].instantiator(
1227 form_name,
1228 _security.forms[form_name].cls,
1229 **kwargs,
1230 )