Debian Codegraph @

flask_security/views.py

raw
1 """
2 flask_security.views
3 ~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security views module
6
7 :copyright: (c) 2012 by Matt Wright.
8 :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
9 :license: MIT, see LICENSE for more details.
10
11 CSRF is tricky. By default all our forms have CSRF protection built in via
12 Flask-WTF. This is regardless of authentication method or whether the request
13 is Form or JSON based. Form-based 'just works' since when rendering the form
14 (on GET), the CSRF token is automatically populated.
15 We want to handle:
16 - JSON requests where CSRF token is in a header (e.g. X-CSRF-Token)
17 - Option to skip CSRF when using a token to authenticate (rather than session)
18 (CSRF_PROTECT_MECHANISMS)
19 - Option to skip CSRF for 'login'/unauthenticated requests
20 (CSRF_IGNORE_UNAUTH_ENDPOINTS)
21 This is complicated by the fact that the only way to disable form CSRF is to
22 pass in meta={csrf: false} at form instantiation time.
23
24 Be aware that for CSRF to work, caller MUST pass in session cookie. So
25 for pure API, and no session cookie - there is no way to support CSRF-Login
26 so app must set CSRF_IGNORE_UNAUTH_ENDPOINTS (or use CSRF/session cookie for logging
27 in then once they have a token, no need for cookie).
28
29 """
30
31 from __future__ import annotations
32 from functools import partial
33 import time
34 import typing as t
35
36 from flask import (
37 Blueprint,
38 after_this_request,
39 current_app,
40 jsonify,
41 request,
42 session,
43 )
44 from flask_login import current_user
45 from flask_wtf.csrf import CSRFError
46
47 from .changeable import change_user_password
48 from .change_email import change_email, change_email_confirm
49 from .change_username import change_username
50 from .confirmable import (
51 confirm_email_token_status,
52 confirm_user,
53 send_confirmation_instructions,
54 )
55 from .decorators import anonymous_user_required, auth_required, unauth_csrf, handle_csrf
56 from .forms import (
57 _setup_methods_xlate,
58 ChangePasswordForm,
59 DummyForm,
60 ForgotPasswordForm,
61 LoginForm,
62 LogoutForm,
63 _build_form_from_request,
64 _build_form,
65 form_errors_munge,
66 PasswordlessLoginForm,
67 ResetPasswordForm,
68 SendConfirmationForm,
69 TwoFactorVerifyCodeForm,
70 TwoFactorSetupForm,
71 TwoFactorRescueForm,
72 UsernameRecoveryForm,
73 VerifyForm,
74 )
75 from .passwordless import login_token_status, send_login_instructions
76 from .proxies import _security, _datastore
77 from .quart_compat import get_quart_status
78 from .signals import tf_profile_changed
79 from .tokens import refresh
80 from .unified_signin import (
81 us_signin,
82 us_signin_send_code,
83 us_setup,
84 us_setup_validate,
85 us_verify,
86 us_verify_link,
87 us_verify_send_code,
88 )
89 from .recoverable import (
90 send_reset_password_instructions,
91 update_password,
92 send_username_recovery_email,
93 reset_password_token_status,
94 )
95 from .registerable import register_user, register_existing
96 from .recovery_codes import mf_recovery, mf_recovery_codes
97 from .tf_plugin import (
98 tf_check_state,
99 tf_illegal_state,
100 tf_set_validity_token_cookie,
101 )
102 from .twofactor import (
103 _complete_two_factor_process,
104 _set_rescue_options,
105 tf_clean_session,
106 tf_disable,
107 )
108 from .utils import (
109 base_render_json,
110 check_and_update_authn_fresh,
111 check_and_get_token_status,
112 _config_value as cv,
113 _confirm_redirect,
114 do_flash,
115 get_identity_attributes,
116 get_message,
117 _get_post_login_redirect,
118 _get_post_logout_redirect,
119 _get_post_register_redirect,
120 _get_post_verify_redirect,
121 get_request_attr,
122 get_url,
123 _handle_already_auth,
124 hash_password,
125 is_user_authenticated,
126 localize_callback,
127 login_user,
128 logout_user,
129 _propagate_next,
130 send_mail,
131 _slash_url_suffix,
132 _td_format,
133 url_for_security,
134 _view_commit,
135 allowed_auth_token,
136 set_request_attr,
137 )
138 from .webauthn import (
139 has_webauthn,
140 webauthn_delete,
141 webauthn_register,
142 webauthn_register_response,
143 webauthn_signin,
144 webauthn_signin_response,
145 webauthn_verify,
146 webauthn_verify_response,
147 )
148
149 if get_quart_status(): # pragma: no cover
150 from quart import make_response, redirect
151 else:
152 from flask import make_response, redirect
153
154 if t.TYPE_CHECKING: # pragma: no cover
155 from flask.typing import ResponseReturnValue, ResponseValue
156 from flask_security import UserMixin
157
158
159 def default_render_json(
160 payload: dict[str, t.Any],
161 code: int,
162 headers: dict[str, str] | None,
163 user: UserMixin | None,
164 ) -> ResponseValue:
165 """Default JSON response handler."""
166 # Force Content-Type header to json.
167 if headers is None:
168 headers = dict()
169 headers["Content-Type"] = "application/json"
170 payload = dict(meta=dict(code=code), response=payload)
171 return make_response(jsonify(payload), code, headers)
172
173
174 def _ctx(endpoint):
175 return _security._run_ctx_processor(endpoint)
176
177
178 @unauth_csrf()
179 def login() -> ResponseReturnValue:
180 """View function for login view"""
181 form = t.cast(LoginForm, _build_form_from_request("login_form"))
182
183 if is_user_authenticated(current_user):
184 return _handle_already_auth(
185 form, payload={"identity_attributes": get_identity_attributes()}
186 )
187
188 # Clean out any potential old session info - in case of previous
189 # aborted 2FA attempt.
190 tf_clean_session()
191
192 if form.validate_on_submit():
193 assert form.user is not None
194 remember_me = form.remember.data if "remember" in form else None
195 response = _security.two_factor_plugins.tf_enter(
196 form.user,
197 remember_me,
198 "password",
199 next_loc=_propagate_next(request.url, form),
200 )
201 if response:
202 return response
203 # two factor not required - login user
204 after_this_request(_view_commit)
205 login_user(form.user, remember=remember_me, authn_via=["password"])
206
207 if _security._want_json(request):
208 return base_render_json(
209 form,
210 include_auth_token=allowed_auth_token(form.user),
211 additional=dict(tf_required=False),
212 )
213 return redirect(_get_post_login_redirect())
214
215 if request.method == "POST" and cv("RETURN_GENERIC_RESPONSES"):
216 # Validation failed - make sure PII error messages are generic
217 fields_to_squash = dict(
218 email=dict(replace_msg="GENERIC_AUTHN_FAILED"),
219 password=dict(replace_msg="GENERIC_AUTHN_FAILED"),
220 )
221 if hasattr(form, "username"):
222 fields_to_squash["username"] = dict(replace_msg="GENERIC_AUTHN_FAILED")
223 form_errors_munge(form, fields_to_squash)
224
225 if request.method == "GET":
226 # set CSRF COOKIE if configured. This is the equivalent of forms and
227 # base_render_json always sending the csrf_token
228 session["fs_cc"] = "set"
229
230 if _security._want_json(request):
231 payload = {
232 "identity_attributes": get_identity_attributes(),
233 }
234 return base_render_json(form, additional=payload)
235
236 if rurl := _confirm_redirect(form, "email"):
237 return rurl
238
239 return _security.render_template(
240 cv("LOGIN_USER_TEMPLATE"),
241 login_user_form=form,
242 identity_attributes=get_identity_attributes(),
243 **_ctx("login"),
244 )
245
246
247 @auth_required(lambda: cv("API_ENABLED_METHODS"))
248 def verify() -> ResponseReturnValue:
249 """View function which handles a reauthentication request."""
250 form = t.cast(
251 VerifyForm, _build_form_from_request("verify_form", user=current_user)
252 )
253
254 if form.validate_on_submit():
255 # form may have called verify_and_update_password()
256 after_this_request(_view_commit)
257
258 # verified - so set freshness time.
259 session["fs_paa"] = time.time()
260
261 if _security._want_json(request):
262 return base_render_json(
263 form, include_auth_token=allowed_auth_token(form.user)
264 )
265 do_flash(*get_message("REAUTHENTICATION_SUCCESSFUL"))
266 return redirect(_get_post_verify_redirect())
267
268 webauthn_available = has_webauthn(current_user, cv("WAN_ALLOW_AS_VERIFY"))
269 if _security._want_json(request):
270 provider_names: list[str] = []
271 if cv("OAUTH_ENABLE"):
272 assert _security.oauthglue is not None
273 provider_names = _security.oauthglue.provider_names
274 payload = {
275 "has_webauthn_verify_credential": webauthn_available,
276 "oauth_enabled": cv("OAUTH_ENABLE"),
277 "oauth_providers": provider_names,
278 }
279 return base_render_json(form, additional=payload)
280
281 return _security.render_template(
282 cv("VERIFY_TEMPLATE"),
283 verify_form=form,
284 has_webauthn_verify_credential=webauthn_available,
285 wan_verify_form=_build_form("wan_verify_form"),
286 **_ctx("verify"),
287 )
288
289
290 def logout() -> ResponseReturnValue:
291 """View function which handles a logout request.
292 As part of the refresh_token feature, logout now has a form defined
293 which a client can pass a refresh token that will be revoked as part of logout
294 (if the refresh token is managed with a cookie, the value will be set into the
295 form).
296 The cookie AND refresh tracker/token will be revoked.
297
298 If CSRF is configured and fails - a confirmation dialog will be shown (which
299 has the csrf token populated).
300 """
301 tf_clean_session()
302
303 if is_user_authenticated(current_user):
304 form = t.cast(
305 LogoutForm, _build_form_from_request("logout_form", user=current_user)
306 )
307 if cv("LOGOUT_CSRF"):
308 try:
309 # if failed and JSON - return 400 response
310 if response := handle_csrf(
311 get_request_attr("fs_authn_via"), _security._want_json(request)
312 ):
313 return response
314 except CSRFError:
315 return _security.render_template(
316 cv("LOGOUT_USER_TEMPLATE"),
317 logout_form=form,
318 **_ctx("logout"),
319 )
320 else:
321 # ensure logout succeeds
322 set_request_attr("csrf_valid", True)
323
324 if form.validate_on_submit():
325 # if they passed a refresh token - revoke it
326 from .tokens import _revoke_refresh_tracker
327
328 if form.refresh_tracker and not form.refresh_tracker.revoked_at:
329 _revoke_refresh_tracker(
330 form.refresh_tracker, form.refresh_errors, current_user
331 )
332 if cv("LOGOUT_CSRF"):
333 # Could be a CSRF error from form validate
334 csrf_field = getattr(form, form.meta.csrf_field_name)
335 if csrf_field and csrf_field.errors:
336 if _security._want_json(request):
337 return base_render_json(form)
338 return _security.render_template(
339 cv("LOGOUT_USER_TEMPLATE"),
340 logout_form=form,
341 **_ctx("logout"),
342 )
343 logout_user()
344
345 # No body is required - so if a POST and json - return OK
346 if request.method == "POST" and _security._want_json(request):
347 return _security._render_json({}, 200, None, None)
348
349 return redirect(_get_post_logout_redirect())
350
351
352 @anonymous_user_required
353 @unauth_csrf()
354 def register() -> ResponseReturnValue:
355 """View function which handles a registration request."""
356
357 if (_security.confirmable or request.is_json) and _security.forms[
358 "confirm_register_form"
359 ].cls:
360 form_name = "confirm_register_form"
361 else:
362 form_name = "register_form"
363 form = _build_form_from_request(form_name)
364
365 if form.validate_on_submit():
366 after_this_request(_view_commit)
367 user = register_user(form)
368 form.user = user
369
370 # The 'auto-login' feature probably should be removed - I can't imagine
371 # an application that would want random email accounts. It has been like this
372 # since the beginning. Note that we still enforce 2FA - however for unified
373 # signin - we adhere to historic behavior.
374 if not _security.confirmable or cv("LOGIN_WITHOUT_CONFIRMATION"):
375 response = _security.two_factor_plugins.tf_enter(
376 form.user,
377 False,
378 "register",
379 next_loc=_propagate_next(request.url, form),
380 )
381 if response:
382 return response
383 # two factor not required - login user.
384 login_user(user, authn_via=["register"])
385 if _security._want_json(request):
386 return base_render_json(
387 form,
388 include_auth_token=allowed_auth_token(form.user),
389 additional=dict(tf_required=False),
390 )
391
392 if not _security._want_json(request):
393 return redirect(_get_post_register_redirect())
394
395 return base_render_json(form)
396
397 # Here on GET or failed validate
398 if request.method == "POST" and cv("RETURN_GENERIC_RESPONSES"):
399 gr = register_existing(form)
400 if gr:
401 if _security._want_json(request):
402 return base_render_json(form)
403
404 return redirect(_get_post_register_redirect())
405
406 if _security._want_json(request):
407 return base_render_json(form)
408
409 return _security.render_template(
410 cv("REGISTER_USER_TEMPLATE"),
411 register_user_form=form,
412 **_ctx("register"),
413 )
414
415
416 @unauth_csrf()
417 def send_login() -> ResponseReturnValue:
418 """View function that sends login instructions for passwordless login"""
419 form = t.cast(
420 PasswordlessLoginForm, _build_form_from_request("passwordless_login_form")
421 )
422
423 if form.validate_on_submit():
424 send_login_instructions(form.user)
425 assert form.user
426 if not _security._want_json(request):
427 do_flash(*get_message("LOGIN_EMAIL_SENT", email=form.user.email))
428
429 if _security._want_json(request):
430 return base_render_json(form)
431
432 return _security.render_template(
433 cv("SEND_LOGIN_TEMPLATE"), send_login_form=form, **_ctx("send_login")
434 )
435
436
437 @anonymous_user_required
438 def token_login(token: str) -> ResponseReturnValue:
439 """View function that handles passwordless login via a token
440 Like reset-password and confirm - this is usually a GET via an email
441 so from the request we can't differentiate form-based apps from non.
442 """
443
444 expired, invalid, user = login_token_status(token)
445
446 if not user or invalid:
447 m, c = get_message("INVALID_LOGIN_TOKEN")
448 if cv("REDIRECT_BEHAVIOR") == "spa":
449 return redirect(get_url(cv("LOGIN_ERROR_VIEW"), qparams={c: m}))
450 do_flash(m, c)
451 return redirect(url_for_security("login"))
452 if expired:
453 send_login_instructions(user)
454 m, c = get_message(
455 "LOGIN_EXPIRED", email=user.email, within=_td_format(cv("LOGIN_WITHIN"))
456 )
457 if cv("REDIRECT_BEHAVIOR") == "spa":
458 return redirect(
459 get_url(
460 cv("LOGIN_ERROR_VIEW"),
461 qparams=user.get_redirect_qparams({c: m}),
462 )
463 )
464 do_flash(m, c)
465 return redirect(url_for_security("login"))
466
467 login_user(user, authn_via=["token"])
468 after_this_request(_view_commit)
469 if cv("REDIRECT_BEHAVIOR") == "spa":
470 return redirect(
471 get_url(cv("POST_LOGIN_VIEW"), qparams=user.get_redirect_qparams())
472 )
473
474 do_flash(*get_message("PASSWORDLESS_LOGIN_SUCCESSFUL"))
475
476 return redirect(_get_post_login_redirect())
477
478
479 @unauth_csrf()
480 def send_confirmation() -> ResponseReturnValue:
481 """View function which sends confirmation instructions (/confirm)."""
482 form = t.cast(
483 SendConfirmationForm, _build_form_from_request("send_confirmation_form")
484 )
485
486 if form.validate_on_submit():
487 send_confirmation_instructions(form.user)
488 if not _security._want_json(request):
489 do_flash(*get_message("CONFIRMATION_REQUEST", email=form.email.data))
490
491 elif request.method == "POST" and cv("RETURN_GENERIC_RESPONSES"):
492 # Here on GET or failed validate
493 rinfo: dict[str, dict[str, str]] = dict(email=dict())
494 form_errors_munge(form, rinfo) # by suppressing errors JSON should return 200
495 # Check for other errors - for default form - there aren't additional fields
496 # but applications might add some (e.g. recaptcha)
497 if not form.errors:
498 # Make look exactly like successful (e.g. real user) request
499 if not _security._want_json(request):
500 do_flash(*get_message("CONFIRMATION_REQUEST", email=form.email.data))
501
502 if _security._want_json(request):
503 # Never include user info since this is an anonymous endpoint.
504 return base_render_json(form, include_user=False)
505
506 return _security.render_template(
507 cv("SEND_CONFIRMATION_TEMPLATE"),
508 send_confirmation_form=form,
509 **_ctx("send_confirmation"),
510 )
511
512
513 def confirm_email(token: str) -> ResponseReturnValue:
514 """
515 View function which handles an email confirmation request.
516 This is always a GET from an email - so for 'spa' must always redirect.
517 """
518
519 expired, invalid, user = confirm_email_token_status(token)
520
521 if not user or invalid or expired:
522 if expired:
523 m, c = get_message(
524 "CONFIRMATION_EXPIRED",
525 within=_td_format(cv("CONFIRM_EMAIL_WITHIN")),
526 )
527 else:
528 m, c = get_message("INVALID_CONFIRMATION_TOKEN")
529 if cv("REDIRECT_BEHAVIOR") == "spa":
530 return redirect(get_url(cv("CONFIRM_ERROR_VIEW"), qparams={c: m}))
531 do_flash(m, c)
532 return redirect(
533 get_url(cv("CONFIRM_ERROR_VIEW")) or url_for_security("send_confirmation")
534 )
535
536 already_confirmed = user.confirmed_at is not None
537 if already_confirmed:
538 m, c = get_message("ALREADY_CONFIRMED")
539
540 if cv("REDIRECT_BEHAVIOR") == "spa":
541 # No reason to expose identity info to anyone who has the link
542 return redirect(
543 get_url(
544 cv("CONFIRM_ERROR_VIEW"),
545 qparams={c: m},
546 )
547 )
548
549 do_flash(m, c)
550 return redirect(
551 get_url(cv("CONFIRM_ERROR_VIEW")) or url_for_security("send_confirmation")
552 )
553
554 confirm_user(user)
555 after_this_request(_view_commit)
556 m, c = get_message("EMAIL_CONFIRMED")
557
558 # ? The only case where user is logged in already would be if
559 # LOGIN_WITHOUT_CONFIRMATION
560 if user != current_user:
561 logout_user()
562 if cv("AUTO_LOGIN_AFTER_CONFIRM"):
563 # N.B. this is a (small) security risk if email went to wrong place.
564 # and you have the LOGIN_WITHOUT_CONFIRMATION flag since in that case
565 # you can be logged in and doing stuff - but another person could
566 # get the email.
567 # Note also this goes against OWASP recommendations.
568 response = _security.two_factor_plugins.tf_enter(
569 user, False, "confirm", next_loc=_propagate_next(request.url, None)
570 )
571 if response:
572 do_flash(m, c)
573 return response
574 login_user(user, authn_via=["confirm"])
575
576 if cv("REDIRECT_BEHAVIOR") == "spa":
577 return redirect(
578 get_url(
579 cv("POST_CONFIRM_VIEW"),
580 qparams=user.get_redirect_qparams({c: m}),
581 )
582 )
583 do_flash(m, c)
584 return redirect(
585 get_url(cv("POST_CONFIRM_VIEW"))
586 or get_url(
587 cv("POST_LOGIN_VIEW") if cv("AUTO_LOGIN_AFTER_CONFIRM") else ".login"
588 )
589 )
590
591
592 @unauth_csrf()
593 def forgot_password() -> ResponseReturnValue:
594 """View function that handles a forgotten password request (/reset).
595 This is allowed for either anonymous or authenticated users. The rationale is that
596 often users stay logged in for a long time and might have forgotten their password
597 and might be prompted for it for sensitive operations (/verify).
598 """
599 form = t.cast(ForgotPasswordForm, _build_form_from_request("forgot_password_form"))
600
601 if form.validate_on_submit():
602 send_reset_password_instructions(form.user)
603 if not _security._want_json(request):
604 do_flash(*get_message("PASSWORD_RESET_REQUEST", email=form.email.data))
605
606 elif request.method == "POST" and cv("RETURN_GENERIC_RESPONSES"):
607 # Here on failed validate (POST) and want generic responses
608 rinfo: dict[str, dict[str, str]] = dict(email=dict())
609 form_errors_munge(form, rinfo) # by suppressing errors JSON should return 200
610 # Check for other errors - for default form - there aren't additional fields
611 # but applications might add some (e.g. recaptcha)
612 if not form.errors:
613 # No OTHER errors on form.
614 # Make look exactly like successful (e.g. real user) request
615 hash_password("not-a-password") # reduce timing between successful and not.
616 if not _security._want_json(request):
617 do_flash(*get_message("PASSWORD_RESET_REQUEST", email=form.email.data))
618
619 if _security._want_json(request):
620 # Never include user info since this is an anonymous endpoint.
621 return base_render_json(form, include_user=False)
622
623 if rurl := _confirm_redirect(form, "email"):
624 return rurl
625
626 if is_user_authenticated(current_user):
627 form.email.data = current_user.email
628 return _security.render_template(
629 cv("FORGOT_PASSWORD_TEMPLATE"),
630 forgot_password_form=form,
631 **_ctx("forgot_password"),
632 )
633
634
635 @unauth_csrf()
636 def reset_password(token: str) -> ResponseReturnValue:
637 """View function that handles a reset password request (/reset/<token>).
638
639 This endpoint can be called either when authenticated or anonymous
640
641 This is usually called via GET as part of an email link and redirects to
642 a reset-password form.
643 It is called via POST to actually update the password (and then redirects to
644 a post reset/login view)
645 If in either case the token is either invalid or expired it redirects to
646 the 'forgot-password' form.
647
648 In the case of non-form based configuration:
649 For GET normal case - redirect to RESET_VIEW?token={token}
650 For GET invalid case - redirect to RESET_ERROR_VIEW?error={error}
651 For POST normal/successful case - return 200 with new authentication token
652 For POST error case return 400
653 """
654 form = t.cast(ResetPasswordForm, _build_form_from_request("reset_password_form"))
655 expired, invalid, form.user = reset_password_token_status(token)
656
657 if request.method == "GET":
658 if not form.user or invalid or expired:
659 if expired:
660 m, c = get_message(
661 "PASSWORD_RESET_EXPIRED",
662 within=_td_format(cv("RESET_PASSWORD_WITHIN")),
663 )
664 else:
665 m, c = get_message("INVALID_RESET_PASSWORD_TOKEN")
666 if cv("REDIRECT_BEHAVIOR") == "spa":
667 return redirect(get_url(cv("RESET_ERROR_VIEW"), qparams={c: m}))
668 do_flash(m, c)
669 return redirect(url_for_security("forgot_password"))
670
671 # All good - for SPA - redirect to the ``reset_view``
672 # Still - don't include PII such as identity and email if someone
673 # intercepts link they still won't necessarily know the login identity
674 # (even though they can change the password!).
675 if cv("REDIRECT_BEHAVIOR") == "spa":
676 return redirect(
677 get_url(
678 cv("RESET_VIEW"),
679 qparams={"token": token},
680 )
681 )
682 # for forms - render the reset password form
683 return _security.render_template(
684 cv("RESET_PASSWORD_TEMPLATE"),
685 reset_password_form=form,
686 reset_password_token=token,
687 **_ctx("reset_password"),
688 )
689
690 # This is the POST case.
691 if not form.user or invalid or expired:
692 if expired:
693 m, c = get_message(
694 "PASSWORD_RESET_EXPIRED", within=_td_format(cv("RESET_PASSWORD_WITHIN"))
695 )
696 else:
697 m, c = get_message("INVALID_RESET_PASSWORD_TOKEN")
698
699 if _security._want_json(request):
700 form.form_errors.append(m)
701 return base_render_json(form, include_user=False)
702 else:
703 do_flash(m, c)
704 return redirect(url_for_security("forgot_password"))
705
706 if form.validate_on_submit():
707 after_this_request(_view_commit)
708 update_password(form.user, form.password.data)
709 if cv("AUTO_LOGIN_AFTER_RESET"):
710 # backwards compat - really shouldn't do this according to OWASP
711 response = _security.two_factor_plugins.tf_enter(
712 form.user, False, "reset", next_loc=_propagate_next(request.url, None)
713 )
714 if response:
715 return response
716 # two factor not required - just login
717 login_user(form.user, authn_via=["reset"])
718 if _security._want_json(request):
719 dummy_form = DummyForm(formdata=None)
720 dummy_form.user = form.user
721 return base_render_json(
722 dummy_form,
723 include_auth_token=allowed_auth_token(form.user),
724 additional=dict(tf_required=False),
725 )
726 else:
727 do_flash(*get_message("PASSWORD_RESET"))
728 return redirect(
729 get_url(cv("POST_RESET_VIEW")) or get_url(cv("POST_LOGIN_VIEW"))
730 )
731 else:
732 if _security._want_json(request):
733 return _security._render_json({}, 200, None, None)
734 else:
735 do_flash(*get_message("PASSWORD_RESET_NO_LOGIN"))
736 return redirect(get_url(cv("POST_RESET_VIEW")) or get_url(".login"))
737
738 # validation failure case - for forms - we try again including the token
739 # for non-forms - we just return errors and assume caller remembers token.
740 if _security._want_json(request):
741 return base_render_json(form)
742 return _security.render_template(
743 cv("RESET_PASSWORD_TEMPLATE"),
744 reset_password_form=form,
745 reset_password_token=token,
746 **_ctx("reset_password"),
747 )
748
749
750 @auth_required(lambda: cv("API_ENABLED_METHODS"))
751 def change_password() -> ResponseReturnValue:
752 """View function which handles a change password request."""
753 form = t.cast(ChangePasswordForm, _build_form_from_request("change_password_form"))
754
755 if not current_user.password:
756 # This is case where user registered w/o a password - since we can't
757 # confirm with existing password - make sure fresh using whatever authentication
758 # method they have set up.
759 if not check_and_update_authn_fresh(
760 cv("FRESHNESS"),
761 cv("FRESHNESS_GRACE_PERIOD"),
762 get_request_attr("fs_authn_via"),
763 ):
764 return _security._reauthn_handler(
765 cv("FRESHNESS"), cv("FRESHNESS_GRACE_PERIOD")
766 )
767
768 if form.validate_on_submit():
769 after_this_request(_view_commit)
770 change_user_password(current_user._get_current_object(), form.new_password.data)
771 if _security._want_json(request):
772 form.user = current_user
773 return base_render_json(
774 form, include_auth_token=allowed_auth_token(form.user)
775 )
776
777 do_flash(*get_message("PASSWORD_CHANGE"))
778 return redirect(
779 get_url(cv("POST_CHANGE_VIEW")) or get_url(cv("POST_LOGIN_VIEW"))
780 )
781
782 active_password = True if current_user.password else False
783 if _security._want_json(request):
784 form.user = current_user
785 payload = dict(active_password=active_password)
786 return base_render_json(form, additional=payload)
787
788 return _security.render_template(
789 cv("CHANGE_PASSWORD_TEMPLATE"),
790 change_password_form=form,
791 active_password=active_password,
792 **_ctx("change_password"),
793 )
794
795
796 @unauth_csrf()
797 def two_factor_setup() -> ResponseReturnValue:
798 """View function for two-factor setup.
799
800 This is used both for GET to fetch forms and POST to actually set configuration
801 (and send token).
802
803 There are 3 cases for setting up:
804 1) initial login and application requires 2FA
805 2) changing existing 2FA information
806 3) user wanting to enable or disable 2FA (assuming application doesn't require it)
807
808 In order to CHANGE/ENABLE/DISABLE a 2FA information, user must be properly logged in
809 AND have a 'fresh' authentication.
810
811 For initial login when 2FA required of course user can't be logged in - in this
812 case we need to have been sent some
813 state via the session as part of login to show a) who and b) that they successfully
814 authenticated.
815 """
816 form = t.cast(TwoFactorSetupForm, _build_form_from_request("two_factor_setup_form"))
817
818 changing = is_user_authenticated(current_user)
819 if not changing:
820 # This is the initial login case
821 if not all(k in session for k in ["tf_user_id", "tf_state"]) or session[
822 "tf_state"
823 ] not in ["setup_from_login", "validating_profile"]:
824 # illegal call on this endpoint
825 tf_clean_session()
826 return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW"))
827
828 user = _datastore.find_user(fs_uniquifier=session["tf_user_id"])
829 if not user:
830 tf_clean_session()
831 return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW"))
832
833 else:
834 # Caller is changing their TFA profile. This requires a 'fresh' authentication
835 # N.B unauth_csrf has done the CSRF check already.
836 if not check_and_update_authn_fresh(
837 cv("FRESHNESS"),
838 cv("FRESHNESS_GRACE_PERIOD"),
839 get_request_attr("fs_authn_via"),
840 ):
841 return _security._reauthn_handler(
842 cv("FRESHNESS"), cv("FRESHNESS_GRACE_PERIOD")
843 )
844 user = current_user
845 form.user = user
846
847 if form.validate_on_submit():
848 # Before storing in DB and therefore requiring 2FA we need to
849 # make sure it actually works.
850 # Requiring 2FA is triggered by having:
851 # - BOTH tf_totp_secret and tf_primary_method in the user record
852 # - OR having the application global config TWO_FACTOR_REQUIRED
853 # - OR User.check_tf_required() returns True (overridden by app).
854 # Until we correctly validate the 2FA - we don't set primary_method in
855 # user model but use the session to store it.
856 pm = form.setup.data
857 if pm == "disable":
858 tf_disable(user)
859 after_this_request(_view_commit)
860 if not _security._want_json(request):
861 do_flash(*get_message("TWO_FACTOR_DISABLED"))
862 return redirect(get_url(cv("TWO_FACTOR_POST_SETUP_VIEW")))
863 else:
864 return base_render_json(form)
865
866 # Regenerate the TOTP secret on every call of 2FA setup
867 totp = _security.totp_factory.generate_totp_secret()
868 phone = form.phone.data if pm == "sms" else None
869 session["tf_totp_secret"] = totp
870 session["tf_primary_method"] = pm
871 session["tf_state"] = "validating_profile"
872 # currently - state_token only works for changing TFA - not initial login
873 state_token = None
874 if changing:
875 state = {
876 "totp_secret": totp,
877 "method": pm,
878 "phone": phone,
879 }
880 state_token = _security.tf_setup_serializer.dumps(state)
881 json_response = {
882 "tf_state": "validating_profile", # deprecated in 5.5.0
883 "tf_primary_method": pm, # old
884 "tf_method": pm,
885 "tf_state_token": state_token,
886 }
887 if phone:
888 # TODO dont save here - wait until complete
889 user.tf_phone_number = phone
890 _datastore.put(user)
891 after_this_request(_view_commit)
892
893 if (
894 pm == "email" or pm == "sms"
895 ): # TODO not sure this is needed - send checks this
896 msg = user.tf_send_security_token(
897 method=pm,
898 totp_secret=totp,
899 phone_number=phone,
900 )
901 if msg:
902 # send code didn't work
903 form.setup.errors = list()
904 form.setup.errors.append(msg)
905 if _security._want_json(request):
906 return base_render_json(
907 form, include_user=False, error_status_code=500
908 )
909
910 qrcode_values = dict()
911 if pm == "authenticator":
912 authr_setup_values = _security.totp_factory.fetch_setup_values(totp, user)
913 # Add all the values used in qrcode to json response
914 json_response["tf_authr_key"] = authr_setup_values["key"]
915 json_response["tf_authr_b32key"] = authr_setup_values["b32key"]
916 json_response["tf_authr_username"] = authr_setup_values["username"]
917 json_response["tf_authr_issuer"] = authr_setup_values["issuer"]
918 json_response["tf_authr_uri"] = authr_setup_values["uri"]
919
920 qrcode_values = dict(
921 authr_qrcode=authr_setup_values["image"],
922 authr_key=authr_setup_values["key"],
923 authr_username=authr_setup_values["username"],
924 authr_issuer=authr_setup_values["issuer"],
925 )
926 if _security._want_json(request):
927 return base_render_json(form, include_user=False, additional=json_response)
928 code_form = _build_form("two_factor_verify_code_form")
929 return _security.render_template(
930 cv("TWO_FACTOR_SETUP_TEMPLATE"),
931 two_factor_setup_form=form,
932 two_factor_verify_code_form=code_form,
933 choices=cv("TWO_FACTOR_ENABLED_METHODS"),
934 chosen_method=pm, # do not translate
935 primary_method=localize_callback(
936 _setup_methods_xlate[getattr(user, "tf_primary_method", None)]
937 ),
938 changing=changing,
939 state_token=state_token,
940 **qrcode_values,
941 **_ctx("tf_setup"),
942 )
943
944 # We get here on GET and POST with failed validation.
945 choices = cv("TWO_FACTOR_ENABLED_METHODS")[:]
946 tf_required = user.check_tf_required_setup()
947 if (not tf_required) and user.tf_primary_method is not None:
948 choices.insert(0, "disable")
949
950 if _security._want_json(request):
951 # Provide information application/UI might need to render their own form/input
952 json_response = {
953 "tf_required": tf_required,
954 "tf_primary_method": getattr(user, "tf_primary_method", None), # old
955 "tf_method": getattr(user, "tf_primary_method", None),
956 "tf_phone_number": getattr(user, "tf_phone_number", None),
957 "tf_available_methods": choices,
958 }
959 return base_render_json(form, include_user=False, additional=json_response)
960
961 code_form = _build_form("two_factor_verify_code_form")
962 return _security.render_template(
963 cv("TWO_FACTOR_SETUP_TEMPLATE"),
964 two_factor_setup_form=form,
965 two_factor_verify_code_form=code_form,
966 choices=choices,
967 chosen_method=None,
968 primary_method=localize_callback(
969 _setup_methods_xlate[getattr(user, "tf_primary_method", None)]
970 ),
971 changing=changing,
972 state_token=None,
973 two_factor_required=tf_required,
974 **_ctx("tf_setup"),
975 )
976
977
978 @auth_required(lambda: cv("API_ENABLED_METHODS"))
979 def two_factor_setup_validate(token: str) -> ResponseReturnValue:
980 """
981 Validate new setup.
982 The token is the state variable that is signed and timed
983 and contains all the state that once confirmed will be stored in the user record.
984 Unlike the code in two_factor_token_validation - this works w/o a session.
985 It also is JUST for setting up/changing two factor for an authenticated user.
986 """
987 form = t.cast(
988 TwoFactorVerifyCodeForm, _build_form_from_request("two_factor_verify_code_form")
989 )
990
991 expired, invalid, state = check_and_get_token_status(
992 token, "tf_setup", cv("TWO_FACTOR_SETUP_WITHIN")
993 )
994 if invalid:
995 m, c = get_message("API_ERROR")
996 if expired:
997 m, c = get_message(
998 "TWO_FACTOR_SETUP_EXPIRED", within=_td_format(cv("TWO_FACTOR_SETUP_WITHIN"))
999 )
1000 if invalid or expired:
1001 tf_clean_session() # until we completely remove session based setup/state
1002 if _security._want_json(request):
1003 form.form_errors.append(m)
1004 return base_render_json(form, include_user=False)
1005 do_flash(m, c)
1006 return redirect(url_for_security("two_factor_setup"))
1007
1008 totp_secret = state["totp_secret"]
1009 method = state["method"]
1010 phone = state["phone"]
1011 form.tf_totp_secret = totp_secret
1012 form.primary_method = method
1013 form.user = current_user
1014 form.is_setup = True
1015
1016 if form.validate_on_submit():
1017 tf_clean_session() # until we completely remove session based setup/state
1018 after_this_request(_view_commit)
1019 _datastore.tf_set(current_user, method, totp_secret, phone)
1020 # TODO: should validity cookie be removed? extended? left alone?
1021 # Currently - leave it alone - meaning cookie still set.
1022
1023 tf_profile_changed.send(
1024 current_app._get_current_object(), # type: ignore[attr-defined]
1025 _async_wrapper=current_app.ensure_sync,
1026 user=current_user,
1027 method=method,
1028 )
1029
1030 if _security._want_json(request):
1031 return base_render_json(
1032 form,
1033 include_user=False,
1034 additional=dict(
1035 tf_method=method,
1036 tf_primary_method=method,
1037 tf_phone=current_user.tf_phone_number,
1038 ),
1039 )
1040 else:
1041 do_flash(*get_message("TWO_FACTOR_CHANGE_METHOD_SUCCESSFUL"))
1042 return redirect(get_url(cv("TWO_FACTOR_POST_SETUP_VIEW")))
1043
1044 # Code not correct/outdated.
1045 if _security._want_json(request):
1046 return base_render_json(form, include_user=False)
1047 m, c = get_message("TWO_FACTOR_INVALID_TOKEN")
1048 do_flash(m, c)
1049 return redirect(url_for_security("two_factor_setup"))
1050
1051
1052 @unauth_csrf()
1053 def two_factor_token_validation() -> ResponseReturnValue:
1054 """View function for two-factor token validation
1055
1056 Two cases:
1057 1) normal login case - everything setup correctly; normal 2FA validation
1058 In this case - user not logged in -
1059 but 'tf_state' == 'ready' or 'validating_profile'
1060 2) validating after CHANGE/ENABLE 2FA. In this case user logged in/authenticated
1061 In this case we allow a GET to get the specific enter-code form.
1062
1063 """
1064 form = t.cast(
1065 TwoFactorVerifyCodeForm, _build_form_from_request("two_factor_verify_code_form")
1066 )
1067
1068 # state info in session
1069 pm = session.get("tf_primary_method", None)
1070 totp_secret = session.get("tf_totp_secret", None)
1071 tf_state = session.get("tf_state", None)
1072 tf_user_id = session.get("tf_user_id", None)
1073
1074 changing = is_user_authenticated(current_user)
1075 if not changing:
1076 # This is the normal login case OR initial setup (two factor required)
1077 if (
1078 tf_state not in ["ready", "validating_profile"]
1079 or (tf_state == "validating_profile" and not all([pm, totp_secret]))
1080 or not tf_user_id
1081 ):
1082 # illegal call on this endpoint
1083 tf_clean_session()
1084 return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW"))
1085
1086 user = _datastore.find_user(fs_uniquifier=tf_user_id)
1087 form.user = user
1088 if not user:
1089 tf_clean_session()
1090 return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW"))
1091
1092 if tf_state == "ready":
1093 # normal login case - use saved values
1094 pm = user.tf_primary_method
1095 totp_secret = user.tf_totp_secret
1096 else:
1097 # Changing TFA profile - user is already authenticated.
1098 if tf_state != "validating_profile" or not all([pm, totp_secret]):
1099 tf_clean_session()
1100 # logout since this seems like attack-ish/logic error
1101 logout_user()
1102 return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW"))
1103 form.user = current_user
1104 form.is_setup = True
1105
1106 form.primary_method = pm
1107 form.tf_totp_secret = totp_secret
1108 assert form.user
1109 if form.validate_on_submit():
1110 # Success - finish process based on 'changing' and clear all session variables
1111 completion_message, token = _complete_two_factor_process(
1112 form.user, pm, totp_secret, changing
1113 )
1114
1115 after_this_request(_view_commit)
1116 if token:
1117 after_this_request(partial(tf_set_validity_token_cookie, token=token))
1118
1119 if not _security._want_json(request):
1120 do_flash(*get_message(completion_message))
1121 if changing:
1122 return redirect(get_url(cv("TWO_FACTOR_POST_SETUP_VIEW")))
1123 else:
1124 return redirect(_get_post_login_redirect())
1125
1126 else:
1127 return base_render_json(
1128 form, include_auth_token=allowed_auth_token(form.user)
1129 )
1130
1131 # GET or not successful POST
1132
1133 # if we were trying to validate a new method
1134 if changing:
1135 if _security._want_json(request):
1136 return base_render_json(form)
1137 # allow app to fetch just this form (independent of /tf_setup)
1138 return _security.render_template(
1139 cv("TWO_FACTOR_VERIFY_CODE_TEMPLATE"),
1140 two_factor_verify_code_form=form,
1141 chosen_method=localize_callback(_setup_methods_xlate[pm]),
1142 **_ctx("tf_token_validation"),
1143 )
1144
1145 # if we were trying to validate an existing method
1146 else:
1147 rescue_form = _build_form("two_factor_rescue_form")
1148 recovery_options = _set_rescue_options(rescue_form, form.user)
1149 if _security._want_json(request):
1150 return base_render_json(
1151 form, additional=dict(recovery_options=recovery_options)
1152 )
1153 return _security.render_template(
1154 cv("TWO_FACTOR_VERIFY_CODE_TEMPLATE"),
1155 two_factor_rescue_form=rescue_form,
1156 two_factor_verify_code_form=form,
1157 chosen_method=localize_callback(_setup_methods_xlate[pm]),
1158 problem=None,
1159 **_ctx("tf_token_validation"),
1160 )
1161
1162
1163 @anonymous_user_required
1164 @unauth_csrf()
1165 def two_factor_rescue() -> ResponseReturnValue:
1166 """Function that handles a situation where user can't
1167 enter his two-factor validation code
1168
1169 User must have already provided valid username/password.
1170 User must have already established 2FA
1171
1172 """
1173 form = t.cast(
1174 TwoFactorRescueForm, _build_form_from_request("two_factor_rescue_form")
1175 )
1176
1177 form.user = tf_check_state(["ready"])
1178 if not form.user:
1179 return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW"))
1180
1181 recovery_options = _set_rescue_options(form, form.user)
1182 rproblem = ""
1183 if form.validate_on_submit():
1184 raction = form.help_setup.data
1185 rproblem = raction
1186 if raction == "email":
1187 msg = form.user.tf_send_security_token(
1188 method="email",
1189 totp_secret=form.user.tf_totp_secret,
1190 phone_number=getattr(form.user, "tf_phone_number", None),
1191 )
1192 if msg:
1193 rproblem = ""
1194 assert isinstance(form.help_setup.errors, list)
1195 form.help_setup.errors.append(msg)
1196 if _security._want_json(request):
1197 return base_render_json(
1198 form, include_user=False, error_status_code=500
1199 )
1200 # drop through to GET path
1201 elif raction == "recovery_code":
1202 return redirect(url_for_security("mf_recovery"))
1203
1204 # send app provider a mail message regarding trouble
1205 elif raction == "help":
1206 send_mail(
1207 cv("EMAIL_SUBJECT_TWO_FACTOR_RESCUE"),
1208 cv("TWO_FACTOR_RESCUE_MAIL"),
1209 cv("TWO_FACTOR_RESCUE_EMAIL_TEMPLATE"),
1210 user=form.user,
1211 )
1212 # drop through to GET path
1213 else:
1214 return "", 404
1215
1216 if _security._want_json(request):
1217 return base_render_json(
1218 form, include_user=False, additional=dict(recovery_options=recovery_options)
1219 )
1220
1221 code_form = _build_form("two_factor_verify_code_form")
1222 return _security.render_template(
1223 cv("TWO_FACTOR_VERIFY_CODE_TEMPLATE"),
1224 two_factor_verify_code_form=code_form,
1225 two_factor_rescue_form=form,
1226 chosen_method=localize_callback(
1227 _setup_methods_xlate[form.user.tf_primary_method]
1228 ),
1229 rescue_mail=cv("TWO_FACTOR_RESCUE_MAIL"),
1230 problem=rproblem,
1231 **_ctx("tf_token_validation"),
1232 )
1233
1234
1235 @anonymous_user_required
1236 @unauth_csrf()
1237 def recover_username() -> ResponseReturnValue:
1238 """View function for username recovery"""
1239
1240 form = t.cast(
1241 UsernameRecoveryForm, _build_form_from_request("username_recovery_form")
1242 )
1243
1244 if form.validate_on_submit():
1245 send_username_recovery_email(form.user)
1246
1247 if _security._want_json(request):
1248 return base_render_json(form, include_user=False)
1249
1250 do_flash(*get_message("USERNAME_RECOVERY_REQUEST"))
1251
1252 return redirect(url_for_security("login"))
1253 elif request.method == "POST" and cv("RETURN_GENERIC_RESPONSES"):
1254 rinfo: dict[str, dict[str, str]] = dict(email=dict())
1255 form_errors_munge(form, rinfo)
1256 if not form.errors:
1257 if not _security._want_json(request):
1258 do_flash(*get_message("USERNAME_RECOVERY_REQUEST"))
1259
1260 if _security._want_json(request):
1261 return base_render_json(form, include_user=False)
1262
1263 if rurl := _confirm_redirect(form, "email"):
1264 return rurl
1265
1266 return _security.render_template(
1267 cv("USERNAME_RECOVERY_TEMPLATE"),
1268 username_recovery_form=form,
1269 **_ctx("recover_username"),
1270 )
1271
1272
1273 def _create_blueprint(app, state, import_name):
1274 """Creates the security extension blueprint"""
1275
1276 bp = Blueprint(
1277 cv("BLUEPRINT_NAME", app=app),
1278 import_name,
1279 url_prefix=cv("URL_PREFIX", app=app),
1280 subdomain=cv("SUBDOMAIN", app=app),
1281 template_folder="templates",
1282 static_folder=cv("STATIC_FOLDER", app),
1283 static_url_path=cv("STATIC_FOLDER_URL", app),
1284 )
1285
1286 if cv("LOGOUT_METHODS", app=app) is not None:
1287 bp.route(
1288 cv("LOGOUT_URL", app=app),
1289 methods=cv("LOGOUT_METHODS", app=app),
1290 endpoint="logout",
1291 )(logout)
1292
1293 login_url = cv("LOGIN_URL", app=app)
1294 if state.passwordless:
1295 bp.route(login_url, methods=["GET", "POST"], endpoint="login")(send_login)
1296 bp.route(
1297 login_url + _slash_url_suffix(login_url, "<token>"),
1298 endpoint="token_login",
1299 )(token_login)
1300 elif cv("US_SIGNIN_REPLACES_LOGIN", app=app):
1301 bp.route(login_url, methods=["GET", "POST"], endpoint="login")(us_signin)
1302
1303 else:
1304 bp.route(login_url, methods=["GET", "POST"], endpoint="login")(login)
1305
1306 if cv("FRESHNESS", app=app).total_seconds() >= 0:
1307 bp.route(cv("VERIFY_URL", app=app), methods=["GET", "POST"], endpoint="verify")(
1308 verify
1309 )
1310
1311 if state.unified_signin:
1312 us_signin_url = cv("US_SIGNIN_URL", app=app)
1313 us_signin_send_code_url = cv("US_SIGNIN_SEND_CODE_URL", app=app)
1314 us_setup_url = cv("US_SETUP_URL", app=app)
1315 us_verify_url = cv("US_VERIFY_URL", app=app)
1316 us_verify_send_code_url = cv("US_VERIFY_SEND_CODE_URL", app=app)
1317 us_verify_link_url = cv("US_VERIFY_LINK_URL", app=app)
1318 bp.route(us_signin_url, methods=["GET", "POST"], endpoint="us_signin")(
1319 us_signin
1320 )
1321 bp.route(
1322 us_signin_send_code_url,
1323 methods=["POST"],
1324 endpoint="us_signin_send_code",
1325 )(us_signin_send_code)
1326
1327 bp.route(us_setup_url, methods=["GET", "POST"], endpoint="us_setup")(us_setup)
1328 bp.route(
1329 us_setup_url + _slash_url_suffix(us_setup_url, "<token>"),
1330 methods=["POST"],
1331 endpoint="us_setup_validate",
1332 )(us_setup_validate)
1333
1334 # Freshness verification
1335 if cv("FRESHNESS", app=app).total_seconds() >= 0:
1336 bp.route(us_verify_url, methods=["GET", "POST"], endpoint="us_verify")(
1337 us_verify
1338 )
1339 bp.route(
1340 us_verify_send_code_url,
1341 methods=["POST"],
1342 endpoint="us_verify_send_code",
1343 )(us_verify_send_code)
1344
1345 bp.route(us_verify_link_url, methods=["GET"], endpoint="us_verify_link")(
1346 us_verify_link
1347 )
1348
1349 if state.two_factor:
1350 two_factor_setup_url = cv("TWO_FACTOR_SETUP_URL", app=app)
1351 two_factor_token_validation_url = cv("TWO_FACTOR_TOKEN_VALIDATION_URL", app=app)
1352 two_factor_rescue_url = cv("TWO_FACTOR_RESCUE_URL", app=app)
1353 bp.route(
1354 two_factor_setup_url,
1355 methods=["GET", "POST"],
1356 endpoint="two_factor_setup",
1357 )(two_factor_setup)
1358 bp.route(
1359 two_factor_setup_url + _slash_url_suffix(two_factor_setup_url, "<token>"),
1360 methods=["POST"],
1361 endpoint="two_factor_setup_validate",
1362 )(two_factor_setup_validate)
1363 bp.route(
1364 two_factor_token_validation_url,
1365 methods=["GET", "POST"],
1366 endpoint="two_factor_token_validation",
1367 )(two_factor_token_validation)
1368 bp.route(
1369 two_factor_rescue_url,
1370 methods=["GET", "POST"],
1371 endpoint="two_factor_rescue",
1372 )(two_factor_rescue)
1373
1374 if state.registerable:
1375 bp.route(
1376 cv("REGISTER_URL", app=app), methods=["GET", "POST"], endpoint="register"
1377 )(register)
1378
1379 if state.recoverable:
1380 reset_url = cv("RESET_URL", app=app)
1381 bp.route(reset_url, methods=["GET", "POST"], endpoint="forgot_password")(
1382 forgot_password
1383 )
1384 bp.route(
1385 reset_url + _slash_url_suffix(reset_url, "<token>"),
1386 methods=["GET", "POST"],
1387 endpoint="reset_password",
1388 )(reset_password)
1389
1390 if state.username_recovery:
1391 username_recovery_url = cv("USERNAME_RECOVERY_URL", app=app)
1392 bp.route(
1393 username_recovery_url,
1394 methods=["GET", "POST"],
1395 endpoint="recover_username",
1396 )(recover_username)
1397
1398 if state.changeable:
1399 bp.route(
1400 cv("CHANGE_URL", app=app),
1401 methods=["GET", "POST"],
1402 endpoint="change_password",
1403 )(change_password)
1404
1405 if state.change_email:
1406 change_email_url = cv("CHANGE_EMAIL_URL", app=app)
1407 bp.route(
1408 change_email_url,
1409 methods=["GET", "POST"],
1410 endpoint="change_email",
1411 )(change_email)
1412 bp.route(
1413 change_email_url + _slash_url_suffix(change_email_url, "<token>"),
1414 methods=["GET"],
1415 endpoint="change_email_confirm",
1416 )(change_email_confirm)
1417
1418 if state.change_username:
1419 bp.route(
1420 cv("CHANGE_USERNAME_URL", app=app),
1421 methods=["GET", "POST"],
1422 endpoint="change_username",
1423 )(change_username)
1424
1425 if state.confirmable:
1426 confirm_url = cv("CONFIRM_URL", app=app)
1427 bp.route(confirm_url, methods=["GET", "POST"], endpoint="send_confirmation")(
1428 send_confirmation
1429 )
1430 bp.route(
1431 confirm_url + _slash_url_suffix(confirm_url, "<token>"),
1432 methods=["GET", "POST"],
1433 endpoint="confirm_email",
1434 )(confirm_email)
1435
1436 if cv("MULTI_FACTOR_RECOVERY_CODES", app) and state.support_mfa:
1437 multi_factor_recovery_codes_url = cv("MULTI_FACTOR_RECOVERY_CODES_URL", app=app)
1438 multi_factor_recovery_url = cv("MULTI_FACTOR_RECOVERY_URL", app=app)
1439 bp.route(
1440 multi_factor_recovery_codes_url,
1441 methods=["GET", "POST"],
1442 endpoint="mf_recovery_codes",
1443 )(mf_recovery_codes)
1444 bp.route(
1445 multi_factor_recovery_url,
1446 methods=["GET", "POST"],
1447 endpoint="mf_recovery",
1448 )(mf_recovery)
1449
1450 if state.webauthn:
1451 wan_register_url = cv("WAN_REGISTER_URL", app=app)
1452 wan_signin_url = cv("WAN_SIGNIN_URL", app=app)
1453 wan_delete_url = cv("WAN_DELETE_URL", app=app)
1454 wan_verify_url = cv("WAN_VERIFY_URL", app=app)
1455 bp.route(
1456 wan_register_url,
1457 methods=["GET", "POST"],
1458 endpoint="wan_register",
1459 )(webauthn_register)
1460 bp.route(
1461 wan_register_url + _slash_url_suffix(wan_register_url, "<token>"),
1462 methods=["POST"],
1463 endpoint="wan_register_response",
1464 )(webauthn_register_response)
1465
1466 bp.route(wan_signin_url, methods=["GET", "POST"], endpoint="wan_signin")(
1467 webauthn_signin
1468 )
1469 bp.route(
1470 wan_signin_url + _slash_url_suffix(wan_signin_url, "<token>"),
1471 methods=["POST"],
1472 endpoint="wan_signin_response",
1473 )(webauthn_signin_response)
1474 bp.route(wan_delete_url, methods=["GET", "POST"], endpoint="wan_delete")(
1475 webauthn_delete
1476 )
1477 if cv("FRESHNESS", app=app).total_seconds() >= 0 and cv(
1478 "WAN_ALLOW_AS_VERIFY", app=app
1479 ):
1480 bp.route(wan_verify_url, methods=["GET", "POST"], endpoint="wan_verify")(
1481 webauthn_verify
1482 )
1483 bp.route(
1484 wan_verify_url + _slash_url_suffix(wan_verify_url, "<token>"),
1485 methods=["POST"],
1486 endpoint="wan_verify_response",
1487 )(webauthn_verify_response)
1488
1489 if state.refresh_token:
1490 refresh_url = cv("REFRESH_TOKEN_URL", app=app)
1491 bp.route(
1492 refresh_url,
1493 methods=["POST"],
1494 endpoint="refresh_token",
1495 )(refresh)
1496 return bp