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