Debian Codegraph @

flask_security/core.py

raw
1 """
2 flask_security.core
3 ~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security core module
6
7 :copyright: (c) 2012 by Matt Wright.
8 :copyright: (c) 2017 by CERN.
9 :copyright: (c) 2017 by ETH Zurich, Swiss Data Science Center.
10 :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
11 :license: MIT, see LICENSE for more details.
12 """
13
14 from __future__ import annotations
15
16 from datetime import datetime, timedelta
17 from dataclasses import dataclass
18 import importlib
19 import time
20 import typing as t
21 import warnings
22
23 from flask import current_app, g, session
24 from flask_login import AnonymousUserMixin, LoginManager
25 from flask_login import current_user
26 from flask_principal import Identity, Principal, RoleNeed, UserNeed, identity_loaded
27 from itsdangerous import URLSafeTimedSerializer, URLSafeSerializer
28 from passlib.context import CryptContext
29 from werkzeug.local import LocalProxy
30
31 from .babel import FsDomain
32 from .change_email import ChangeEmailForm
33 from .change_username import ChangeUsernameForm
34 from .decorators import (
35 default_reauthn_handler,
36 default_unauthn_handler,
37 default_unauthz_handler,
38 )
39 from .forms import (
40 ChangePasswordForm,
41 ConfirmRegisterForm,
42 ForgotPasswordForm,
43 Form,
44 LoginForm,
45 LogoutForm,
46 PasswordlessLoginForm,
47 RegisterForm,
48 RegisterFormMixin,
49 RegisterFormV2,
50 ResetPasswordForm,
51 SendConfirmationForm,
52 TwoFactorVerifyCodeForm,
53 TwoFactorSetupForm,
54 TwoFactorRescueForm,
55 UsernameRecoveryForm,
56 VerifyForm,
57 _build_username_field,
58 _build_register_form,
59 _build_login_form,
60 )
61 from .json import setup_json
62 from .mail_util import MailUtil
63 from .password_util import PasswordUtil
64 from .phone_util import PhoneUtil
65 from .oauth_glue import OAuthGlue
66 from .proxies import _security
67 from .recovery_codes import (
68 MfRecoveryForm,
69 MfRecoveryCodesForm,
70 MfRecoveryCodesUtil,
71 )
72 from .signals import user_failed_authn
73 from .tf_plugin import TfPlugin, TwoFactorSelectForm
74 from .tokens import RefreshTokenForm
75 from .twofactor import tf_send_security_token
76 from .unified_signin import (
77 UnifiedSigninForm,
78 UnifiedSigninSetupForm,
79 UnifiedSigninSetupValidateForm,
80 UnifiedVerifyForm,
81 us_send_security_token,
82 )
83 from .webauthn import (
84 WebAuthnDeleteForm,
85 WebAuthnRegisterForm,
86 WebAuthnRegisterResponseForm,
87 WebAuthnSigninForm,
88 WebAuthnSigninResponseForm,
89 WebAuthnVerifyForm,
90 )
91 from .webauthn_util import WebauthnUtil
92 from .username_util import UsernameUtil
93 from .totp import Totp
94 from .utils import _
95 from .utils import _config_value as cv
96 from .utils import (
97 _FsPermNeed,
98 _add_cache_control,
99 _csrf_cookie_handler,
100 _default_render_template,
101 _default_want_json,
102 get_identity_attribute,
103 get_identity_attributes,
104 get_message,
105 get_request_attr,
106 is_user_authenticated,
107 naive_utcnow,
108 parse_auth_token,
109 set_request_attr,
110 uia_email_mapper,
111 uia_username_mapper,
112 url_for_security,
113 verify_and_update_password,
114 )
115 from .views import _create_blueprint, default_render_json
116
117 if t.TYPE_CHECKING: # pragma: no cover
118 import flask
119 from flask import Request
120 from flask.typing import ResponseValue
121 from authlib.integrations.flask_client import OAuth
122 from .datastore import UserDatastore
123
124 # flask_login isn't typed yet
125 class BaseUserMixin:
126 # __hash__ = object.__hash__
127
128 @property
129 def is_active(self) -> bool:
130 return True
131
132 @property
133 def is_authenticated(self) -> bool:
134 return self.is_active
135
136 @property
137 def is_anonymous(self) -> bool:
138 return False
139
140 def get_id(self) -> str: ...
141
142 def __eq__(self, other: object) -> bool:
143 """
144 Checks the equality of two `UserMixin` objects using `get_id`.
145 """
146 if isinstance(other, UserMixin):
147 return self.get_id() == other.get_id()
148 return NotImplemented
149
150 def __ne__(self, other: object) -> bool:
151 """
152 Checks the inequality of two `UserMixin` objects using `get_id`.
153 """
154 equal = self.__eq__(other)
155 if equal is NotImplemented:
156 return NotImplemented
157 return not equal
158
159 else:
160 from flask_login import UserMixin as BaseUserMixin
161
162 # List of authentication mechanisms supported.
163 AUTHN_MECHANISMS = ("basic", "session", "token")
164
165
166 #: Default Flask-Security configuration
167 _default_config: dict[str, t.Any] = {
168 "ANONYMOUS_USER_DISABLED": False,
169 "BLUEPRINT_NAME": "security",
170 "CLI_ROLES_NAME": "roles",
171 "CLI_USERS_NAME": "users",
172 "URL_PREFIX": None,
173 "STATIC_FOLDER": "static",
174 "STATIC_FOLDER_URL": "/fs-static",
175 "SUBDOMAIN": None,
176 "FLASH_MESSAGES": True,
177 "RETURN_GENERIC_RESPONSES": False,
178 "INPUT_NORMALIZE_FORM": "NFKD",
179 "USE_REGISTER_V2": True,
180 "I18N_DOMAIN": "flask_security",
181 "I18N_DIRNAME": "builtin",
182 "EMAIL_VALIDATOR_ARGS": None,
183 "PASSWORD_HASH": "argon2",
184 "PASSWORD_SALT": None,
185 "PASSWORD_SINGLE_HASH": {
186 "django_argon2",
187 "django_bcrypt_sha256",
188 "django_pbkdf2_sha256",
189 "django_pbkdf2_sha1",
190 "django_bcrypt",
191 "django_salted_md5",
192 "django_salted_sha1",
193 "django_des_crypt",
194 "plaintext",
195 },
196 "PASSWORD_SCHEMES": [
197 "bcrypt",
198 "argon2",
199 "des_crypt",
200 "pbkdf2_sha256",
201 "pbkdf2_sha512",
202 "sha256_crypt",
203 "sha512_crypt",
204 # And always last one...
205 "plaintext",
206 ],
207 "DEPRECATED_PASSWORD_SCHEMES": ["auto"],
208 "PASSWORD_HASH_OPTIONS": {}, # Deprecated at passlib 1.7
209 "PASSWORD_HASH_PASSLIB_OPTIONS": {}, # passlib >= 1.7.1 method to pass options
210 # (as part of CryptoContext.using)
211 "PASSWORD_LENGTH_MIN": 8,
212 "PASSWORD_COMPLEXITY_CHECKER": None,
213 "PASSWORD_CHECK_BREACHED": False,
214 "PASSWORD_BREACHED_COUNT": 1,
215 "PASSWORD_NORMALIZE_FORM": "NFKD",
216 "PASSWORD_REQUIRED": True,
217 "PASSWORD_CONFIRM_REQUIRED": True, # for RegisterFormV2
218 "HASHING_SCHEMES": ["sha256_crypt", "hex_md5"],
219 "DEPRECATED_HASHING_SCHEMES": ["auto"],
220 "LOGIN_URL": "/login",
221 "LOGOUT_URL": "/logout",
222 "REGISTER_URL": "/register",
223 "RESET_URL": "/reset",
224 "CHANGE_URL": "/change",
225 "CONFIRM_URL": "/confirm",
226 "VERIFY_URL": "/verify",
227 "TWO_FACTOR_SETUP_URL": "/tf-setup",
228 "TWO_FACTOR_TOKEN_VALIDATION_URL": "/tf-validate",
229 "TWO_FACTOR_RESCUE_URL": "/tf-rescue",
230 "TWO_FACTOR_SELECT_URL": "/tf-select",
231 "TWO_FACTOR_POST_SETUP_VIEW": ".two_factor_setup", # endpoint or URL
232 "TWO_FACTOR_ERROR_VIEW": ".login",
233 "LOGOUT_METHODS": ["POST"],
234 "LOGOUT_CSRF": False,
235 "LOGOUT_USER_TEMPLATE": "security/logout_user.html",
236 "POST_LOGIN_VIEW": "/",
237 "POST_LOGOUT_VIEW": "/",
238 "LOGIN_ERROR_VIEW": None, # spa
239 "POST_OAUTH_LOGIN_VIEW": None, # spa
240 "POST_OAUTH_VERIFY_VIEW": None, # spa
241 "CONFIRM_ERROR_VIEW": None, # spa
242 "POST_CONFIRM_VIEW": None, # spa
243 "RESET_VIEW": None, # spa
244 "RESET_ERROR_VIEW": None, # spa
245 "VERIFY_ERROR_VIEW": None, # spa
246 "POST_RESET_VIEW": None,
247 "POST_CHANGE_VIEW": None,
248 "POST_VERIFY_VIEW": None,
249 "POST_REGISTER_VIEW": None,
250 "UNAUTHORIZED_VIEW": None,
251 "REQUIRES_CONFIRMATION_ERROR_VIEW": None,
252 "REDIRECT_HOST": None,
253 "REDIRECT_BEHAVIOR": None,
254 "REDIRECT_ALLOW_SUBDOMAINS": False,
255 "REDIRECT_BASE_DOMAIN": None,
256 "REDIRECT_ALLOWED_SUBDOMAINS": [],
257 "FORGOT_PASSWORD_TEMPLATE": "security/forgot_password.html",
258 "LOGIN_USER_TEMPLATE": "security/login_user.html",
259 "REGISTER_USER_TEMPLATE": "security/register_user.html",
260 "RESET_PASSWORD_TEMPLATE": "security/reset_password.html",
261 "CHANGE_PASSWORD_TEMPLATE": "security/change_password.html",
262 "SEND_CONFIRMATION_TEMPLATE": "security/send_confirmation.html",
263 "SEND_LOGIN_TEMPLATE": "security/send_login.html",
264 "VERIFY_TEMPLATE": "security/verify.html",
265 "TWO_FACTOR_VERIFY_CODE_TEMPLATE": "security/two_factor_verify_code.html",
266 "TWO_FACTOR_SETUP_TEMPLATE": "security/two_factor_setup.html",
267 "TWO_FACTOR_SELECT_TEMPLATE": "security/two_factor_select.html",
268 "CONFIRMABLE": False,
269 "REGISTERABLE": False,
270 "RECOVERABLE": False,
271 "TRACKABLE": False,
272 "PASSWORDLESS": False,
273 "CHANGEABLE": False,
274 "TWO_FACTOR": False,
275 "SEND_REGISTER_EMAIL": True,
276 "REGISTER_EMAIL_EXISTING_USERNAME_TEMPLATE": "security/email/"
277 "welcome_existing_username",
278 "REGISTER_EMAIL_EXISTING_TEMPLATE": "security/email/welcome_existing",
279 "REGISTER_EMAIL_TEMPLATE": "security/email/welcome",
280 "SEND_PASSWORD_CHANGE_EMAIL": True,
281 "SEND_PASSWORD_RESET_EMAIL": True,
282 "SEND_PASSWORD_RESET_NOTICE_EMAIL": True,
283 "LOGIN_WITHIN": timedelta(days=1),
284 "CHANGE_EMAIL": False,
285 "CHANGE_EMAIL_TEMPLATE": "security/change_email.html",
286 "CHANGE_EMAIL_WITHIN": timedelta(hours=2),
287 "CHANGE_EMAIL_URL": "/change-email",
288 "CHANGE_EMAIL_CONFIRM_URL": "/change-email-confirm",
289 "CHANGE_EMAIL_ERROR_VIEW": None, # spa
290 "POST_CHANGE_EMAIL_VIEW": None, # spa
291 "CHANGE_EMAIL_SALT": "change-email-salt",
292 "CHANGE_EMAIL_SUBJECT": _("Confirm your new email address"),
293 "CHANGE_EMAIL_EMAIL_TEMPLATE": "security/email/change_email_instructions",
294 "CHANGE_USERNAME": False,
295 "CHANGE_USERNAME_TEMPLATE": "security/change_username.html",
296 "CHANGE_USERNAME_EMAIL_TEMPLATE": "security/email/change_username_notice",
297 "CHANGE_USERNAME_URL": "/change-username",
298 "POST_CHANGE_USERNAME_VIEW": None,
299 "SEND_USERNAME_CHANGE_EMAIL": True,
300 "TWO_FACTOR_AUTHENTICATOR_VALIDITY": 120,
301 "TWO_FACTOR_EMAIL_TEMPLATE": "security/email/two_factor_instructions",
302 "TWO_FACTOR_MAIL_VALIDITY": 300,
303 "TWO_FACTOR_SMS_VALIDITY": 120,
304 "TWO_FACTOR_ALWAYS_VALIDATE": True,
305 "TWO_FACTOR_LOGIN_VALIDITY": timedelta(days=30),
306 "TWO_FACTOR_VALIDITY_SALT": "tf-validity-salt",
307 "TWO_FACTOR_VALIDITY_COOKIE_NAME": "tf_validity",
308 "TWO_FACTOR_VALIDITY_COOKIE": {
309 "httponly": True,
310 "secure": True,
311 "samesite": "Strict",
312 },
313 "TWO_FACTOR_SETUP_SALT": "tf-setup-salt",
314 "TWO_FACTOR_SETUP_WITHIN": timedelta(minutes=30),
315 "TWO_FACTOR_RESCUE_EMAIL": True,
316 "TWO_FACTOR_RESCUE_EMAIL_TEMPLATE": "security/email/two_factor_rescue",
317 "MULTI_FACTOR_RECOVERY_CODES": False,
318 "MULTI_FACTOR_RECOVERY_CODES_N": 5,
319 "MULTI_FACTOR_RECOVERY_CODES_URL": "/mf-recovery-codes",
320 "MULTI_FACTOR_RECOVERY_CODES_TEMPLATE": "security/mf_recovery_codes.html",
321 "MULTI_FACTOR_RECOVERY_URL": "/mf-recovery",
322 "MULTI_FACTOR_RECOVERY_TEMPLATE": "security/mf_recovery.html",
323 "MULTI_FACTOR_RECOVERY_CODES_KEYS": None,
324 "MULTI_FACTOR_RECOVERY_CODE_TTL": None,
325 "OAUTH_ENABLE": False,
326 "OAUTH_BUILTIN_PROVIDERS": ["github", "google"],
327 "OAUTH_START_URL": "/login/oauthstart",
328 "OAUTH_RESPONSE_URL": "/login/oauthresponse",
329 "OAUTH_VERIFY_START_URL": "/login/oauth-verify-start",
330 "OAUTH_VERIFY_RESPONSE_URL": "/login/oauth-verify-response",
331 "CONFIRM_EMAIL_WITHIN": timedelta(days=2),
332 "RESET_PASSWORD_WITHIN": timedelta(days=1),
333 "LOGIN_WITHOUT_CONFIRMATION": False,
334 "AUTO_LOGIN_AFTER_CONFIRM": False,
335 "AUTO_LOGIN_AFTER_RESET": False,
336 "EMAIL_SENDER": LocalProxy(
337 lambda: current_app.config.get("MAIL_DEFAULT_SENDER", "no-reply@localhost")
338 ),
339 "TWO_FACTOR_RESCUE_MAIL": "no-reply@localhost",
340 "TOKEN_AUTHENTICATION_KEY": "auth_token",
341 "TOKEN_AUTHENTICATION_HEADER": "Authentication-Token",
342 "TOKEN_MAX_AGE": timedelta(minutes=15),
343 "TOKEN_EXPIRE_TIMESTAMP": lambda user: 0,
344 "REFRESH_TOKEN": False,
345 "REFRESH_TOKEN_SALT": "refresh-token-salt",
346 "REFRESH_TOKEN_MAX_AGE": timedelta(days=90),
347 "REFRESH_TOKEN_MAX_IDLE": timedelta(days=7),
348 "REFRESH_TOKEN_CLEANUP_EXPIRED": True,
349 "REFRESH_TOKEN_CLEANUP_REVOKED": False,
350 "REFRESH_TOKEN_URL": "/refresh-token",
351 "REFRESH_TOKEN_COOKIE_NAME": "fs_refresh",
352 "REFRESH_TOKEN_COOKIE": {
353 "samesite": "Strict",
354 "httponly": True,
355 "secure": True,
356 },
357 "CONFIRM_SALT": "confirm-salt",
358 "RESET_SALT": "reset-salt",
359 "LOGIN_SALT": "login-salt",
360 "CHANGE_SALT": "change-salt",
361 "REMEMBER_SALT": "remember-salt",
362 "DEFAULT_REMEMBER_ME": False,
363 "DEFAULT_HTTP_AUTH_REALM": _("Login Required"),
364 "EMAIL_SUBJECT_REGISTER": _("Welcome"),
365 "EMAIL_SUBJECT_CONFIRM": _("Please confirm your email"),
366 "EMAIL_SUBJECT_PASSWORDLESS": _("Login instructions"),
367 "EMAIL_SUBJECT_PASSWORD_NOTICE": _("Your password has been reset"),
368 "EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE": _("Your password has been changed"),
369 "EMAIL_SUBJECT_PASSWORD_RESET": _("Password reset instructions"),
370 "EMAIL_SUBJECT_USERNAME_CHANGE_NOTICE": _("Your username has been changed"),
371 "EMAIL_SUBJECT_USERNAME_RECOVERY": _("Your requested username"),
372 "EMAIL_PLAINTEXT": True,
373 "EMAIL_HTML": True,
374 "EMAIL_SUBJECT_TWO_FACTOR": _("Two-Factor Login"),
375 "EMAIL_SUBJECT_TWO_FACTOR_RESCUE": _("Two-Factor Rescue"),
376 "EMAIL_TEMPLATE_PASSWORDLESS": "security/email/login_instructions",
377 "EMAIL_TEMPLATE_CONFIRM": "security/email/confirmation_instructions",
378 "EMAIL_TEMPLATE_PASSWORD_RESET": "security/email/reset_instructions",
379 "EMAIL_TEMPLATE_PASSWORD_RESET_NOTICE": "security/email/reset_notice",
380 "EMAIL_TEMPLATE_PASSWORD_CHANGE_NOTICE": "security/email/change_notice",
381 "USER_IDENTITY_ATTRIBUTES": [
382 {"email": {"mapper": uia_email_mapper, "case_insensitive": True}}
383 ],
384 "PHONE_REGION_DEFAULT": "US",
385 "FRESHNESS": timedelta(hours=24),
386 "FRESHNESS_GRACE_PERIOD": timedelta(hours=1),
387 "FRESHNESS_ALLOW_AUTH_TOKEN": True,
388 "API_ENABLED_METHODS": ["session", "token"],
389 "DATETIME_FACTORY": naive_utcnow,
390 "TOTP_SECRETS": None,
391 "TOTP_ISSUER": None,
392 "SMS_SERVICE": "Dummy",
393 "SMS_SERVICE_CONFIG": {
394 "ACCOUNT_SID": None,
395 "AUTH_TOKEN": None,
396 "PHONE_NUMBER": None,
397 },
398 "TWO_FACTOR_REQUIRED": False,
399 "TWO_FACTOR_ENABLED_METHODS": ["email", "authenticator", "sms"],
400 "TWO_FACTOR_IMPLEMENTATIONS": {
401 "code": "flask_security.twofactor.CodeTfPlugin",
402 "webauthn": "flask_security.webauthn.WebAuthnTfPlugin",
403 },
404 "UNIFIED_SIGNIN": False,
405 "USERNAME_RECOVERY": False,
406 "USERNAME_RECOVERY_TEMPLATE": "security/recover_username.html",
407 "USERNAME_RECOVERY_EMAIL_TEMPLATE": "security/email/username_recovery",
408 "USERNAME_RECOVERY_URL": "/recover-username",
409 "US_SETUP_SALT": "us-setup-salt",
410 "US_SIGNIN_URL": "/us-signin",
411 "US_SIGNIN_SEND_CODE_URL": "/us-signin/send-code",
412 "US_SETUP_URL": "/us-setup",
413 "US_VERIFY_URL": "/us-verify",
414 "US_VERIFY_SEND_CODE_URL": "/us-verify/send-code",
415 "US_VERIFY_LINK_URL": "/us-verify-link",
416 "US_POST_SETUP_VIEW": ".us_setup", # endpoint or URL
417 "US_SIGNIN_TEMPLATE": "security/us_signin.html",
418 "US_SETUP_TEMPLATE": "security/us_setup.html",
419 "US_VERIFY_TEMPLATE": "security/us_verify.html",
420 "US_ENABLED_METHODS": ["password", "email", "authenticator", "sms"],
421 "US_MFA_REQUIRED": ["password", "email"],
422 "US_TOKEN_VALIDITY": 120,
423 "US_EMAIL_SUBJECT": _("Verification Code"),
424 "US_EMAIL_TEMPLATE": "security/email/us_instructions",
425 "US_SETUP_WITHIN": timedelta(minutes=30),
426 "US_SIGNIN_REPLACES_LOGIN": False,
427 "CACHE_CONTROL": {"private": True, "no-store": True},
428 "CSRF_PROTECT_MECHANISMS": AUTHN_MECHANISMS,
429 "CSRF_IGNORE_UNAUTH_ENDPOINTS": False,
430 "CSRF_COOKIE_NAME": None,
431 "CSRF_COOKIE": {
432 "samesite": "Strict",
433 "httponly": False,
434 "secure": True,
435 },
436 "CSRF_HEADER": "X-XSRF-Token",
437 "CSRF_COOKIE_REFRESH_EACH_REQUEST": False,
438 "BACKWARDS_COMPAT_AUTH_TOKEN": False,
439 "JOIN_USER_ROLES": True,
440 "USERNAME_ENABLE": False,
441 "USERNAME_REQUIRED": False,
442 "USERNAME_ALLOWED_CHARS": ["L", "N"],
443 "USERNAME_MIN_LENGTH": 4,
444 "USERNAME_MAX_LENGTH": 32,
445 "WEBAUTHN": False,
446 "WAN_CHALLENGE_BYTES": None, # uses system default
447 "WAN_POST_REGISTER_VIEW": ".wan_register", # endpoint or URL
448 "WAN_RP_NAME": "My Flask App",
449 "WAN_SALT": "wan-salt",
450 "WAN_REGISTER_TIMEOUT": 60000, # milliseconds
451 "WAN_REGISTER_TEMPLATE": "security/wan_register.html",
452 "WAN_REGISTER_URL": "/wan-register",
453 "WAN_REGISTER_WITHIN": timedelta(minutes=30),
454 "WAN_SIGNIN_TIMEOUT": 60000, # milliseconds
455 "WAN_SIGNIN_TEMPLATE": "security/wan_signin.html",
456 "WAN_SIGNIN_URL": "/wan-signin",
457 "WAN_SIGNIN_WITHIN": timedelta(minutes=1),
458 "WAN_DELETE_URL": "/wan-delete",
459 "WAN_VERIFY_URL": "/wan-verify",
460 "WAN_VERIFY_TEMPLATE": "security/wan_verify.html",
461 "WAN_ALLOW_AS_FIRST_FACTOR": True,
462 "WAN_ALLOW_AS_MULTI_FACTOR": True,
463 "WAN_ALLOW_USER_HINTS": True,
464 "WAN_ALLOW_AS_VERIFY": ["first", "secondary"],
465 "WAN_NAME_ALLOWED_CHARS": ["L", "N", "Pc", "Pd", "Zs"],
466 "WAN_NAME_MAX_LENGTH": 64,
467 "ZXCVBN_MINIMUM_SCORE": 3,
468 }
469
470 #: Default Flask-Security messages
471 _default_messages = {
472 "API_ERROR": (_("Input not appropriate for requested API"), "error"),
473 "GENERIC_AUTHN_FAILED": (
474 _("Authentication failed - identity or password/passcode invalid"),
475 "error",
476 ),
477 "GENERIC_RECOVERY": (
478 _(
479 "If that email address is in our system, "
480 "you will receive an email describing how to reset your password."
481 ),
482 "info",
483 ),
484 "GENERIC_US_SIGNIN": (
485 _("If that identity is in our system, you were sent a code."),
486 "info",
487 ),
488 "UNAUTHORIZED": (_("You do not have permission to view this resource."), "error"),
489 "UNAUTHENTICATED": (
490 _("You must sign in to view this resource."),
491 "error",
492 ),
493 "REAUTHENTICATION_REQUIRED": (
494 _("You must reauthenticate to access this endpoint"),
495 "error",
496 ),
497 "CONFIRM_REGISTRATION": (
498 _(
499 "Thank you. To confirm your email address %(email)s,"
500 " please click on the link"
501 " in the email we have just sent to you."
502 ),
503 "success",
504 ),
505 "EMAIL_CONFIRMED": (_("Thank you. Your email has been confirmed."), "success"),
506 "ALREADY_CONFIRMED": (_("Your email has already been confirmed."), "info"),
507 "INVALID_CONFIRMATION_TOKEN": (_("Invalid confirmation token."), "error"),
508 "EMAIL_ALREADY_ASSOCIATED": (
509 _("%(email)s is already associated with an account."),
510 "error",
511 ),
512 "IDENTITY_ALREADY_ASSOCIATED": (
513 _(
514 "Identity attribute '%(attr)s' with value '%(value)s' is already"
515 " associated with an account."
516 ),
517 "error",
518 ),
519 "IDENTITY_NOT_REGISTERED": (
520 _("Identity %(id)s not registered"),
521 "error",
522 ),
523 "OAUTH_HANDSHAKE_ERROR": (
524 _(
525 "An error occurred while communicating with the OAuth provider:"
526 " (%(exerror)s - %(exdesc)s). "
527 "Please try again."
528 ),
529 "error",
530 ),
531 "PASSWORD_MISMATCH": (_("Password does not match"), "error"),
532 "RETYPE_PASSWORD_MISMATCH": (_("Passwords do not match"), "error"),
533 "INVALID_REDIRECT": (_("Redirections outside the domain are forbidden"), "error"),
534 "INVALID_RECOVERY_CODE": (_("Recovery code invalid"), "error"),
535 "NO_RECOVERY_CODES_SETUP": (_("No recovery codes generated yet"), "info"),
536 "PASSWORD_RESET_REQUEST": (
537 _("Instructions to reset your password have been sent to %(email)s."),
538 "info",
539 ),
540 "PASSWORD_RESET_EXPIRED": (
541 _("You did not reset your password within %(within)s. "),
542 "error",
543 ),
544 "INVALID_RESET_PASSWORD_TOKEN": (_("Invalid reset password token."), "error"),
545 "CONFIRMATION_REQUIRED": (_("Email requires confirmation."), "error"),
546 "CONFIRMATION_REQUEST": (
547 _("Confirmation instructions have been sent to %(email)s."),
548 "info",
549 ),
550 "CONFIRMATION_EXPIRED": (
551 _("You did not confirm your email within %(within)s. "),
552 "error",
553 ),
554 "LOGIN_EXPIRED": (
555 _(
556 "You did not login within %(within)s. New instructions to login "
557 "have been sent to %(email)s."
558 ),
559 "error",
560 ),
561 "LOGIN_EMAIL_SENT": (
562 _("Instructions to login have been sent to %(email)s."),
563 "success",
564 ),
565 "INVALID_LOGIN_TOKEN": (_("Invalid login token."), "error"),
566 "DISABLED_ACCOUNT": (_("Account is disabled."), "error"),
567 "EMAIL_NOT_PROVIDED": (_("Email not provided"), "error"),
568 "INVALID_EMAIL_ADDRESS": (_("Invalid email address"), "error"),
569 "INVALID_CODE": (_("Invalid code"), "error"),
570 "INVALID_INPUT": (
571 _("Value entered is not valid for the field"),
572 "error",
573 ),
574 "INVALID_INPUT_LENGTH": (
575 _("Value entered must be less than %(length) characters"),
576 "error",
577 ),
578 "PASSWORD_NOT_PROVIDED": (_("Password not provided"), "error"),
579 "PASSWORD_INVALID_LENGTH": (
580 _("Password must be at least %(length)s characters"),
581 "error",
582 ),
583 "PASSWORD_TOO_SIMPLE": (_("Password not complex enough"), "error"),
584 "PASSWORD_BREACHED": (_("Password on breached list"), "error"),
585 "PASSWORD_BREACHED_SITE_ERROR": (
586 _("Failed to contact breached passwords site"),
587 "error",
588 ),
589 "PHONE_INVALID": (_("Phone number not valid e.g. missing country code"), "error"),
590 "USER_DOES_NOT_EXIST": (_("Specified user does not exist"), "error"),
591 "INVALID_PASSWORD": (_("Invalid password"), "error"),
592 "INVALID_PASSWORD_CODE": (_("Password or code submitted is not valid"), "error"),
593 "PASSWORDLESS_LOGIN_SUCCESSFUL": (_("You have successfully logged in."), "success"),
594 "FORGOT_PASSWORD": (_("Forgot password?"), "info"),
595 "PASSWORD_RESET": (
596 _(
597 "You successfully reset your password and you have been logged in "
598 "automatically."
599 ),
600 "success",
601 ),
602 "PASSWORD_RESET_NO_LOGIN": (
603 _(
604 "You successfully reset your password."
605 " Please authenticate using your new password."
606 ),
607 "success",
608 ),
609 "PASSWORD_IS_THE_SAME": (
610 _("Your new password must be different than your previous password."),
611 "error",
612 ),
613 "PASSWORD_CHANGE": (_("You successfully changed your password."), "success"),
614 "LOGIN": (_("Please log in to access this page."), "info"),
615 "REFRESH": (_("Please reauthenticate to access this page."), "info"),
616 "REFRESH_TOKEN_INVALID": (_("Refresh token is invalid (%(reason)s)"), "error"),
617 "REAUTHENTICATION_SUCCESSFUL": (_("Reauthentication successful"), "info"),
618 "ANONYMOUS_USER_REQUIRED": (
619 _("You can only access this endpoint when not logged in."),
620 "error",
621 ),
622 "CODE_HAS_BEEN_SENT": (_("Code has been sent."), "info"),
623 "FAILED_TO_SEND_CODE": (_("Failed to send code. Please try again later"), "error"),
624 "TWO_FACTOR_INVALID_TOKEN": (_("Invalid code"), "error"),
625 "TWO_FACTOR_LOGIN_SUCCESSFUL": (_("Your code has been confirmed"), "success"),
626 "TWO_FACTOR_CHANGE_METHOD_SUCCESSFUL": (
627 _("You successfully changed your two-factor method."),
628 "success",
629 ),
630 "TWO_FACTOR_PERMISSION_DENIED": (
631 _("You currently do not have permissions to access this page"),
632 "error",
633 ),
634 "TWO_FACTOR_METHOD_NOT_AVAILABLE": (_("Marked method is not valid"), "error"),
635 "TWO_FACTOR_DISABLED": (
636 _("You successfully disabled two-factor authorization."),
637 "success",
638 ),
639 "TWO_FACTOR_SETUP_EXPIRED": (
640 _("Setup must be completed within %(within)s. Please start over."),
641 "error",
642 ),
643 "US_CURRENT_METHODS": (
644 _("Currently active sign in options: %(method_list)s."),
645 "info",
646 ),
647 "US_METHOD_NOT_AVAILABLE": (_("Requested method is not valid"), "error"),
648 "US_SETUP_EXPIRED": (
649 _("Setup must be completed within %(within)s. Please start over."),
650 "error",
651 ),
652 "US_SETUP_SUCCESSFUL": (_("Unified sign in setup successful"), "info"),
653 "US_SPECIFY_IDENTITY": (_("You must specify a valid identity to sign in"), "error"),
654 "USE_CODE": (_("Use this code to sign in: %(code)s"), "info"),
655 "USERNAME_CHANGE": (_("You successfully changed your username"), "success"),
656 "USERNAME_INVALID_LENGTH": (
657 _(
658 "Username must be at least %(min)d characters and less than"
659 " %(max)d characters"
660 ),
661 "error",
662 ),
663 "USERNAME_DISALLOWED_CHARACTERS": (
664 _("Username can contain only letters and numbers"),
665 "error",
666 ),
667 "USERNAME_NOT_PROVIDED": (_("Username not provided"), "error"),
668 "USERNAME_ALREADY_ASSOCIATED": (
669 _("%(username)s is already associated with an account."),
670 "error",
671 ),
672 "WEBAUTHN_EXPIRED": (
673 _("Passkey operations must be completed within %(within)s. Please start over."),
674 "error",
675 ),
676 "WEBAUTHN_NAME_REQUIRED": (
677 _("Nickname for new passkey is required."),
678 "error",
679 ),
680 "WEBAUTHN_NAME_INUSE": (
681 _("%(name)s is already associated with a passkey."),
682 "error",
683 ),
684 "WEBAUTHN_NAME_NOT_FOUND": (
685 _("%(name)s not registered with current user."),
686 "error",
687 ),
688 "WEBAUTHN_NAME_DISALLOWED_CHARACTERS": (
689 _(
690 "Passkey nicknames can contain only letters, numbers,"
691 " and limited punctuation."
692 ),
693 "error",
694 ),
695 "WEBAUTHN_CREDENTIAL_DELETED": (
696 _("Successfully deleted the passkey with name: %(name)s"),
697 "info",
698 ),
699 "WEBAUTHN_REGISTER_SUCCESSFUL": (
700 _("Successfully added the passkey with name: %(name)s"),
701 "info",
702 ),
703 "WEBAUTHN_CREDENTIAL_ID_INUSE": (
704 _("Passkey already registered."),
705 "error",
706 ),
707 "WEBAUTHN_UNKNOWN_CREDENTIAL_ID": (
708 _("Unregistered passkey."),
709 "error",
710 ),
711 "WEBAUTHN_ORPHAN_CREDENTIAL_ID": (
712 _("Passkey doesn't belong to any user."),
713 "error",
714 ),
715 "WEBAUTHN_NO_VERIFY": (
716 _("Could not verify passkey: %(cause)s."),
717 "error",
718 ),
719 "WEBAUTHN_CREDENTIAL_WRONG_USAGE": (
720 _("Passkey not registered for this use (first or secondary)"),
721 "error",
722 ),
723 "WEBAUTHN_MISMATCH_USER_HANDLE": (
724 _("Credential user handle didn't match"),
725 "error",
726 ),
727 "CHANGE_EMAIL_EXPIRED": (
728 _("Confirmation must be completed within %(within)s. Please start over."),
729 "error",
730 ),
731 "CHANGE_EMAIL_CONFIRMED": (
732 _("Change of email address confirmed"),
733 "success",
734 ),
735 "CHANGE_EMAIL_SENT": (
736 _(
737 "Instructions to confirm your new email address have"
738 " been sent to %(email)s."
739 ),
740 "success",
741 ),
742 "USERNAME_RECOVERY_REQUEST": (
743 _("If registered, your username will be sent to your email."),
744 "info",
745 ),
746 }
747
748
749 def _default_form_instantiator(
750 name: str, cls: t.Type[Form], *args: t.Any, **kwargs: dict[str, t.Any]
751 ) -> Form:
752 return cls(*args, **kwargs)
753
754
755 @dataclass
756 class FormInfo:
757 """
758 Each view form has a name - assigned by Flask-Security.
759 As part of every request, the form is instantiated using (usually) request.form or
760 request.json.
761 The default instantiator simply uses the class constructor - however
762 applications can provide their OWN instantiator which can do pretty much anything
763 as long as it returns an instantiated form. The 'cls' argument is optional since
764 the instantiator COULD be form agnostic (using the form name to differentiate).
765
766 The instantiator callable will always be called from a flask request context
767 and receive the following arguments::
768
769 (name, form_cls_name (optional), **kwargs)
770
771 kwargs will always have `formdata` and often will have `meta`. All kwargs
772 must be passed to the underlying form constructor.
773
774 See :py:meth:`flask_security.Security.set_form_info`
775
776 .. versionadded:: 5.1.0
777 """
778
779 instantiator: t.Callable[..., Form] = _default_form_instantiator
780 cls: t.Type[Form] | None = None
781
782
783 def _user_loader(user_id):
784 """Load based on fs_uniquifier (alternative_id).
785 If the db model and db are properly configured and set there is no way we should
786 ever see a null user_id. But it is clearly wrong.
787 """
788 if not user_id:
789 return None
790 user = _security.datastore.find_user(fs_uniquifier=str(user_id))
791 if user and user.active:
792 set_request_attr("fs_authn_via", "session")
793 set_request_attr("fs_paa", session.get("fs_paa", 0))
794 return user
795 return None
796
797
798 def _request_loader(request):
799 # Short-circuit if we have already been called and verified.
800 # This can happen since Flask-Login will call us (if no session) and our own
801 # decorator @auth_token_required can call us.
802 # N.B. we don't call current_user here since that in fact might try and LOAD
803 # a user - which would call us again.
804 if get_request_attr("fs_authn_via") == "token":
805 return g._login_user
806
807 header_key = cv("TOKEN_AUTHENTICATION_HEADER")
808 args_key = cv("TOKEN_AUTHENTICATION_KEY")
809 header_token = request.headers.get(header_key, None)
810 token = request.args.get(args_key, header_token)
811 if request.is_json:
812 data = request.get_json(silent=True) or {}
813 if isinstance(data, dict):
814 token = data.get(args_key, token)
815
816 try:
817 tdata = parse_auth_token(token)
818 # Fallback to fs_uniquifier - allows upgrading to token_uniquifier while
819 # old tokens still work.
820 user = None
821 if hasattr(_security.datastore.user_model, "fs_token_uniquifier"):
822 user = _security.datastore.find_user(fs_token_uniquifier=tdata["uid"])
823 if not user:
824 user = _security.datastore.find_user(fs_uniquifier=tdata["uid"])
825 except Exception:
826 return None
827
828 if user and user.active and user.verify_auth_token(tdata):
829 set_request_attr("fs_authn_via", "token")
830 if cv("FRESHNESS_ALLOW_AUTH_TOKEN"):
831 set_request_attr("fs_paa", tdata.get("fs_paa", 0))
832 return user
833
834 return None
835
836
837 def _identity_loader():
838 # N.B. once AnonymousUser is gone - can just check current_user
839 if current_user and hasattr(current_user, "fs_uniquifier"):
840 return Identity(current_user.fs_uniquifier)
841 return None
842
843
844 def _on_identity_loaded(sender, identity):
845 if current_user and hasattr(current_user, "fs_uniquifier"):
846 identity.provides.add(UserNeed(current_user.fs_uniquifier))
847
848 for role in getattr(current_user, "roles", []):
849 identity.provides.add(RoleNeed(role.name))
850 for fsperm in role.get_permissions():
851 identity.provides.add(_FsPermNeed(fsperm))
852
853 identity.user = current_user
854
855
856 def _get_login_manager(app, security):
857 lm = LoginManager()
858 # Flask-Login is likely going in the direction of removing AnonymousUser
859 # however this might wreak havoc on applications that just assume that
860 # current_user is always set.
861 if cv("ANONYMOUS_USER_DISABLED", app=app):
862 lm.anonymous_user = lambda: None
863 else:
864 lm.anonymous_user = AnonymousUser
865
866 lm.user_loader(_user_loader)
867 lm.request_loader(_request_loader)
868 # Set Flask-Login handler so @login_required will have same behavior as
869 # @auth_required
870 lm.unauthorized_callback = security._unauthn_handler
871
872 # Note: since we redirect unauthenticated requests to us - we no longer need to
873 # mess with Flask-Login login_view, or message settings.
874 # We also (5.4.0) stop doing anything with need_fresh_login - we support time-based
875 # freshness.
876
877 lm.init_app(app)
878 return lm
879
880
881 def _get_principal(app):
882 p = Principal(app, use_sessions=False)
883 p.identity_loader(_identity_loader)
884 return p
885
886
887 def _get_pwd_context(app: flask.Flask) -> CryptContext:
888 pw_hash = cv("PASSWORD_HASH", app=app)
889 schemes = cv("PASSWORD_SCHEMES", app=app)
890 deprecated = cv("DEPRECATED_PASSWORD_SCHEMES", app=app)
891 if pw_hash not in schemes:
892 allowed = ", ".join(schemes[:-1]) + " and " + schemes[-1]
893 raise ValueError(
894 f"Invalid password hashing scheme {pw_hash}. Allowed values are {allowed}"
895 )
896 cc = CryptContext(
897 schemes=schemes,
898 default=pw_hash,
899 deprecated=deprecated,
900 **cv("PASSWORD_HASH_PASSLIB_OPTIONS", app=app),
901 )
902 return cc
903
904
905 def _get_hashing_context(app: flask.Flask) -> CryptContext:
906 schemes = cv("HASHING_SCHEMES", app=app)
907 deprecated = cv("DEPRECATED_HASHING_SCHEMES", app=app)
908 return CryptContext(schemes=schemes, deprecated=deprecated)
909
910
911 def _get_serializer(app, name, serializer=URLSafeTimedSerializer):
912 secret_key = app.config.get("SECRET_KEY")
913 derived_keys = app.config.get("SECRET_KEY_FALLBACKS")
914
915 secret_keys = [secret_key] + (
916 derived_keys if isinstance(derived_keys, list) else []
917 )
918 salt = cv(f"{name.upper()}_SALT", app=app)
919 return serializer(secret_keys, salt=salt)
920
921
922 def _context_processor():
923 return dict(
924 url_for_security=url_for_security,
925 security=_security,
926 _fs_is_user_authenticated=is_user_authenticated,
927 )
928
929
930 class RoleMixin:
931 """Mixin for `Role` model definitions"""
932
933 if t.TYPE_CHECKING: # pragma: no cover
934 id: int
935 name: str
936 description: str | None
937 permissions: list[str] | None
938 update_datetime: datetime
939
940 def __init__(self, **kwargs: t.Any): ...
941
942 def __eq__(self, other: object) -> bool:
943 if isinstance(other, RoleMixin) or isinstance(other, str):
944 return self.name == other or self.name == getattr(other, "name", None)
945 return NotImplemented # pragma: no cover
946
947 def __ne__(self, other: object) -> bool:
948 if isinstance(other, RoleMixin) or isinstance(other, str):
949 return not self.__eq__(other)
950 return NotImplemented # pragma: no cover
951
952 def __hash__(self) -> int:
953 return hash(self.name) # pragma: no cover
954
955 def get_permissions(self) -> set[str]:
956 """
957 Return set of permissions associated with role.
958
959 .. versionadded:: 3.3.0
960 """
961 if hasattr(self, "permissions") and self.permissions:
962 return set(self.permissions)
963 return set()
964
965
966 class UserMixin(BaseUserMixin):
967 """Mixin for `User` model definitions"""
968
969 if t.TYPE_CHECKING: # pragma: no cover
970 # These are defined in the applications Model files.
971 id: int
972 email: str
973 username: str | None
974 password: str | None
975 active: bool
976 fs_uniquifier: str
977 fs_token_uniquifier: str
978 fs_webauthn_user_handle: str
979 confirmed_at: datetime | None
980 last_login_at: datetime
981 current_login_at: datetime
982 last_login_ip: str | None
983 current_login_ip: str | None
984 login_count: int
985 tf_primary_method: str | None
986 tf_totp_secret: str | None
987 tf_phone_number: str | None
988 mf_recovery_codes: list[str] | None
989 us_phone_number: str | None
990 us_totp_secrets: str | bytes | None
991 create_datetime: datetime
992 update_datetime: datetime
993 roles: list[RoleMixin]
994 webauthn: list[WebAuthnMixin]
995 refresh_trackers: list[RefreshTrackerMixin]
996
997 def __init__(self, **kwargs: t.Any): ...
998
999 def get_id(self) -> str:
1000 """Returns the user identification attribute. 'Alternative-token' for
1001 Flask-Login. This is always ``fs_uniquifier``.
1002
1003 .. versionadded:: 3.4.0
1004 """
1005 return str(self.fs_uniquifier)
1006
1007 @property
1008 def is_active(self) -> bool:
1009 """Returns `True` if the user is active."""
1010 return self.active
1011
1012 def get_auth_token(self) -> str | bytes:
1013 """Constructs the user's authentication token.
1014
1015 :raises ValueError: If ``fs_token_uniquifier`` is part of model but not set.
1016
1017 Uses ``fs_uniquifier`` or ``fs_token_uniquifier`` (if in the UserModel)
1018 to identify this user. If ``fs_token_uniquifier`` is used then
1019 changing password doesn't invalidate auth tokens.
1020
1021 Calls :meth:`.UserMixin.augment_auth_token` which applications can override
1022 to add any additional information.
1023
1024 The returned value is securely signed using the ``remember_token_serializer``
1025
1026 .. versionchanged:: 4.0.0
1027 If user model has ``fs_token_uniquifier`` - use that (raise ValueError
1028 if not set). Otherwise, fallback to using ``fs_uniquifier``.
1029 .. versionchanged:: 5.4.0
1030 New format - a dict with a version string. Add a token-based expiry
1031 option as well as a session id.
1032 .. versionchanged:: 5.5.0
1033 Remove session id (never set or used); added fs_paa (last authentication
1034 timestamp)
1035 """
1036 from .proxies import _datastore
1037
1038 uid = getattr(self, _datastore.get_token_uniquifier_name())
1039 if not uid:
1040 raise ValueError()
1041 tdata: dict[str, t.Any] = {
1042 "ver": str(5),
1043 "uid": uid,
1044 "fs_paa": time.time(), # equivalent of session["fs_paa"]
1045 "exp": int(cv("TOKEN_EXPIRE_TIMESTAMP")(self)), # if >0 then shorter of
1046 # :data:SECURITY_MAX_AGE and this.
1047 }
1048 # Let application add things
1049 self.augment_auth_token(tdata)
1050
1051 # Serialize and sign
1052 return _security.remember_token_serializer.dumps(tdata)
1053
1054 def augment_auth_token(self, tdata: dict[str, t.Any]) -> None:
1055 """Override this to add/modify parts of the auth token.
1056 Additions to the dict can be made here and verified in
1057 :meth:`.UserMixin.verify_auth_token`
1058
1059 .. versionadded:: 5.4.0
1060 """
1061 return
1062
1063 def verify_auth_token(self, tdata: dict[str, t.Any]) -> bool:
1064 """
1065 Override this to perform additional verification of contents of auth token.
1066 Prior to this being called the token has been validated (via signing)
1067 and has not expired (either with MAX_AGE or specific 'exp' value).
1068
1069 :param tdata: a dictionary just as in augment_auth_token()
1070 :return: True if auth token represented by tdata is valid, False otherwise.
1071
1072 .. versionadded:: 3.3.0
1073
1074 .. versionchanged:: 5.4.0
1075 Now receives a dictionary.
1076 """
1077 return True
1078
1079 def has_role(self, role: str | RoleMixin) -> bool:
1080 """Returns `True` if the user identifies with the specified role.
1081
1082 :param role: A role name or `Role` instance"""
1083 if isinstance(role, str):
1084 return role in (role.name for role in self.roles)
1085 else:
1086 return role in self.roles
1087
1088 def has_permission(self, permission: str) -> bool:
1089 """
1090 Returns `True` if user has this permission (via a role it has).
1091
1092 :param permission: permission string name
1093
1094 .. versionadded:: 3.3.0
1095
1096 """
1097 for role in self.roles:
1098 if permission in role.get_permissions():
1099 return True
1100 return False
1101
1102 def get_security_payload(self) -> dict[str, t.Any]:
1103 """Serialize user object as response payload.
1104 Override this to return any/all the user object in JSON responses.
1105 Return a dict.
1106 """
1107 return {}
1108
1109 def get_redirect_qparams(
1110 self, existing: dict[str, t.Any] | None = None
1111 ) -> dict[str, t.Any]:
1112 """Return user info that will be added to redirect query params.
1113
1114 :param existing: Existing dict of params to update.
1115 :return: A dict whose keys are query params and values are query values.
1116
1117 The returned dict will always have an 'identity' key/value.
1118 If the User Model contains 'email', an 'email' key/value will be added.
1119 All keys provided in 'existing' will also be merged in.
1120
1121 .. versionadded:: 3.2.0
1122
1123 .. versionchanged:: 4.0.0
1124 Add 'identity' using UserMixin.calc_username() - email is optional.
1125 """
1126 if not existing:
1127 existing = {}
1128 if hasattr(self, "email"):
1129 existing.update({"email": self.email})
1130 existing.update({"identity": self.calc_username()})
1131 return existing
1132
1133 def verify_and_update_password(self, password: str) -> bool:
1134 """Returns ``True`` if the password is valid for the specified user.
1135
1136 Additionally, the hashed password in the database is updated if the
1137 hashing algorithm happens to have changed.
1138
1139 N.B. you MUST call DB commit if you are using a session-based datastore
1140 (such as SqlAlchemy) since the user instance might have been altered
1141 (i.e. ``app.security.datastore.commit()``).
1142 This is usually handled in the view.
1143
1144 :param password: A plaintext password to verify
1145
1146 .. versionadded:: 3.2.0
1147 """
1148 return verify_and_update_password(password, self)
1149
1150 def calc_username(self) -> str:
1151 """Come up with the best 'username' based on how the app
1152 is configured (via :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`).
1153 Returns the first non-null match (and converts to string).
1154 In theory this should NEVER be the empty string unless the user
1155 record isn't actually valid.
1156
1157 .. versionadded:: 3.4.0
1158 """
1159 cusername = None
1160 for attr in get_identity_attributes():
1161 cusername = getattr(self, attr, None)
1162 if cusername is not None and len(str(cusername)) > 0:
1163 break
1164 return str(cusername) if cusername is not None else ""
1165
1166 def us_send_security_token(self, method: str, **kwargs: t.Any) -> str | None:
1167 """Generate and send the security code for unified sign in.
1168
1169 :param method: The method in which the code will be sent
1170 :param kwargs: Opaque parameters that are subject to change at any time
1171 :return: None if successful, error message if not.
1172
1173 This is a wrapper around :meth:`us_send_security_token`
1174 that can be overridden to manage any errors.
1175
1176 .. versionadded:: 3.4.0
1177 """
1178 try:
1179 us_send_security_token(self, method, **kwargs)
1180 except Exception:
1181 return get_message("FAILED_TO_SEND_CODE")[0]
1182 return None
1183
1184 def tf_send_security_token(self, method: str, **kwargs: t.Any) -> str | None:
1185 """Generate and send the security code for two-factor.
1186
1187 :param method: The method in which the code will be sent
1188 :param kwargs: Opaque parameters that are subject to change at any time
1189 :return: None if successful, error message if not.
1190
1191 This is a wrapper around :meth:`tf_send_security_token`
1192 that can be overridden to manage any errors.
1193
1194 .. versionadded:: 3.4.0
1195 """
1196 try:
1197 tf_send_security_token(self, method, **kwargs)
1198 except Exception:
1199 return get_message("FAILED_TO_SEND_CODE")[0]
1200 return None
1201
1202 def check_tf_required(
1203 self, tf_setup_methods: list[tuple[str, str]], tf_fresh: bool
1204 ) -> tuple[bool, list[tuple[str, str]]]:
1205 """Check if current user requires two-factor authentication.
1206
1207 :param tf_setup_methods: A tuple of (two_factor method, label) - methods
1208 the user has already set up (from all two-factor implementations)
1209 :param tf_fresh: if True then user has recently completed
1210 two-factor authentication on the requesting device
1211 :return: Whether TFA is required for this user and a possibly augmented
1212 list of allowable methods
1213
1214 The default implementation uses global configuration values.
1215 An application could for example require two-factor authentication for users
1216 with a particular role, or not require two-factor for 'new' users.
1217 This is called AFTER the user has successfully authenticated.
1218
1219 .. versionadded:: 5.8.0
1220 """
1221 if cv("TWO_FACTOR_REQUIRED") or len(tf_setup_methods) > 0:
1222 if cv("TWO_FACTOR_ALWAYS_VALIDATE") or not tf_fresh:
1223 return True, tf_setup_methods
1224 return False, tf_setup_methods
1225
1226 def check_tf_required_setup(self) -> bool:
1227 """Check if current user requires two-factor authentication.
1228 This is called as part of two-factor setup to inform the caller
1229
1230 N.B. this is only called from tf-setup - not from webauthn and
1231 is only used to improve UX - the above method check_tf_required is the
1232 definitive answer in the authentication path.
1233
1234 .. versionadded:: 5.8.0
1235 """
1236 return cv("TWO_FACTOR_REQUIRED")
1237
1238 def track_failed_authn(self, auth_type: str, tfa: bool = False) -> None:
1239 """Called when a user fails to authenticate.
1240
1241 The following flask-Security endpoints call this:
1242
1243 - security.login
1244 - security.verify
1245 - security.us_signin
1246 - security.us_verify
1247 - security.us_verify_link
1248 - security.wan_signin_response
1249 - security.wan_verify_response
1250 - security.two_factor_token_validation
1251
1252 auth_type is what failed:
1253
1254 - password
1255 - passcode (unified signin)
1256 - passkey (webauthn)
1257
1258 tfa - True if it was a second factor that failed
1259
1260 This is called any time a credential is presented but is not verifiable.
1261 It is NOT called on API errors or missing data.
1262
1263 Use Flask's request proxy to get information such as endpoint. Note that
1264 it is possible there isn't a Flask Request if this is called from the cli.
1265
1266 The default implementation sends the user_failed_authn signal.
1267
1268 .. versionadded:: 5.8.0
1269 """
1270 user_failed_authn.send(
1271 current_app._get_current_object(), # type: ignore[attr-defined]
1272 _async_wrapper=current_app.ensure_sync,
1273 user=self,
1274 auth_type=auth_type,
1275 tfa=tfa,
1276 )
1277
1278 def is_locked(self, form_error: list[str] | None = None) -> bool:
1279 """
1280 Return True if the user account is locked.
1281
1282 It is called from the following endpoints:
1283
1284 - security.login
1285 - security.us_signin
1286 - security.forgot_password
1287 - security.recover_username
1288 - security.wan_signin_response
1289 - oauthresponse
1290
1291 For authentication endpoints it is called AFTER the credentials have been
1292 verified, and AFTER the check whether the user is disabled/deactivated
1293 but before the check for confirmation required.
1294
1295 form_error is a list that could be associated with a form - used to convey
1296 any error messages.
1297
1298 .. tip::
1299 This does not prevent an already authenticated user from continuing to access
1300 the system. Think of it similar to the confirmation sequence.
1301 See :meth:`.UserDatastore.deactivate_user`.
1302
1303 .. versionadded:: 5.8.0
1304 """
1305 return False
1306
1307
1308 class WebAuthnMixin:
1309 if t.TYPE_CHECKING: # pragma: no cover
1310 # These are defined in the applications Model files.
1311 id: int
1312 name: str
1313 credential_id: bytes
1314 public_key: bytes
1315 sign_count: int
1316 transports: list[str] | None
1317 backup_state: bool
1318 device_type: str
1319 extensions: str | None
1320 lastuse_datetime: datetime
1321 usage: str
1322
1323 def __init__(self, **kwargs: t.Any): ...
1324
1325 def get_user_mapping(self) -> dict[str, t.Any]:
1326 """
1327 Return the filter needed by find_user() to get the user
1328 associated with this webauthn credential.
1329 Note that this probably has to be overridden when using mongoengine.
1330
1331 .. versionadded:: 5.0.0
1332 """
1333 return dict(id=self.user_id) # type: ignore
1334
1335
1336 class RefreshTrackerMixin:
1337 if t.TYPE_CHECKING: # pragma: no cover
1338 # These are defined in the application's Model files.
1339 id: int
1340 name: str
1341 # refresh_family and gen track rotation and lets the app react
1342 refresh_family: str
1343 gen: int
1344 expires_at: datetime
1345 revoked_at: datetime | None
1346 last_used_at: datetime
1347
1348 def __init__(self, **kwargs: t.Any): ...
1349
1350
1351 class AnonymousUser(AnonymousUserMixin):
1352 """AnonymousUser definition"""
1353
1354 def __init__(self):
1355 self.roles = list()
1356
1357 def has_role(self, *args):
1358 """Returns `False`"""
1359 return False
1360
1361
1362 class Security:
1363 """The :class:`Security` class initializes the Flask-Security extension.
1364
1365 :param app: The application.
1366 :param datastore: An instance of a user datastore.
1367 :param register_blueprint: to register the Security blueprint or not.
1368 :param login_form: set form for the login view
1369 :param logout_form: set form for the logout view
1370 :param verify_form: set form for reauthentication due to freshness check
1371 :param change_email_form: set form for changing email address
1372 :param register_form: set form for the register view when
1373 :data:`SECURITY_CONFIRMABLE` is false (deprecated) or for the register view
1374 when :data:`SECURITY_USE_REGISTER_V2` is true.
1375 :param confirm_register_form: set form for the register view when
1376 :data:`SECURITY_CONFIRMABLE` is true (deprecated)
1377 :param forgot_password_form: set form for the forgot password view
1378 :param reset_password_form: set form for the reset password view
1379 :param change_password_form: set form for the change password view
1380 :param change_username_form: set form for the change username view
1381 :param send_confirmation_form: set form for the send confirmation view
1382 :param passwordless_login_form: set form for the passwordless login view
1383 :param two_factor_setup_form: set form for the 2FA setup view
1384 :param two_factor_verify_code_form: set form the the 2FA verify code view
1385 :param two_factor_rescue_form: set form for the 2FA rescue view
1386 :param two_factor_select_form: set form for selecting between active 2FA methods
1387 :param mf_recovery_codes_form: set form for retrieving and setting recovery codes
1388 :param mf_recovery_form: set form for multi factor recovery
1389 :param refresh_token_form: set form for the refresh token view
1390 :param username_recovery_form: set form for the username recovery view
1391 :param us_signin_form: set form for the unified sign in view
1392 :param us_setup_form: set form for the unified sign in setup view
1393 :param us_setup_validate_form: set form for the unified sign in setup validate view
1394 :param us_verify_form: set form for reauthenticating due to freshness check
1395 :param wan_register_form: set form for registering a webauthn security key
1396 :param wan_register_response_form: set form for registering a webauthn security key
1397 :param wan_signin_form: set form for authenticating with a webauthn security key
1398 :param wan_signin_response_form: set form for authenticating with a webauthn
1399 :param wan_delete_form: set form for deleting a webauthn security key
1400 :param wan_verify_form: set form for using a webauthn key to verify authenticity
1401 :param mail_util_cls: Class to use for sending emails. Defaults to :class:`MailUtil`
1402 :param password_util_cls: Class to use for password normalization/validation.
1403 Defaults to :class:`PasswordUtil`
1404 :param phone_util_cls: Class to use for phone number utilities.
1405 Defaults to :class:`PhoneUtil`
1406 :param render_template: function to use to render templates. The default is Flask's
1407 render_template() function.
1408 :param totp_cls: Class to use as TOTP factory. Defaults to :class:`Totp`
1409 :param username_util_cls: Class to use for normalizing and validating usernames.
1410 Defaults to :class:`UsernameUtil`
1411 :param webauthn_util_cls: Class to use for customizing WebAuthn registration
1412 and signin. Defaults to :class:`WebauthnUtil`
1413 :param mf_recovery_codes_util_cls: Class for generating, checking, encrypting
1414 and decrypting recovery codes. Defaults to :class:`MfRecoveryCodesUtil`
1415 :param oauth: An instance of authlib.integrations.flask_client.OAuth. If not set,
1416 Flask-Security will create one.
1417
1418 .. tip::
1419 Be sure that all your configuration values have been set PRIOR to
1420 instantiating this class. Some configuration values are set as attributes
1421 on the instance and therefore won't track any changes.
1422
1423 .. versionadded:: 3.4.0
1424 ``verify_form`` added as part of freshness/reauthentication
1425
1426 .. versionadded:: 3.4.0
1427 ``us_signin_form``, ``us_setup_form``, ``us_setup_validate_form``, and
1428 ``us_verify_form`` added as part of the :ref:`configuration:unified signin`
1429 feature.
1430
1431 .. versionadded:: 3.4.0
1432 ``totp_cls`` added to enable applications to implement replay protection - see
1433 :py:class:`Totp`.
1434
1435 .. versionadded:: 3.4.0
1436 ``phone_util_cls`` added to allow different phone number
1437 parsing implementations - see :py:class:`PhoneUtil`
1438
1439 .. versionadded:: 4.0.0
1440 ``mail_util_cls`` added to isolate mailing handling.
1441 ``password_util_cls`` added to encapsulate password validation/normalization.
1442
1443 .. versionadded:: 4.1.0
1444 ``username_util_cls`` added to encapsulate username handling.
1445
1446 .. versionadded:: 5.0.0
1447 ``wan_register_form``, ``wan_register_response_form``,
1448 ``webauthn_signin_form``, ``wan_signin_response_form``,
1449 ``webauthn_delete_form``, ``webauthn_verify_form``, ``tf_select_form``.
1450 .. versionadded:: 5.0.0
1451 ``WebauthnUtil`` class.
1452 .. versionadded:: 5.0.0
1453 Added support for multi-factor recovery codes ``mf_recovery_codes_form``,
1454 ``mf_recovery_form``.
1455 .. versionadded:: 5.1.0
1456 ``mf_recovery_codes_util_cls``, ``oauth``
1457 .. versionadded:: 5.5.0
1458 ``change_email_form`` in support of the
1459 :ref:`Change-Email<configuration:change-email>` feature.
1460 .. versionadded:: 5.6.0
1461 ``username_recovery_form``, ``change_username_form``,
1462
1463 .. versionchanged:: 5.7.0
1464 ``register_form`` default value is RegisterFormV2 and
1465 ``confirm_register_form`` default is now ``None``.
1466
1467 .. versionadded:: 5.9.0
1468 ``refresh_token_form``, ``logout_form``
1469
1470 .. deprecated:: 4.0.0
1471 ``send_mail`` and ``send_mail_task``. Replaced with ``mail_util_cls``.
1472 ``two_factor_verify_password_form`` removed.
1473 ``password_validator`` removed in favor of the new ``password_util_cls``.
1474 .. deprecated:: 5.0.0
1475 Passing in a LoginManager instance. Removed in 5.1.0
1476 .. deprecated:: 5.0.0
1477 json_encoder_cls is no longer honored since Flask 2.2 has deprecated it.
1478 .. deprecated:: 5.3.1
1479 Passing in an anonymous_user class. Removed in 5.4.0
1480 .. deprecated:: 5.6.0
1481 Passing in a confirm_register_form class.
1482 """
1483
1484 def __init__(
1485 self,
1486 app: flask.Flask | None = None,
1487 datastore: UserDatastore | None = None,
1488 register_blueprint: bool = True,
1489 *,
1490 login_form: t.Type[LoginForm] = LoginForm,
1491 logout_form: t.Type[LogoutForm] = LogoutForm,
1492 verify_form: t.Type[VerifyForm] = VerifyForm,
1493 change_email_form: t.Type[ChangeEmailForm] = ChangeEmailForm,
1494 change_username_form: t.Type[ChangeUsernameForm] = ChangeUsernameForm,
1495 confirm_register_form: t.Type[ConfirmRegisterForm] | None = None,
1496 register_form: t.Type[RegisterForm] | t.Type[RegisterFormV2] = RegisterFormV2,
1497 forgot_password_form: t.Type[ForgotPasswordForm] = ForgotPasswordForm,
1498 reset_password_form: t.Type[ResetPasswordForm] = ResetPasswordForm,
1499 change_password_form: t.Type[ChangePasswordForm] = ChangePasswordForm,
1500 send_confirmation_form: t.Type[SendConfirmationForm] = SendConfirmationForm,
1501 passwordless_login_form: t.Type[PasswordlessLoginForm] = PasswordlessLoginForm,
1502 two_factor_verify_code_form: t.Type[
1503 TwoFactorVerifyCodeForm
1504 ] = TwoFactorVerifyCodeForm,
1505 two_factor_setup_form: t.Type[TwoFactorSetupForm] = TwoFactorSetupForm,
1506 two_factor_rescue_form: t.Type[TwoFactorRescueForm] = TwoFactorRescueForm,
1507 two_factor_select_form: t.Type[TwoFactorSelectForm] = TwoFactorSelectForm,
1508 mf_recovery_codes_form: t.Type[MfRecoveryCodesForm] = MfRecoveryCodesForm,
1509 mf_recovery_form: t.Type[MfRecoveryForm] = MfRecoveryForm,
1510 refresh_token_form: t.Type[RefreshTokenForm] = RefreshTokenForm,
1511 us_signin_form: t.Type[UnifiedSigninForm] = UnifiedSigninForm,
1512 us_setup_form: t.Type[UnifiedSigninSetupForm] = UnifiedSigninSetupForm,
1513 us_setup_validate_form: t.Type[
1514 UnifiedSigninSetupValidateForm
1515 ] = UnifiedSigninSetupValidateForm,
1516 us_verify_form: t.Type[UnifiedVerifyForm] = UnifiedVerifyForm,
1517 wan_register_form: t.Type[WebAuthnRegisterForm] = WebAuthnRegisterForm,
1518 wan_register_response_form: t.Type[
1519 WebAuthnRegisterResponseForm
1520 ] = WebAuthnRegisterResponseForm,
1521 wan_signin_form: t.Type[WebAuthnSigninForm] = WebAuthnSigninForm,
1522 wan_signin_response_form: t.Type[
1523 WebAuthnSigninResponseForm
1524 ] = WebAuthnSigninResponseForm,
1525 wan_delete_form: t.Type[WebAuthnDeleteForm] = WebAuthnDeleteForm,
1526 wan_verify_form: t.Type[WebAuthnVerifyForm] = WebAuthnVerifyForm,
1527 mail_util_cls: t.Type[MailUtil] = MailUtil,
1528 password_util_cls: t.Type[PasswordUtil] = PasswordUtil,
1529 phone_util_cls: t.Type[PhoneUtil] = PhoneUtil,
1530 render_template: t.Callable[..., str] = _default_render_template,
1531 totp_cls: t.Type[Totp] = Totp,
1532 username_recovery_form: t.Type[UsernameRecoveryForm] = UsernameRecoveryForm,
1533 username_util_cls: t.Type[UsernameUtil] = UsernameUtil,
1534 webauthn_util_cls: t.Type[WebauthnUtil] = WebauthnUtil,
1535 mf_recovery_codes_util_cls: t.Type[MfRecoveryCodesUtil] = MfRecoveryCodesUtil,
1536 oauth: OAuth | None = None,
1537 **kwargs: t.Any,
1538 ):
1539 # to be nice and hopefully avoid backwards compat issues - we still accept
1540 # kwargs - but we don't do anything with them. If caller sends in some -
1541 # output a deprecation warning
1542 if len(kwargs) > 0:
1543 warnings.warn(
1544 "kwargs passed to the constructor are now ignored",
1545 DeprecationWarning,
1546 stacklevel=2,
1547 )
1548 self.app = app
1549 self._datastore = datastore
1550 self._register_blueprint = register_blueprint
1551 self._mail_util_cls = mail_util_cls
1552 self._password_util_cls = password_util_cls
1553 self._phone_util_cls = phone_util_cls
1554 self.render_template = render_template
1555 self._totp_cls = totp_cls
1556 self._username_util_cls = username_util_cls
1557 self._webauthn_util_cls = webauthn_util_cls
1558 self._mf_recovery_codes_util_cls = mf_recovery_codes_util_cls
1559 self._oauth = oauth
1560
1561 # Forms - we create a list from constructor.
1562 # BC - in init_app we will allow override of class.
1563 self.forms: dict[str, FormInfo] = {
1564 "login_form": FormInfo(cls=login_form),
1565 "logout_form": FormInfo(cls=logout_form),
1566 "verify_form": FormInfo(cls=verify_form),
1567 "confirm_register_form": FormInfo(cls=confirm_register_form),
1568 "register_form": FormInfo(cls=register_form),
1569 "forgot_password_form": FormInfo(cls=forgot_password_form),
1570 "reset_password_form": FormInfo(cls=reset_password_form),
1571 "change_email_form": FormInfo(cls=change_email_form),
1572 "change_password_form": FormInfo(cls=change_password_form),
1573 "change_username_form": FormInfo(cls=change_username_form),
1574 "send_confirmation_form": FormInfo(cls=send_confirmation_form),
1575 "passwordless_login_form": FormInfo(cls=passwordless_login_form),
1576 "two_factor_verify_code_form": FormInfo(cls=two_factor_verify_code_form),
1577 "two_factor_setup_form": FormInfo(cls=two_factor_setup_form),
1578 "two_factor_rescue_form": FormInfo(cls=two_factor_rescue_form),
1579 "two_factor_select_form": FormInfo(cls=two_factor_select_form),
1580 "mf_recovery_codes_form": FormInfo(cls=mf_recovery_codes_form),
1581 "mf_recovery_form": FormInfo(cls=mf_recovery_form),
1582 "refresh_token_form": FormInfo(cls=refresh_token_form),
1583 "username_recovery_form": FormInfo(cls=username_recovery_form),
1584 "us_signin_form": FormInfo(cls=us_signin_form),
1585 "us_setup_form": FormInfo(cls=us_setup_form),
1586 "us_setup_validate_form": FormInfo(cls=us_setup_validate_form),
1587 "us_verify_form": FormInfo(cls=us_verify_form),
1588 "wan_register_form": FormInfo(cls=wan_register_form),
1589 "wan_register_response_form": FormInfo(cls=wan_register_response_form),
1590 "wan_signin_form": FormInfo(cls=wan_signin_form),
1591 "wan_signin_response_form": FormInfo(cls=wan_signin_response_form),
1592 "wan_delete_form": FormInfo(cls=wan_delete_form),
1593 "wan_verify_form": FormInfo(cls=wan_verify_form),
1594 }
1595
1596 # Attributes not settable from init.
1597 self._unauthn_handler: t.Callable[..., ResponseValue] = default_unauthn_handler
1598 self._reauthn_handler: t.Callable[[timedelta, timedelta], ResponseValue] = (
1599 default_reauthn_handler
1600 )
1601 self._unauthz_handler: t.Callable[[str, list[str] | None], ResponseValue] = (
1602 default_unauthz_handler
1603 )
1604 self._render_json: t.Callable[
1605 [dict[str, t.Any], int, dict[str, str] | None, UserMixin | None],
1606 ResponseValue,
1607 ] = default_render_json
1608 self._want_json: t.Callable[[Request], bool] = _default_want_json
1609
1610 # Type attributes that we don't initialize until init_app time.
1611 self.remember_token_serializer: URLSafeTimedSerializer
1612 self.login_serializer: URLSafeTimedSerializer
1613 self.reset_serializer: URLSafeTimedSerializer
1614 self.change_email_serializer: URLSafeTimedSerializer
1615 self.confirm_serializer: URLSafeTimedSerializer
1616 self.us_setup_serializer: URLSafeTimedSerializer
1617 self.tf_setup_serializer: URLSafeTimedSerializer
1618 self.tf_validity_serializer: URLSafeTimedSerializer
1619 self.wan_serializer: URLSafeTimedSerializer
1620 self.refresh_token_serializer: URLSafeSerializer
1621 self.principal: Principal
1622 self.pwd_context: CryptContext
1623 self.hashing_context: CryptContext
1624 self._context_processors: dict[str, list[t.Callable[[], dict[str, t.Any]]]] = {}
1625 self.i18n_domain: FsDomain
1626 self.datastore: UserDatastore
1627 self.register_blueprint: bool
1628 self.two_factor_plugins: TfPlugin
1629 self.oauthglue: OAuthGlue | None = None
1630 self.datetime_factory: t.Callable[[], datetime] = (
1631 naive_utcnow # can be changed in init_app()
1632 )
1633
1634 self.login_manager: LoginManager
1635 self._mail_util: MailUtil
1636 self._phone_util: PhoneUtil
1637 self._password_util: PasswordUtil
1638 self._totp_factory: Totp
1639 self._username_util: UsernameUtil
1640 self._webauthn_util: WebauthnUtil
1641 self._mf_recovery_codes_util: MfRecoveryCodesUtil
1642
1643 # Add necessary attributes here to keep mypy happy
1644 self.trackable: bool = False
1645 self.change_email: bool = False
1646 self.change_username: bool = False
1647 self.confirmable: bool = False
1648 self.registerable: bool = False
1649 self.changeable: bool = False
1650 self.recoverable: bool = False
1651 self.refresh_token: bool = False
1652 self.two_factor: bool = False
1653 self.unified_signin: bool = False
1654 self.passwordless: bool = False
1655 self.username_recovery: bool = False
1656 self.webauthn: bool = False
1657
1658 self.support_mfa: bool = False
1659
1660 if app is not None and datastore is not None:
1661 self.init_app(app, datastore, register_blueprint=register_blueprint)
1662
1663 def init_app(
1664 self,
1665 app: flask.Flask,
1666 datastore: UserDatastore | None = None,
1667 register_blueprint: bool | None = None,
1668 **kwargs: t.Any,
1669 ) -> None:
1670 """Initializes the Flask-Security extension for the specified
1671 application and datastore implementation.
1672
1673 :param app: The application.
1674 :param datastore: An instance of a user datastore.
1675 :param register_blueprint: to register the Security blueprint or not.
1676 :param kwargs: Can be used to override/initialize any of the form names,
1677 or feature flags.
1678 All other kwargs are ignored.
1679
1680 If you create the Security instance with both an 'app' and 'datastore'
1681 you shouldn't call this - it will be called as part of the constructor.
1682 """
1683 self.app = app
1684
1685 if datastore:
1686 self._datastore = datastore
1687 if not self._datastore:
1688 raise ValueError("Datastore must be provided")
1689 self.datastore = self._datastore
1690
1691 if register_blueprint is not None:
1692 self._register_blueprint = register_blueprint
1693 self.register_blueprint = self._register_blueprint
1694
1695 # default post redirects to APPLICATION_ROOT, which itself defaults to "/"
1696 app.config.setdefault(
1697 "SECURITY_POST_LOGIN_VIEW", app.config.get("APPLICATION_ROOT", "/")
1698 )
1699 app.config.setdefault(
1700 "SECURITY_POST_LOGOUT_VIEW", app.config.get("APPLICATION_ROOT", "/")
1701 )
1702
1703 for key, value in _default_config.items():
1704 app.config.setdefault("SECURITY_" + key, value)
1705
1706 for key, value in _default_messages.items():
1707 app.config.setdefault("SECURITY_MSG_" + key, value)
1708
1709 # Override default forms
1710 # BC - kwarg value here overrides init/constructor time
1711 # BC - we allow forms to be set from config
1712 form_names = [
1713 "login_form",
1714 "logout_form",
1715 "verify_form",
1716 "change_email_form",
1717 "confirm_register_form",
1718 "register_form",
1719 "forgot_password_form",
1720 "reset_password_form",
1721 "change_password_form",
1722 "change_username_form",
1723 "send_confirmation_form",
1724 "passwordless_login_form",
1725 "two_factor_verify_code_form",
1726 "two_factor_setup_form",
1727 "two_factor_rescue_form",
1728 "two_factor_select_form",
1729 "mf_recovery_form",
1730 "mf_recovery_codes_form",
1731 "refresh_token_form",
1732 "username_recovery_form",
1733 "us_signin_form",
1734 "us_setup_form",
1735 "us_setup_validate_form",
1736 "us_verify_form",
1737 "wan_register_form",
1738 "wan_register_response_form",
1739 "wan_signin_form",
1740 "wan_signin_response_form",
1741 "wan_delete_form",
1742 "wan_verify_form",
1743 ]
1744 for form_name in form_names:
1745 if form_cls := kwargs.get(
1746 form_name, cv(form_name.upper(), app, strict=False)
1747 ):
1748 self.forms[form_name].cls = form_cls
1749
1750 # deprecate confirm_register_form, ConfirmRegisterForm and RegisterForm
1751 if self.forms["confirm_register_form"].cls:
1752 warnings.warn(
1753 "The ConfirmRegisterForm and the confirm_register_form"
1754 " option are"
1755 " deprecated as of version 5.6.0 and will be removed in a future"
1756 " release.",
1757 DeprecationWarning,
1758 stacklevel=2,
1759 )
1760 if self.forms["register_form"].cls and issubclass(
1761 self.forms["register_form"].cls, RegisterForm
1762 ):
1763 warnings.warn(
1764 "The RegisterForm is"
1765 " deprecated as of version 5.6.0 and will be removed in a future"
1766 " release. The form RegisterFormV2 should be sub-classed instead.",
1767 DeprecationWarning,
1768 stacklevel=2,
1769 )
1770 if not cv("USE_REGISTER_V2", app=app):
1771 warnings.warn(
1772 "The SECURITY_USE_REGISTER_V2 configuration option is"
1773 " deprecated as of version 5.7.0 and will be removed in a future"
1774 " release.",
1775 DeprecationWarning,
1776 stacklevel=2,
1777 )
1778 # Switch back to old register and confirm_register forms
1779 # Only do this is they haven't subclassed
1780 if self.forms["register_form"].cls == RegisterFormV2:
1781 self.forms["register_form"].cls = RegisterForm
1782 if not self.forms["confirm_register_form"].cls:
1783 self.forms["confirm_register_form"].cls = ConfirmRegisterForm
1784
1785 # The following will be set as attributes and initialized from constructor or
1786 # kwargs or config.
1787 attr_names = [
1788 "trackable",
1789 "registerable",
1790 "change_email",
1791 "change_username",
1792 "confirmable",
1793 "changeable",
1794 "recoverable",
1795 "refresh_token",
1796 "two_factor",
1797 "unified_signin",
1798 "username_recovery",
1799 "passwordless",
1800 "webauthn",
1801 "render_template",
1802 "datetime_factory",
1803 ]
1804 for attr in attr_names:
1805 if ov := kwargs.get(attr, cv(attr.upper(), app, strict=False)):
1806 setattr(self, attr, ov)
1807
1808 identity_loaded.connect_via(app)(_on_identity_loaded)
1809
1810 if hasattr(self.datastore, "user_model") and not hasattr(
1811 self.datastore.user_model, "fs_uniquifier"
1812 ): # pragma: no cover
1813 raise ValueError("User model must contain fs_uniquifier as of 4.0.0")
1814
1815 if not cv("PASSWORD_REQUIRED", app=app) and not cv("UNIFIED_SIGNIN", app=app):
1816 raise ValueError(
1817 "SECURITY_PASSWORD_REQUIRED can only be set to False if"
1818 " the SECURITY_UNIFIED_SIGNIN feature is enabled"
1819 )
1820
1821 # Check for pre-4.0 SECURITY_USER_IDENTITY_ATTRIBUTES format
1822 for uia in cv("USER_IDENTITY_ATTRIBUTES", app=app): # pragma: no cover
1823 if not isinstance(uia, dict):
1824 raise ValueError(
1825 "SECURITY_USER_IDENTITY_ATTRIBUTES changed semantics"
1826 " in 4.0 - please see release notes."
1827 )
1828 if len(list(uia.keys())) != 1:
1829 raise ValueError(
1830 "Each element in SECURITY_USER_IDENTITY_ATTRIBUTES"
1831 " must have one and only one key."
1832 )
1833
1834 if not isinstance(cv("TOKEN_MAX_AGE", app=app), timedelta):
1835 app.config["SECURITY_TOKEN_MAX_AGE"] = timedelta(
1836 seconds=cv("TOKEN_MAX_AGE", app=app)
1837 )
1838
1839 within_conversion = [
1840 "LOGIN_WITHIN",
1841 "CHANGE_EMAIL_WITHIN",
1842 "CONFIRM_EMAIL_WITHIN",
1843 "RESET_PASSWORD_WITHIN",
1844 "TWO_FACTOR_SETUP_WITHIN",
1845 "US_SETUP_WITHIN",
1846 "WAN_REGISTER_WITHIN",
1847 "WAN_SIGNIN_WITHIN",
1848 "TWO_FACTOR_LOGIN_VALIDITY",
1849 ]
1850 for key in within_conversion:
1851 within_value = cv(key, app=app)
1852 if not isinstance(within_value, timedelta):
1853 values = within_value.split()
1854 app.config[f"SECURITY_{key}"] = timedelta(**{values[1]: int(values[0])})
1855 warnings.warn(
1856 f"Non timedelta values for SECURITY_{key} are"
1857 f"deprecated as of 5.9",
1858 DeprecationWarning,
1859 stacklevel=2,
1860 )
1861
1862 self.login_manager = _get_login_manager(app, self)
1863 self._phone_util = self._phone_util_cls(app)
1864 self._mail_util = self._mail_util_cls(app)
1865 self._password_util = self._password_util_cls(app)
1866 self._username_util = self._username_util_cls(app)
1867 self._webauthn_util = self._webauthn_util_cls(app)
1868 self._mf_recovery_codes_util = self._mf_recovery_codes_util_cls(app)
1869 self.remember_token_serializer = _get_serializer(app, "remember")
1870 self.login_serializer = _get_serializer(app, "login")
1871 self.reset_serializer = _get_serializer(app, "reset")
1872 self.change_email_serializer = _get_serializer(app, "change_email")
1873 self.confirm_serializer = _get_serializer(app, "confirm")
1874 self.us_setup_serializer = _get_serializer(app, "us_setup")
1875 self.tf_setup_serializer = _get_serializer(app, "two_factor_setup")
1876 self.tf_validity_serializer = _get_serializer(app, "two_factor_validity")
1877 self.wan_serializer = _get_serializer(app, "wan")
1878 self.refresh_token_serializer = _get_serializer(
1879 app, "refresh_token", URLSafeSerializer
1880 )
1881 self.principal = _get_principal(app)
1882 self.pwd_context = _get_pwd_context(app)
1883 self.hashing_context = _get_hashing_context(app)
1884 self.i18n_domain = FsDomain(app)
1885
1886 if cv("WEBAUTHN", app=app) or cv("TWO_FACTOR", app):
1887 self.support_mfa = True
1888
1889 if cv("PASSWORDLESS", app=app):
1890 warnings.warn(
1891 "The passwordless feature was deprecated in Version 5.0.0"
1892 " and will be removed in the future. Please use the Unified Signin"
1893 " feature instead.",
1894 DeprecationWarning,
1895 stacklevel=2,
1896 )
1897 if cv("AUTO_LOGIN_AFTER_RESET", app=app):
1898 warnings.warn(
1899 "The auto-login after successful password reset functionality"
1900 " has been deprecated and will be removed in a future release.",
1901 DeprecationWarning,
1902 stacklevel=2,
1903 )
1904
1905 if cv("USERNAME_ENABLE", app):
1906 if hasattr(self.datastore, "user_model") and not hasattr(
1907 self.datastore.user_model, "username"
1908 ): # pragma: no cover
1909 raise ValueError(
1910 "User model must contain 'username' if"
1911 " SECURITY_USERNAME_ENABLE is True"
1912 )
1913 # if not already listed in user identity attributes, add it at the end
1914 uialist = []
1915 for uia in cv("USER_IDENTITY_ATTRIBUTES", app=app):
1916 uialist.append(list(uia.keys())[0])
1917 if "username" not in uialist:
1918 uias = cv("USER_IDENTITY_ATTRIBUTES", app=app).copy()
1919 uias.append(
1920 {
1921 "username": {
1922 "mapper": uia_username_mapper,
1923 "case_insensitive": True,
1924 }
1925 }
1926 )
1927 app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"] = uias
1928 self.user_identity_attributes = uias
1929
1930 # Add dynamic fields - probably overkill to check if these are our forms.
1931 fcls = self.forms["register_form"].cls
1932 if fcls and issubclass(fcls, RegisterFormMixin):
1933 fcls.username = _build_username_field(app)
1934 fcls = self.forms["confirm_register_form"].cls
1935 if fcls and issubclass(fcls, RegisterFormMixin):
1936 fcls.username = _build_username_field(app)
1937
1938 fcls = self.forms["login_form"].cls
1939 if fcls and issubclass(fcls, LoginForm):
1940 _build_login_form(app=app, fcls=fcls)
1941
1942 # new unified RegisterForm
1943 fcls = self.forms["register_form"].cls
1944 if fcls and issubclass(fcls, RegisterFormV2):
1945 _build_register_form(app=app, fcls=fcls)
1946 fcls = self.forms["change_username_form"].cls
1947 if fcls and issubclass(fcls, ChangeUsernameForm):
1948 fcls.username = _build_username_field(app=app)
1949
1950 # initialize two-factor plugins. Note that each implementation likely
1951 # has its own feature flag which will control whether it is active or not.
1952 self.two_factor_plugins = TfPlugin()
1953 for name, impl_class in cv("TWO_FACTOR_IMPLEMENTATIONS", app).items():
1954 module_path, class_name = impl_class.rsplit(".", 1)
1955 module = importlib.import_module(module_path)
1956 self.two_factor_plugins.register_tf_impl(
1957 app, name, getattr(module, class_name)
1958 )
1959
1960 if cv("OAUTH_ENABLE", app=app):
1961 self.oauthglue = OAuthGlue(app, self._oauth)
1962
1963 # register our blueprint/endpoints
1964 bp = None
1965 if self.register_blueprint:
1966 bp = _create_blueprint(app, self, __name__)
1967 self.two_factor_plugins.create_blueprint(app, bp, self)
1968 if self.oauthglue:
1969 self.oauthglue._create_blueprint(app, bp)
1970 if cv("CACHE_CONTROL", app=app):
1971 bp.after_request(_add_cache_control)
1972 app.register_blueprint(bp)
1973 app.context_processor(_context_processor)
1974
1975 if hasattr(app, "cli"):
1976 from .cli import users, roles
1977
1978 if un := cv("CLI_USERS_NAME", app, strict=True):
1979 app.cli.add_command(users, un)
1980 if rn := cv("CLI_ROLES_NAME", app, strict=True):
1981 app.cli.add_command(roles, rn)
1982
1983 # Alternate/code authentication configuration checks and setup
1984 alt_auth = False
1985 if cv("UNIFIED_SIGNIN", app=app):
1986 alt_auth = True
1987 if len(cv("US_ENABLED_METHODS", app=app)) < 1:
1988 raise ValueError("Must configure some US_ENABLED_METHODS")
1989 if "sms" in cv(
1990 "US_ENABLED_METHODS", app=app
1991 ) and not get_identity_attribute("us_phone_number", app=app):
1992 warnings.warn(
1993 "'sms' was enabled in SECURITY_US_ENABLED_METHODS;"
1994 " however 'us_phone_number' not configured in"
1995 " SECURITY_USER_IDENTITY_ATTRIBUTES",
1996 stacklevel=2,
1997 )
1998 if cv("TWO_FACTOR", app=app):
1999 alt_auth = True
2000 if len(cv("TWO_FACTOR_ENABLED_METHODS", app=app)) < 1:
2001 raise ValueError("Must configure some TWO_FACTOR_ENABLED_METHODS")
2002 if cv("MULTI_FACTOR_RECOVERY_CODES", app=app):
2003 # These rely on totp to generate
2004 alt_auth = True
2005
2006 if alt_auth:
2007 # cryptography is used to encrypt TOTP secrets
2008 self._check_modules("cryptography", "TWO_FACTOR or UNIFIED_SIGNIN")
2009
2010 need_qrcode = (
2011 cv("UNIFIED_SIGNIN", app=app)
2012 and "authenticator" in cv("US_ENABLED_METHODS", app=app)
2013 ) or (
2014 cv("TWO_FACTOR", app=app)
2015 and "authenticator" in cv("TWO_FACTOR_ENABLED_METHODS", app=app)
2016 )
2017 if need_qrcode:
2018 self._check_modules("qrcode", "TWO_FACTOR or UNIFIED_SIGNIN")
2019
2020 need_sms = (
2021 cv("UNIFIED_SIGNIN", app=app)
2022 and "sms" in cv("US_ENABLED_METHODS", app=app)
2023 ) or (
2024 cv("TWO_FACTOR", app=app)
2025 and "sms" in cv("TWO_FACTOR_ENABLED_METHODS", app=app)
2026 )
2027 if need_sms:
2028 sms_service = cv("SMS_SERVICE", app=app)
2029 if sms_service == "Twilio": # pragma: no cover
2030 self._check_modules("twilio", "SMS")
2031 if self._phone_util_cls == PhoneUtil:
2032 self._check_modules("phonenumbers", "SMS")
2033
2034 secrets = cv("TOTP_SECRETS", app=app)
2035 issuer = cv("TOTP_ISSUER", app=app)
2036 if not secrets or not issuer:
2037 raise ValueError("Both TOTP_SECRETS and TOTP_ISSUER must be set")
2038 self._totp_factory = self._totp_cls(secrets, issuer)
2039
2040 if cv("PASSWORD_COMPLEXITY_CHECKER", app=app) == "zxcvbn":
2041 self._check_modules("zxcvbn", "PASSWORD_COMPLEXITY_CHECKER")
2042
2043 if cv("WEBAUTHN", app=app):
2044 self._check_modules("webauthn", "WEBAUTHN")
2045 self._check_modules("nh3", "WEBAUTHN")
2046
2047 if cv("USERNAME_ENABLE", app=app) and self._username_util_cls == UsernameUtil:
2048 self._check_modules("nh3", "USERNAME_ENABLE")
2049
2050 # Register so other packages can reference our translations.
2051 app.jinja_env.globals["_fsdomain"] = self.i18n_domain.gettext
2052
2053 # Perform CSRF checks. Apps must initialize CSRFProtect PRIOR to
2054 # initializing us.
2055 self._csrf_init(app)
2056
2057 # register our JSON encoder extensions
2058 setup_json(app, bp)
2059
2060 app.extensions["security"] = self
2061
2062 def _check_modules(self, module, config_name): # pragma: no cover
2063 from importlib.util import find_spec
2064
2065 module_exists = find_spec(module)
2066 if not module_exists:
2067 raise ValueError(f"{module} is required for {config_name}")
2068
2069 return module_exists
2070
2071 @staticmethod
2072 def _csrf_init(app):
2073 # various config checks - some of these are opinionated in that there
2074 # could be a reason for some of these combinations - but in general
2075 # they cause strange behavior.
2076 # WTF_CSRF_ENABLED defaults to True if not set in Flask-WTF
2077 if not app.config.get("WTF_CSRF_ENABLED", True):
2078 return
2079 csrf = app.extensions.get("csrf", None)
2080
2081 # If they don't want ALL mechanisms protected, then they must
2082 # set WTF_CSRF_CHECK_DEFAULT=False so that our decorators get control.
2083 # And our decorators use csrf.protect()
2084 if cv("CSRF_PROTECT_MECHANISMS", app=app) != AUTHN_MECHANISMS:
2085 if not csrf:
2086 # This isn't good.
2087 raise ValueError(
2088 "CSRF_PROTECT_MECHANISMS defined but"
2089 " CsrfProtect not part of application."
2090 " Make sure to initialize CSRFProtect prior to"
2091 " initializing Flask-Security"
2092 )
2093 if app.config.get("WTF_CSRF_CHECK_DEFAULT", True):
2094 raise ValueError(
2095 "WTF_CSRF_CHECK_DEFAULT must be set to False if"
2096 " CSRF_PROTECT_MECHANISMS is set"
2097 )
2098 # We don't get control unless they turn off WTF_CSRF_CHECK_DEFAULT if
2099 # they have enabled global CSRFProtect.
2100 if (
2101 cv("CSRF_IGNORE_UNAUTH_ENDPOINTS", app=app)
2102 and csrf
2103 and app.config.get("WTF_CSRF_CHECK_DEFAULT", False)
2104 ):
2105 raise ValueError(
2106 "To ignore unauth endpoints you must set WTF_CSRF_CHECK_DEFAULT"
2107 " to False"
2108 )
2109
2110 csrf_cookie = cv("CSRF_COOKIE", app=app)
2111 # We used to have 'key' part of CSRF_COOKIE - and in csrf_cookie_handler
2112 # we removed that prior to setting the cookie. That was a terrible UI
2113 # decision since if the user sets the key - they likely will not set
2114 # all the other important things like samesite, secure etc.
2115 # Now CSRF_COOKIE_NAME is used for the name - we do the backwards compat
2116 # magic here
2117 if csrf_cookie and csrf_cookie.get("key", None):
2118 app.config["SECURITY_CSRF_COOKIE_NAME"] = csrf_cookie.pop("key")
2119 if cv("CSRF_COOKIE_NAME", app=app) and not csrf:
2120 # Common use case is for cookie value to be used as contents for header
2121 # which is only looked at when CsrfProtect is initialized.
2122 raise ValueError(
2123 "CSRF_COOKIE defined however CsrfProtect not part of application"
2124 )
2125
2126 if csrf:
2127 # Add configured header to WTF_CSRF_HEADERS
2128 if ch := cv("CSRF_HEADER", app=app):
2129 if ch not in app.config["WTF_CSRF_HEADERS"]:
2130 app.config["WTF_CSRF_HEADERS"].append(ch)
2131 if cv("CSRF_COOKIE_NAME", app=app):
2132 app.after_request(_csrf_cookie_handler)
2133
2134 def set_form_info(self, name: str, form_info: FormInfo) -> None:
2135 """Set form instantiation info.
2136
2137 :param name: Name of form.
2138 :param form_info: see :py:class:`FormInfo`
2139
2140 .. admonition:: Advanced
2141
2142 Forms (which are all FlaskForms) are instantiated at the start of each
2143 request. Normally this is done as part of a view by simply calling the
2144 form class constructor - Flask-WTForms handles filling it in from
2145 various request attributes.
2146
2147 The form classes themselves can be extended (e.g. to add or change fields)
2148 and the derived class can be set at `Security` constructor time,
2149 `init_app` time, or using this method.
2150
2151 This default implementation is suitable for most applications.
2152
2153 Some application might want to control the instantiation of forms, for
2154 example to be able to inject additional validation services.
2155 Using this method, a callable `instantiator` can be set that Flask-Security
2156 will call to return a properly instantiated form.
2157
2158 .. danger::
2159 Do not perform any validation as part of instantiation - many views have
2160 a bunch of logic PRIOR to calling the form validator.
2161
2162 .. versionadded:: 5.1.0
2163 """
2164 if name not in self.forms.keys():
2165 raise ValueError(f"Unknown form name {name}")
2166 if form_info.instantiator == _default_form_instantiator and not form_info.cls:
2167 raise ValueError(
2168 "If default form instantiator is used, a form class must be provided"
2169 )
2170 self.forms[name] = form_info
2171
2172 def render_json(
2173 self,
2174 cb: t.Callable[
2175 [dict[str, t.Any], int, dict[str, str] | None, UserMixin | None],
2176 ResponseValue,
2177 ],
2178 ) -> None:
2179 """Callback to render response payload as JSON.
2180
2181 :param cb: Callback function with
2182 signature (payload, code, headers=None, user=None)
2183
2184 :payload: A dict. Please see the formal API spec for details.
2185 :code: Http status code
2186 :headers: Headers object
2187 :user: the UserDatastore object (or None). Note that this is usually
2188 the same as current_user - but not always.
2189
2190 The default implementation simply returns::
2191
2192 headers["Content-Type"] = "application/json"
2193 payload = dict(meta=dict(code=code), response=payload)
2194 return make_response(jsonify(payload), code, headers)
2195
2196 .. important::
2197 Note that this has nothing to do with how the response is serialized.
2198 That is controlled by Flask and starting with Flask 2.2 that is managed
2199 by sub-classing Flask::JSONProvider. Flask-Security does this to add
2200 serializing lazy-strings.
2201
2202
2203 This can be used by applications to unify all their JSON API responses.
2204 This is called in a request context and should return a Response or something
2205 Flask can create a Response from.
2206
2207 .. versionadded:: 3.3.0
2208 """
2209 self._render_json = cb
2210
2211 def want_json(self, fn: t.Callable[[flask.Request], bool]) -> None:
2212 """Function that returns True if response should be JSON (based on the request)
2213
2214 :param fn: Function with the following signature (request)
2215
2216 :request: Werkzueg/Flask request
2217
2218 The default implementation returns True if either the Content-Type is
2219 "application/json" or the best Accept header value is "application/json".
2220
2221 .. versionadded:: 3.3.0
2222 """
2223 self._want_json = fn
2224
2225 def unauthz_handler(
2226 self,
2227 cb: t.Callable[[str, list[str] | None], ResponseValue],
2228 ) -> None:
2229 """
2230 Callback for failed authorization.
2231 This is called by the :func:`roles_required`, :func:`roles_accepted`,
2232 :func:`permissions_required`, or :func:`permissions_accepted`
2233 if a role or permission is missing.
2234
2235 :param cb: Callback function with signature (func, params)
2236
2237 :func_name: the decorator function name (e.g. 'roles_required')
2238 :params: list of what (if any) was passed to the decorator.
2239
2240 Should return a Response or something Flask can create a Response from.
2241 Can raise an exception if it is handled as part of
2242 flask.errorhandler(<exception>)
2243
2244 With the passed parameters, the application could deliver a concise error
2245 message.
2246
2247 .. versionadded:: 3.3.0
2248
2249 .. versionchanged:: 5.1.0
2250 Pass in the function name, not the function!
2251 """
2252 self._unauthz_handler = cb
2253
2254 def unauthn_handler(
2255 self,
2256 cb: t.Callable[[list[str], dict[str, str] | None], ResponseValue],
2257 ) -> None:
2258 """
2259 Callback when a protected endpoint is accessed without the required
2260 authentication.
2261 This is called by :func:`auth_required`, :func:`auth_token_required`
2262 or :func:`http_auth_required` if authentication fails.
2263 It is also called from Flask-Login's @login_required decorator.
2264
2265 :param cb: Callback function with signature (mechanisms=None, headers=None)
2266
2267 :mechanisms: List of which authentication mechanisms were tried
2268 :headers: dict of headers to return
2269
2270 Should return a Response or something Flask can create a Response from.
2271 Can raise an exception if it is handled as part of
2272 ``flask.errorhandler(<exception>)``
2273
2274 The default implementation will return a 401 response if the request was JSON,
2275 otherwise will redirect to the `login` view. In addition, the
2276 :data:`user_unauthenticated` signal is sent.
2277
2278 .. versionadded:: 3.3.0
2279
2280 .. versionchanged:: 5.4.0
2281 No longer calls Flask-Login and has complete logic built-in.
2282 """
2283 self._unauthn_handler = cb
2284
2285 def reauthn_handler(
2286 self, cb: t.Callable[[timedelta, timedelta], ResponseValue]
2287 ) -> None:
2288 """
2289 Callback when endpoint required a fresh authentication.
2290 This is called by :func:`auth_required`.
2291
2292 :param cb: Callback function with signature (within, grace)
2293
2294 :within: timedelta that endpoint required fresh authentication within.
2295 :grace: timedelta of grace period that endpoint allowed.
2296
2297 Should return a Response or something Flask can create a Response from.
2298 Can raise an exception if it is handled as part of
2299 ``flask.errorhandler(<exception>)``
2300
2301 The default implementation will return a 401 response if the request was JSON,
2302 otherwise will redirect to :py:data:`SECURITY_US_VERIFY_URL`
2303 (if :py:data:`SECURITY_UNIFIED_SIGNIN` is enabled)
2304 else to :py:data:`SECURITY_VERIFY_URL`.
2305 If both of those are None it sends an ``abort(401)``.
2306
2307 See :meth:`flask_security.auth_required` for details about freshness checking.
2308
2309 .. versionadded:: 3.4.0
2310 """
2311 self._reauthn_handler = cb
2312
2313 @property
2314 def mail_util(self) -> MailUtil:
2315 """Instance of mail_util_cls created at init_app() time.
2316 See :ref:`api:extendable classes`"""
2317 return self._mail_util
2318
2319 @property
2320 def password_util(self) -> PasswordUtil:
2321 """Instance of password_util_cls created at init_app() time.
2322 See :ref:`api:extendable classes`"""
2323 return self._password_util
2324
2325 @property
2326 def username_util(self) -> UsernameUtil:
2327 """Instance of username_util_cls created at init_app() time.
2328 See :ref:`api:extendable classes`"""
2329 return self._username_util
2330
2331 @property
2332 def phone_util(self) -> PhoneUtil:
2333 """Instance of phone_util_cls created at init_app() time.
2334 See :ref:`api:extendable classes`"""
2335 return self._phone_util
2336
2337 @property
2338 def totp_factory(self) -> Totp:
2339 """Instance of totp_factory created at init_app() time.
2340 See :ref:`api:extendable classes`"""
2341 return self._totp_factory
2342
2343 @property
2344 def mf_recovery_codes_util(self) -> MfRecoveryCodesUtil:
2345 """Instance of mf_recovery_codes_util_cls created at init_app() time.
2346 See :ref:`api:extendable classes`"""
2347 return self._mf_recovery_codes_util
2348
2349 @property
2350 def webauthn_util(self) -> WebauthnUtil:
2351 """Instance of webauthn_util_cls created at init_app() time.
2352 See :ref:`api:extendable classes`"""
2353 return self._webauthn_util
2354
2355 def _add_ctx_processor(
2356 self, endpoint: str, fn: t.Callable[[], dict[str, t.Any]]
2357 ) -> None:
2358 group = self._context_processors.setdefault(endpoint, [])
2359 if fn not in group:
2360 group.append(fn)
2361
2362 def _run_ctx_processor(self, endpoint: str) -> dict[str, t.Any]:
2363 rv: dict[str, t.Any] = {}
2364 for gl in ["global", endpoint]:
2365 for fn in self._context_processors.setdefault(gl, []):
2366 rv.update(fn())
2367 return rv
2368
2369 def context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2370 self._add_ctx_processor("global", fn)
2371
2372 def forgot_password_context_processor(
2373 self, fn: t.Callable[[], dict[str, t.Any]]
2374 ) -> None:
2375 self._add_ctx_processor("forgot_password", fn)
2376
2377 def login_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2378 self._add_ctx_processor("login", fn)
2379
2380 def logout_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2381 self._add_ctx_processor("logout", fn)
2382
2383 def register_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2384 self._add_ctx_processor("register", fn)
2385
2386 def reset_password_context_processor(
2387 self, fn: t.Callable[[], dict[str, t.Any]]
2388 ) -> None:
2389 self._add_ctx_processor("reset_password", fn)
2390
2391 def change_email_context_processor(
2392 self, fn: t.Callable[[], dict[str, t.Any]]
2393 ) -> None:
2394 self._add_ctx_processor("change_email", fn)
2395
2396 def change_password_context_processor(
2397 self, fn: t.Callable[[], dict[str, t.Any]]
2398 ) -> None:
2399 self._add_ctx_processor("change_password", fn)
2400
2401 def change_username_context_processor(
2402 self, fn: t.Callable[[], dict[str, t.Any]]
2403 ) -> None:
2404 self._add_ctx_processor("change_username", fn)
2405
2406 def recover_username_context_processor(
2407 self, fn: t.Callable[[], dict[str, t.Any]]
2408 ) -> None:
2409 self._add_ctx_processor("recover_username", fn)
2410
2411 def send_confirmation_context_processor(
2412 self, fn: t.Callable[[], dict[str, t.Any]]
2413 ) -> None:
2414 self._add_ctx_processor("send_confirmation", fn)
2415
2416 def send_login_context_processor(
2417 self, fn: t.Callable[[], dict[str, t.Any]]
2418 ) -> None:
2419 self._add_ctx_processor("send_login", fn)
2420
2421 def verify_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2422 self._add_ctx_processor("verify", fn)
2423
2424 def mail_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2425 self._add_ctx_processor("mail", fn)
2426
2427 def tf_setup_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2428 self._add_ctx_processor("tf_setup", fn)
2429
2430 def tf_token_validation_context_processor(
2431 self, fn: t.Callable[[], dict[str, t.Any]]
2432 ) -> None:
2433 self._add_ctx_processor("tf_token_validation", fn)
2434
2435 def tf_select_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2436 self._add_ctx_processor("tf_select", fn)
2437
2438 def us_signin_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2439 self._add_ctx_processor("us_signin", fn)
2440
2441 def us_setup_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2442 self._add_ctx_processor("us_setup", fn)
2443
2444 def us_verify_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
2445 self._add_ctx_processor("us_verify", fn)
2446
2447 def wan_register_context_processor(
2448 self, fn: t.Callable[[], dict[str, t.Any]]
2449 ) -> None:
2450 self._add_ctx_processor("wan_register", fn)
2451
2452 def wan_signin_context_processor(
2453 self, fn: t.Callable[[], dict[str, t.Any]]
2454 ) -> None:
2455 self._add_ctx_processor("wan_signin", fn)
2456
2457 def wan_verify_context_processor(
2458 self, fn: t.Callable[[], dict[str, t.Any]]
2459 ) -> None:
2460 self._add_ctx_processor("wan_verify", fn)
2461
2462 def mf_recovery_codes_context_processor(
2463 self, fn: t.Callable[[], dict[str, t.Any]]
2464 ) -> None:
2465 self._add_ctx_processor("mf_recovery_codes", fn)
2466
2467 def mf_recovery_context_processor(
2468 self, fn: t.Callable[[], dict[str, t.Any]]
2469 ) -> None:
2470 self._add_ctx_processor("mf_recovery", fn)