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