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