Debian Codegraph @

flask_security/unified_signin.py

raw
1 """
2 flask_security.unified_signin
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security Unified Signin module
6
7 :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9
10 This implements a unified sign in endpoint - allowing
11 authentication via identity and passcode - where identity is configured
12 via SECURITY_USER_IDENTITY_ATTRIBUTES, and allowable passcodes are
13 one of US_ENABLED_METHODS.
14
15 Finish up:
16 - we should be able to add a phone number as part of setup even w/o any METHODS -
17 i.e. to allow login with any identity (phone) and a password.
18
19 Consider/Questions:
20 - Allow registering/confirming with just a phone number - this likely would require
21 a new register/confirm endpoint in order to implement verification.
22 - Right now ChangePassword won't work - it requires an existing password - so
23 if the user doesn't have one - can't change it. However ForgotPassword will in
24 fact allow the user to add a password. Is that sufficient?
25 - This also means that there is no way to REMOVE your password once it is setup,
26 although user can register without one.
27 - separate code validation times for SMS, email, authenticator?
28 - token versus code versus passcode? Confusing terminology.
29
30 """
31
32 from __future__ import annotations
33
34 import time
35 import typing as t
36
37 from flask import current_app
38 from flask import after_this_request, request, session
39 from flask_login import current_user
40 from wtforms import (
41 BooleanField,
42 PasswordField,
43 RadioField,
44 SelectMultipleField,
45 StringField,
46 SubmitField,
47 TelField,
48 validators,
49 )
50 from wtforms.widgets import CheckboxInput
51
52 from .confirmable import requires_confirmation
53 from .decorators import anonymous_user_required, auth_required, unauth_csrf
54 from .forms import (
55 _setup_methods_xlate,
56 Form,
57 NextFormMixin,
58 RequiredLocalize,
59 build_form_from_request,
60 build_form,
61 form_errors_munge,
62 generic_message,
63 get_form_field_label,
64 get_form_field_xlate,
65 )
66 from .proxies import _security, _datastore
67 from .quart_compat import get_quart_status
68 from .signals import us_profile_changed, us_security_token_sent
69 from .utils import (
70 _,
71 SmsSenderFactory,
72 base_render_json,
73 check_and_get_token_status,
74 config_value as cv,
75 confirm_redirect,
76 do_flash,
77 get_identity_attributes,
78 get_post_login_redirect,
79 get_post_verify_redirect,
80 get_message,
81 get_url,
82 get_within_delta,
83 handle_already_auth,
84 is_user_authenticated,
85 localize_callback,
86 login_user,
87 lookup_identity,
88 propagate_next,
89 send_mail,
90 url_for_security,
91 view_commit,
92 )
93 from .tf_plugin import tf_verify_validity_token
94 from .twofactor import tf_clean_session
95 from .webauthn import has_webauthn
96
97 if t.TYPE_CHECKING: # pragma: no cover
98 from flask.typing import ResponseValue
99 from flask_security import UserMixin
100
101 if get_quart_status(): # pragma: no cover
102 from quart import redirect
103 else:
104 from flask import redirect
105
106
107 def _compute_code_methods():
108 # Return list of methods that actually send codes
109 return list(set(cv("US_ENABLED_METHODS")) - {"password", "authenticator"})
110
111
112 def _compute_setup_methods():
113 # Return list of methods that require setup
114 return list(set(cv("US_ENABLED_METHODS")) - {"password"})
115
116
117 def _compute_active_methods(user):
118 # Compute methods already setup.
119 active_methods = set(cv("US_ENABLED_METHODS")) & set(
120 _datastore.us_get_totp_secrets(user).keys()
121 )
122 if user.password:
123 active_methods = active_methods.union({"password"})
124 return list(active_methods)
125
126
127 def _compute_active_code_methods(user):
128 return list(set(_compute_active_methods(user)) & set(_compute_code_methods()))
129
130
131 def _us_common_validate(form):
132 # Be aware - this has side effect on the form - it will fill in
133 # the form.user
134
135 # Validate identity - we go in order to figure out which user attribute the
136 # request gave us. Note that we give up on the first 'match' even if that
137 # doesn't yield a user. Why?
138 form.user = lookup_identity(form.identity.data)
139 if not form.user:
140 form.identity.errors.append(get_message("US_SPECIFY_IDENTITY")[0])
141 return False
142 if not form.user.is_active:
143 form.identity.errors.append(get_message("DISABLED_ACCOUNT")[0])
144 return False
145 if form.user.is_locked(form.identity.errors):
146 return False
147 return True
148
149
150 class _UnifiedPassCodeForm(Form):
151 """Common form for signin and verify/reauthenticate."""
152
153 # filled in by caller
154 user: UserMixin
155
156 # Filled in here
157 authn_via: str
158
159 # PasswordField so it doesn't show, no autocomplete since it might be a password
160 # (could also be a passcode).
161 passcode = PasswordField(
162 get_form_field_label("passcode"),
163 render_kw={
164 "placeholder": get_form_field_xlate(_("Code or Password")),
165 "autocomplete": "off",
166 },
167 )
168 submit = SubmitField(get_form_field_label("submit"))
169
170 chosen_method = RadioField(
171 _("Available Methods"),
172 choices=[
173 ("email", get_form_field_xlate(_("Via email"))),
174 ("sms", get_form_field_xlate(_("Via SMS"))),
175 ],
176 validators=[validators.Optional()],
177 )
178 submit_send_code = SubmitField(get_form_field_label("sendcode"))
179
180 def __init__(self, *args, **kwargs):
181 super().__init__(*args, **kwargs)
182
183 def validate(self, **kwargs: t.Any) -> bool:
184 if not super().validate(**kwargs):
185 return False
186 return True
187
188 def validate2(self) -> bool:
189 totp_secrets = _datastore.us_get_totp_secrets(self.user)
190 if self.submit.data:
191 # This is authn - verify passcode/password
192 # Since we have a unique totp_secret for each method - we
193 # can figure out which mechanism was used.
194 # Note that password check requires a string (not int or None)
195 assert isinstance(self.passcode.errors, list)
196 passcode = self.passcode.data
197 if not passcode:
198 self.passcode.errors.append(get_message("INVALID_PASSWORD_CODE")[0])
199 return False
200 passcode = str(passcode)
201
202 ok = False
203 for method in cv("US_ENABLED_METHODS"):
204 if method == "password" and self.user.password:
205 passcode = _security.password_util.normalize(passcode)
206 if self.user.verify_and_update_password(passcode):
207 ok = True
208 break
209 else:
210 if method in totp_secrets and _security.totp_factory.verify_totp(
211 token=passcode,
212 totp_secret=totp_secrets[method],
213 user=self.user,
214 window=cv("US_TOKEN_VALIDITY"),
215 ):
216 ok = True
217 break
218 if not ok:
219 self.user.track_failed_authn("passcode")
220 self.passcode.errors.append(get_message("INVALID_PASSWORD_CODE")[0])
221 return False
222
223 self.authn_via = method
224 return True
225 elif self.submit_send_code.data:
226 # Send a code - chosen_method must be valid
227 assert isinstance(self.chosen_method.errors, list)
228 cm = self.chosen_method.data
229 if cm not in cv("US_ENABLED_METHODS"):
230 self.chosen_method.errors.append(
231 get_message("US_METHOD_NOT_AVAILABLE")[0]
232 )
233 return False
234 if cm not in totp_secrets:
235 self.chosen_method.errors.append(
236 get_message("US_METHOD_NOT_AVAILABLE")[0]
237 )
238 return False
239 if cm == "sms" and not self.user.us_phone_number:
240 # They need to us-setup!
241 self.chosen_method.errors.append(get_message("PHONE_INVALID")[0])
242 return False
243 return True
244 return False # pragma: no cover
245
246
247 class UnifiedSigninForm(_UnifiedPassCodeForm, NextFormMixin):
248 """A unified login form
249 For either identity/password or request and enter code.
250 """
251
252 identity = StringField(
253 get_form_field_label("identity"),
254 validators=[RequiredLocalize()],
255 )
256 remember = BooleanField(
257 get_form_field_label("remember_me"),
258 default=lambda: cv("DEFAULT_REMEMBER_ME", app=current_app),
259 )
260
261 def __init__(self, *args, **kwargs):
262 super().__init__(*args, **kwargs)
263 self.requires_confirmation = False
264
265 def validate(self, **kwargs: t.Any) -> bool:
266 if not super().validate(**kwargs):
267 return False
268 if not _us_common_validate(self):
269 return False
270 if not super().validate2():
271 return False
272
273 # Can't authenticate nor get a code if still required confirmation.
274 self.requires_confirmation = requires_confirmation(self.user)
275 assert isinstance(self.identity.errors, list)
276 if self.requires_confirmation:
277 self.identity.errors.append(get_message("CONFIRMATION_REQUIRED")[0])
278 return False
279 return True
280
281
282 class UnifiedVerifyForm(_UnifiedPassCodeForm):
283 """Verify authentication.
284 This is for freshness 'reauthentication' required.
285 """
286
287 def validate(self, **kwargs: t.Any) -> bool:
288 self.user = current_user
289 if not super().validate(**kwargs):
290 return False
291 if not super().validate2():
292 return False
293 return True
294
295
296 class UnifiedSigninSetupForm(Form):
297 """Setup form"""
298
299 setup_choices = [
300 ("email", get_form_field_label("email_method")),
301 (
302 "authenticator",
303 get_form_field_label("authapp_method"),
304 ),
305 ("sms", get_form_field_label("sms_method")),
306 ]
307 chosen_method = RadioField(
308 get_form_field_xlate(_("Setup additional sign in option")),
309 validate_choice=False,
310 )
311 delete_choices = [
312 ("email", get_form_field_xlate("Delete email option")),
313 (
314 "authenticator",
315 get_form_field_xlate("Delete authenticator option"),
316 ),
317 ("sms", get_form_field_xlate("Delete SMS option")),
318 ]
319
320 delete_method = SelectMultipleField(
321 label=get_form_field_xlate(_("Delete active sign in option")),
322 option_widget=CheckboxInput(),
323 validate_choice=False,
324 )
325 phone = TelField(get_form_field_label("phone"))
326 submit = SubmitField(get_form_field_label("submit"))
327
328 def __init__(self, *args, **kwargs):
329 super().__init__(*args, **kwargs)
330
331 def validate(self, **kwargs: t.Any) -> bool:
332 if not super().validate(**kwargs):
333 return False
334
335 assert isinstance(self.chosen_method.errors, list)
336 assert isinstance(self.phone.errors, list)
337 assert isinstance(self.delete_method.errors, list)
338
339 if not self.chosen_method.data and not self.delete_method.data:
340 self.form_errors.append(get_message("API_ERROR")[0])
341 return False
342 if self.chosen_method.data:
343 if self.chosen_method.data not in cv("US_ENABLED_METHODS"):
344 self.chosen_method.errors.append(
345 get_message("US_METHOD_NOT_AVAILABLE")[0]
346 )
347 return False
348
349 if self.chosen_method.data == "sms":
350 if not self.phone.data:
351 self.phone.errors.append(get_message("PHONE_INVALID")[0])
352 return False
353 msg = _security.phone_util.validate_phone_number(self.phone.data)
354 if msg:
355 self.phone.errors.append(msg)
356 return False
357 # As an identity attribute - it MUST be unique!
358 cphone = _security.phone_util.get_canonical_form(self.phone.data)
359 if _datastore.find_user(us_phone_number=cphone):
360 msg = get_message(
361 "IDENTITY_ALREADY_ASSOCIATED",
362 attr="us_phone_number",
363 value=cphone,
364 )[0]
365 self.phone.errors.append(msg)
366 return False
367 if self.delete_method.data:
368 if not all(
369 m in _compute_active_methods(current_user)
370 for m in self.delete_method.data
371 ):
372 self.delete_method.errors.append(
373 get_message("US_METHOD_NOT_AVAILABLE")[0]
374 )
375 return False
376
377 return True
378
379
380 class UnifiedSigninSetupValidateForm(Form):
381 """The unified sign in setup validation form"""
382
383 # These 2 filled in by view
384 user: UserMixin
385 totp_secret: str
386
387 passcode = StringField(
388 get_form_field_label("passcode"),
389 render_kw={
390 "autocomplete": "one-time-code",
391 "type": "text",
392 "pattern": "[0-9]*",
393 },
394 validators=[RequiredLocalize()],
395 )
396 submit = SubmitField(get_form_field_label("submitcode"), id="submit-code")
397
398 def __init__(self, *args, **kwargs):
399 super().__init__(*args, **kwargs)
400
401 def validate(self, **kwargs: t.Any) -> bool:
402 if not super().validate(**kwargs):
403 return False
404
405 assert isinstance(self.passcode.errors, list)
406 assert self.passcode.data is not None # RequiredLocalize validator
407 if not _security.totp_factory.verify_totp(
408 token=self.passcode.data,
409 totp_secret=self.totp_secret,
410 user=self.user,
411 window=cv("US_TOKEN_VALIDITY"),
412 ):
413 self.passcode.errors.append(get_message("INVALID_PASSWORD_CODE")[0])
414 return False
415
416 return True
417
418
419 def _send_code_helper(form, send_magic_link):
420 # send code
421 user = form.user
422 method = form.chosen_method.data
423 totp_secrets = _datastore.us_get_totp_secrets(user)
424
425 msg = user.us_send_security_token(
426 method,
427 totp_secret=totp_secrets[method],
428 phone_number=getattr(user, "us_phone_number", None),
429 send_magic_link=send_magic_link,
430 )
431 return msg
432
433
434 @anonymous_user_required
435 @unauth_csrf()
436 def us_signin_send_code() -> ResponseValue:
437 """
438 Send code view. POST only.
439 This takes an identity (as configured in USER_IDENTITY_ATTRIBUTES)
440 and a method request to send a code.
441 """
442 form = t.cast(UnifiedSigninForm, build_form_from_request("us_signin_form"))
443 form.submit_send_code.data = True
444 form.submit.data = False
445
446 code_methods = _compute_code_methods()
447
448 if form.validate_on_submit():
449 msg = _send_code_helper(form, True)
450 if msg:
451 assert isinstance(form.chosen_method.errors, list)
452 form.chosen_method.errors.append(msg)
453
454 if _security._want_json(request):
455 # Not authenticated yet - so don't send any user info.
456 return base_render_json(
457 form, include_user=False, error_status_code=500 if msg else 200
458 )
459
460 if not msg:
461 # Make sure same response as non-setup method below
462 do_flash(*generic_message("CODE_HAS_BEEN_SENT", "GENERIC_US_SIGNIN"))
463
464 return _security.render_template(
465 cv("US_SIGNIN_TEMPLATE"),
466 us_signin_form=form,
467 available_methods=cv("US_ENABLED_METHODS"),
468 code_methods=code_methods,
469 chosen_method=form.chosen_method.data,
470 skip_loginmenu=True,
471 **_security._run_ctx_processor("us_signin"),
472 )
473 elif request.method == "POST" and cv("RETURN_GENERIC_RESPONSES"):
474 # TODO - this suppresses the error if they don't select ANY send code option.
475 rinfo: dict[str, dict[str, str]] = dict(
476 identity=dict(), passcode=dict(), chosen_method=dict()
477 )
478 form_errors_munge(form, rinfo)
479 if not _security._want_json(request):
480 # Make sure same response as successful code above.
481 do_flash(*get_message("GENERIC_US_SIGNIN"))
482
483 # Here on failed validation
484 if _security._want_json(request):
485 payload = {
486 "available_methods": cv("US_ENABLED_METHODS"),
487 "code_methods": code_methods,
488 "identity_attributes": get_identity_attributes(),
489 }
490 return base_render_json(form, include_user=False, additional=payload)
491
492 if rurl := confirm_redirect(form, "email"):
493 return rurl
494
495 return _security.render_template(
496 cv("US_SIGNIN_TEMPLATE"),
497 us_signin_form=form,
498 available_methods=cv("US_ENABLED_METHODS"),
499 code_methods=code_methods,
500 skip_loginmenu=True,
501 **_security._run_ctx_processor("us_signin"),
502 )
503
504
505 @auth_required(lambda: cv("API_ENABLED_METHODS"))
506 def us_verify_send_code() -> ResponseValue:
507 """
508 Send code during verify. POST only.
509 """
510 form = t.cast(UnifiedVerifyForm, build_form_from_request("us_verify_form"))
511 form.submit_send_code.data = True
512 form.submit.data = False
513
514 code_methods = _compute_active_code_methods(current_user)
515
516 if form.validate_on_submit():
517 msg = _send_code_helper(form, False)
518 if msg:
519 assert isinstance(form.chosen_method.errors, list)
520 form.chosen_method.errors.append(msg)
521
522 if _security._want_json(request):
523 # no real reason to send user info?
524 return base_render_json(
525 form, include_user=False, error_status_code=500 if msg else 200
526 )
527 if not msg:
528 do_flash(*get_message("CODE_HAS_BEEN_SENT"))
529 return _security.render_template(
530 cv("US_VERIFY_TEMPLATE"),
531 us_verify_form=form,
532 available_methods=cv("US_ENABLED_METHODS"),
533 code_methods=code_methods,
534 chosen_method=form.chosen_method.data,
535 skip_login_menu=True,
536 **_security._run_ctx_processor("us_verify"),
537 )
538
539 # Here on failed validation
540 if _security._want_json(request):
541 return base_render_json(form)
542
543 return _security.render_template(
544 cv("US_VERIFY_TEMPLATE"),
545 us_verify_form=form,
546 available_methods=cv("US_ENABLED_METHODS"),
547 code_methods=code_methods,
548 skip_login_menu=True,
549 **_security._run_ctx_processor("us_verify"),
550 )
551
552
553 @unauth_csrf()
554 def us_signin() -> ResponseValue:
555 """
556 Unified sign in view.
557 This takes an identity (as configured in USER_IDENTITY_ATTRIBUTES)
558 and a passcode (password or OTP).
559 """
560 form = t.cast(UnifiedSigninForm, build_form_from_request("us_signin_form"))
561 form.submit.data = True
562 form.submit_send_code.data = False
563 code_methods = _compute_code_methods()
564 payload = {
565 "available_methods": cv("US_ENABLED_METHODS"),
566 "code_methods": code_methods,
567 "identity_attributes": get_identity_attributes(),
568 }
569
570 if is_user_authenticated(current_user):
571 return handle_already_auth(form, payload=payload)
572
573 # Clean out any potential old session info - in case of previous
574 # aborted 2FA attempt.
575 tf_clean_session()
576
577 if form.validate_on_submit():
578 # Check if multifactor is required. Some (this is configurable) don't
579 # need 2FA since they ARE multifactor (such as SMS and authenticator).
580 remember_me = form.remember.data if "remember" in form else None
581 if form.authn_via in cv("US_MFA_REQUIRED"):
582 response = _security.two_factor_plugins.tf_enter(
583 form.user,
584 remember_me,
585 form.authn_via,
586 next_loc=propagate_next(request.url, form),
587 )
588 if response:
589 return response
590 after_this_request(view_commit)
591 login_user(form.user, remember=remember_me, authn_via=[form.authn_via])
592
593 if _security._want_json(request):
594 return base_render_json(
595 form, include_auth_token=True, additional=dict(tf_required=False)
596 )
597
598 return redirect(get_post_login_redirect())
599
600 # Here on GET or failed POST validate
601 if request.method == "POST" and cv("RETURN_GENERIC_RESPONSES"):
602 rinfo = dict(
603 identity=dict(replace_msg="GENERIC_AUTHN_FAILED"),
604 passcode=dict(replace_msg="GENERIC_AUTHN_FAILED"),
605 )
606 form_errors_munge(form, rinfo)
607
608 if request.method == "GET":
609 # set CSRF COOKIE if configured. This is the equivalent of forms and
610 # base_render_json always sending the csrf_token
611 session["fs_cc"] = "set"
612
613 if _security._want_json(request):
614 return base_render_json(form, include_user=False, additional=payload)
615
616 # On error - wipe code
617 form.passcode.data = None
618
619 if rurl := confirm_redirect(form, "email"):
620 return rurl
621
622 return _security.render_template(
623 cv("US_SIGNIN_TEMPLATE"),
624 us_signin_form=form,
625 available_methods=cv("US_ENABLED_METHODS"),
626 code_methods=code_methods,
627 skip_login_menu=True,
628 **_security._run_ctx_processor("us_signin"),
629 )
630
631
632 @auth_required(lambda: cv("API_ENABLED_METHODS"))
633 def us_verify() -> ResponseValue:
634 """
635 Re-authenticate to reset freshness time.
636 This is likely the result of a reauthn_handler redirect, which
637 will have filled in ?next=xxx - which we want to carefully not lose as we
638 go through these steps.
639 """
640 form = t.cast(UnifiedVerifyForm, build_form_from_request("us_verify_form"))
641 form.submit.data = True
642 form.submit_send_code.data = False
643
644 code_methods = _compute_active_code_methods(current_user)
645
646 if form.validate_on_submit():
647 # verified - so set freshness time.
648 session["fs_paa"] = time.time()
649
650 if _security._want_json(request):
651 return base_render_json(form, include_auth_token=True)
652
653 do_flash(*get_message("REAUTHENTICATION_SUCCESSFUL"))
654 return redirect(get_post_verify_redirect())
655
656 # Here on GET or failed POST validate
657 webauthn_available = has_webauthn(current_user, cv("WAN_ALLOW_AS_VERIFY"))
658 if _security._want_json(request):
659 payload = {
660 "available_methods": cv("US_ENABLED_METHODS"),
661 "code_methods": code_methods,
662 "has_webauthn_verify_credential": webauthn_available,
663 "oauth_enabled": cv("OAUTH_ENABLE"),
664 "oauth_providers": (
665 _security.oauthglue.provider_names # type: ignore[union-attr]
666 if cv("OAUTH_ENABLE")
667 else []
668 ),
669 }
670 return base_render_json(form, additional=payload)
671
672 # On error - wipe code
673 form.passcode.data = None
674 return _security.render_template(
675 cv("US_VERIFY_TEMPLATE"),
676 us_verify_form=form,
677 code_methods=code_methods,
678 skip_login_menu=True,
679 has_webauthn_verify_credential=webauthn_available,
680 wan_verify_form=build_form("wan_verify_form"),
681 **_security._run_ctx_processor("us_verify"),
682 )
683
684
685 @anonymous_user_required
686 def us_verify_link() -> ResponseValue:
687 """
688 Used to verify a magic email link. GET only
689 Since this is just a URL - be careful not to disclose info like
690 whether email exists or not.
691 """
692 fs_uniquifier = request.args.get("id", None)
693 code = request.args.get("code", None)
694 if not fs_uniquifier or not code:
695 m, c = get_message("API_ERROR")
696 if cv("REDIRECT_BEHAVIOR") == "spa":
697 return redirect(get_url(cv("LOGIN_ERROR_VIEW"), qparams={c: m}))
698 do_flash(m, c)
699 return redirect(url_for_security("us_signin"))
700
701 user = _datastore.find_user(fs_uniquifier=fs_uniquifier)
702 if not user or not user.active:
703 if not user:
704 m, c = generic_message("USER_DOES_NOT_EXIST", "GENERIC_AUTHN_FAILED")
705 else:
706 m, c = generic_message("DISABLED_ACCOUNT", "GENERIC_AUTHN_FAILED")
707 if cv("REDIRECT_BEHAVIOR") == "spa":
708 return redirect(get_url(cv("LOGIN_ERROR_VIEW"), qparams={c: m}))
709 do_flash(m, c)
710 return redirect(url_for_security("us_signin"))
711
712 totp_secrets = _datastore.us_get_totp_secrets(user)
713 if "email" not in totp_secrets or not _security.totp_factory.verify_totp(
714 token=code,
715 totp_secret=totp_secrets["email"],
716 user=user,
717 window=cv("US_TOKEN_VALIDITY"),
718 ):
719 m, c = generic_message("INVALID_CODE", "GENERIC_AUTHN_FAILED")
720 user.track_failed_authn("passcode")
721
722 if cv("REDIRECT_BEHAVIOR") == "spa":
723 return redirect(
724 get_url(
725 cv("LOGIN_ERROR_VIEW"),
726 qparams=user.get_redirect_qparams({c: m}),
727 )
728 )
729 do_flash(m, c)
730 return redirect(url_for_security("us_signin"))
731
732 # copied from tf_enter...
733 if _security.support_mfa:
734 tf_setup_methods = _security.two_factor_plugins.get_setup_tf_methods(user)
735 tf_fresh = tf_verify_validity_token(user.fs_uniquifier)
736 tf_required, tf_available_methods = user.check_tf_required(
737 tf_setup_methods, tf_fresh
738 )
739 if tf_required and "email" in cv("US_MFA_REQUIRED"):
740 # tf_login doesn't know anything about "spa" etc. In general two-factor
741 # isn't quite ready for SPA. So we return an error via a redirect rather
742 # than mess up SPA applications. To be clear - this simply doesn't
743 # work - using a magic link w/ 2FA - need to use code/password as primary
744 # authentication.
745 if cv("REDIRECT_BEHAVIOR") == "spa":
746 return redirect(
747 get_url(
748 cv("LOGIN_ERROR_VIEW"),
749 qparams=user.get_redirect_qparams({"tf_required": 1}),
750 )
751 )
752 response = _security.two_factor_plugins.tf_enter(
753 user, False, "email", next_loc=propagate_next(request.url, None)
754 )
755 if response:
756 return response
757
758 login_user(user, authn_via=["email"])
759 after_this_request(view_commit)
760 if cv("REDIRECT_BEHAVIOR") == "spa":
761 # We do NOT send the authentication token here since the only way to
762 # send it would be via a query param and that isn't secure. (logging and
763 # possibly HTTP Referer header).
764 # This means that this can only work if sessions are active which sort of
765 # makes sense - otherwise you need to use /us-signin with a code.
766 return redirect(
767 get_url(cv("POST_LOGIN_VIEW"), qparams=user.get_redirect_qparams())
768 )
769
770 do_flash(*get_message("PASSWORDLESS_LOGIN_SUCCESSFUL"))
771 return redirect(get_post_login_redirect())
772
773
774 @auth_required(
775 lambda: cv("API_ENABLED_METHODS"),
776 within=lambda: cv("FRESHNESS"),
777 grace=lambda: cv("FRESHNESS_GRACE_PERIOD"),
778 )
779 def us_setup() -> ResponseValue:
780 """
781 Change unified sign in methods.
782 We want to verify the new method - so don't store anything yet in DB
783 use a timed signed token to pass along state.
784 GET - retrieve current info (json) or form.
785 """
786 form = t.cast(UnifiedSigninSetupForm, build_form_from_request("us_setup_form"))
787
788 setup_methods = _compute_setup_methods()
789 active_methods = _compute_active_methods(current_user)
790 form.chosen_method.choices = [
791 c
792 for c in form.setup_choices
793 if c[0] not in active_methods and c[0] in setup_methods
794 ]
795 form.delete_method.choices = [
796 c for c in form.delete_choices if c[0] in active_methods
797 ]
798
799 # translate active methods
800 if not active_methods:
801 active_methods = [None]
802 current_methods = _security.i18n_domain.format_list(
803 [localize_callback(_setup_methods_xlate[m]) for m in active_methods]
804 )
805 current_methods_msg = get_message(
806 "US_CURRENT_METHODS", method_list=current_methods
807 )[0]
808
809 if form.validate_on_submit():
810 qrcode_values = dict()
811 json_response = dict()
812 state_token = None
813 delete_method = form.delete_method.data
814 add_method = form.chosen_method.data
815
816 if delete_method:
817 after_this_request(view_commit)
818 for m in delete_method:
819 _datastore.us_reset(current_user, m)
820 active_methods = _compute_active_methods(current_user)
821 if not active_methods:
822 active_methods = [None]
823 current_methods = _security.i18n_domain.format_list(
824 [localize_callback(_setup_methods_xlate[m]) for m in active_methods]
825 )
826
827 current_methods_msg = get_message(
828 "US_CURRENT_METHODS", method_list=current_methods
829 )[0]
830 form.chosen_method.choices = [
831 c
832 for c in form.setup_choices
833 if c[0] not in active_methods and c[0] in setup_methods
834 ]
835 form.delete_method.choices = [
836 c for c in form.delete_choices if c[0] in active_methods
837 ]
838 form.delete_method.data = None
839 us_profile_changed.send(
840 current_app._get_current_object(), # type: ignore
841 _async_wrapper=current_app.ensure_sync, # type: ignore[arg-type]
842 user=current_user,
843 methods=delete_method,
844 delete=True,
845 )
846
847 if add_method:
848 # Always generate a totp_secret. We don't set it in the DB until
849 # user has successfully validated.
850 totp = _security.totp_factory.generate_totp_secret()
851
852 # N.B. totp (totp_secret) is actually encrypted - so it seems safe enough
853 # to send it to the user.
854 # Only check phone number if SMS (see form validate)
855 phone_number = None
856 if add_method == "sms":
857 assert form.phone.data is not None
858 phone_number = _security.phone_util.get_canonical_form(form.phone.data)
859 state = {
860 "totp_secret": totp,
861 "chosen_method": add_method,
862 "phone_number": phone_number,
863 }
864 msg = current_user.us_send_security_token(
865 method=add_method,
866 totp_secret=totp,
867 phone_number=phone_number,
868 )
869 if msg:
870 # sending didn't work.
871 assert isinstance(form.chosen_method.errors, list)
872 form.chosen_method.errors.append(msg)
873 if _security._want_json(request):
874 # Not authenticated yet - so don't send any user info.
875 return base_render_json(
876 form, include_user=False, error_status_code=500 if msg else 400
877 )
878 return _security.render_template(
879 cv("US_SETUP_TEMPLATE"),
880 available_methods=cv("US_ENABLED_METHODS"),
881 active_methods=active_methods,
882 current_methods_msg=current_methods_msg,
883 setup_methods=setup_methods,
884 us_setup_form=form,
885 **_security._run_ctx_processor("us_setup"),
886 )
887
888 state_token = _security.us_setup_serializer.dumps(state)
889 json_response = dict(
890 chosen_method=form.chosen_method.data,
891 phone=phone_number,
892 state=state_token,
893 )
894
895 if form.chosen_method.data == "authenticator":
896 authr_setup_values = _security.totp_factory.fetch_setup_values(
897 totp, current_user
898 )
899
900 # Add all the values used in qrcode to json response
901 json_response["authr_key"] = authr_setup_values["key"]
902 json_response["authr_b32key"] = authr_setup_values["b32key"]
903 json_response["authr_username"] = authr_setup_values["username"]
904 json_response["authr_issuer"] = authr_setup_values["issuer"]
905 json_response["authr_uri"] = authr_setup_values["uri"]
906
907 qrcode_values = dict(
908 authr_qrcode=authr_setup_values["image"],
909 authr_key=authr_setup_values["key"],
910 authr_username=authr_setup_values["username"],
911 authr_issuer=authr_setup_values["issuer"],
912 )
913
914 if _security._want_json(request):
915 return base_render_json(form, include_user=False, additional=json_response)
916 form.delete_method.data = None
917 return _security.render_template(
918 cv("US_SETUP_TEMPLATE"),
919 available_methods=cv("US_ENABLED_METHODS"),
920 active_methods=active_methods,
921 current_methods_msg=current_methods_msg,
922 setup_methods=setup_methods,
923 code_sent=form.chosen_method.data in _compute_code_methods(),
924 chosen_method=form.chosen_method.data,
925 us_setup_form=form,
926 us_setup_validate_form=build_form("us_setup_validate_form"),
927 **qrcode_values,
928 state=state_token,
929 **_security._run_ctx_processor("us_setup"),
930 )
931
932 phone_number = None
933 if "sms" in cv("US_ENABLED_METHODS"):
934 phone_number = current_user.us_phone_number
935
936 # Get here on initial new setup (GET)
937 # Or failure of POST
938 if _security._want_json(request):
939 payload = {
940 "identity_attributes": get_identity_attributes(),
941 "available_methods": cv("US_ENABLED_METHODS"),
942 "active_methods": active_methods,
943 "setup_methods": setup_methods,
944 "phone": phone_number,
945 }
946 return base_render_json(form, include_user=False, additional=payload)
947
948 # Show user existing phone number
949 form.phone.data = phone_number
950 form.chosen_method.data = None
951 form.delete_method.data = None
952 return _security.render_template(
953 cv("US_SETUP_TEMPLATE"),
954 available_methods=cv("US_ENABLED_METHODS"),
955 active_methods=active_methods,
956 current_methods_msg=current_methods_msg,
957 setup_methods=setup_methods,
958 us_setup_form=form,
959 **_security._run_ctx_processor("us_setup"),
960 )
961
962
963 @auth_required(lambda: cv("API_ENABLED_METHODS"))
964 def us_setup_validate(token: str) -> ResponseValue:
965 """
966 Validate new setup.
967 The token is the state variable that is signed and timed
968 and contains all the state that once confirmed will be stored in the user record.
969 """
970 form = t.cast(
971 UnifiedSigninSetupValidateForm,
972 build_form_from_request("us_setup_validate_form"),
973 )
974
975 expired, invalid, state = check_and_get_token_status(
976 token, "us_setup", get_within_delta("US_SETUP_WITHIN")
977 )
978 if invalid:
979 m, c = get_message("API_ERROR")
980 if expired:
981 m, c = get_message("US_SETUP_EXPIRED", within=cv("US_SETUP_WITHIN"))
982 if invalid or expired:
983 if _security._want_json(request):
984 form.form_errors.append(m)
985 return base_render_json(form, include_user=False)
986 do_flash(m, c)
987 return redirect(url_for_security("us_setup"))
988
989 form.totp_secret = state["totp_secret"]
990 form.user = current_user
991
992 if form.validate_on_submit():
993 after_this_request(view_commit)
994 method = state["chosen_method"]
995 phone = state["phone_number"] if method == "sms" else None
996 _datastore.us_set(current_user, method, state["totp_secret"], phone)
997
998 us_profile_changed.send(
999 current_app._get_current_object(), # type: ignore
1000 _async_wrapper=current_app.ensure_sync, # type: ignore[arg-type]
1001 user=current_user,
1002 methods=[method],
1003 delete=False,
1004 )
1005 if _security._want_json(request):
1006 phone_number = None
1007 if "sms" in cv("US_ENABLED_METHODS"):
1008 phone_number = current_user.us_phone_number
1009 return base_render_json(
1010 form,
1011 include_user=False,
1012 additional=dict(chosen_method=method, phone=phone_number),
1013 )
1014 else:
1015 do_flash(*get_message("US_SETUP_SUCCESSFUL"))
1016 return redirect(get_url(cv("US_POST_SETUP_VIEW")))
1017
1018 # Code not correct/outdated.
1019 if _security._want_json(request):
1020 return base_render_json(form, include_user=False)
1021 m, c = get_message("INVALID_PASSWORD_CODE")
1022 do_flash(m, c)
1023 return redirect(url_for_security("us_setup"))
1024
1025
1026 def us_send_security_token(
1027 user, method, totp_secret, phone_number, send_magic_link=False
1028 ):
1029 """Generate and send the security code.
1030
1031 :param user: The user to send the code to
1032 :param method: The method in which the code will be sent
1033 :param totp_secret: the unique shared secret of the user
1034 :param phone_number: If 'sms' phone number to send to
1035 :param send_magic_link: If true a magic link that can be clicked on will be sent.
1036 This shouldn't be sent during a setup.
1037
1038 There is no return value - it is assumed that exceptions are thrown by underlying
1039 methods that callers can catch.
1040
1041 Flask-Security code should NOT call this directly -
1042 call :meth:`.UserMixin.us_send_security_token`
1043
1044 .. versionadded:: 3.4.0
1045 """
1046 code = _security.totp_factory.generate_totp_password(totp_secret)
1047
1048 if method == "email":
1049 login_link = None
1050 if send_magic_link:
1051 login_link = url_for_security(
1052 "us_verify_link", id=str(user.fs_uniquifier), code=code, _external=True
1053 )
1054 send_mail(
1055 cv("US_EMAIL_SUBJECT"),
1056 user.email,
1057 "us_instructions",
1058 user=user,
1059 username=user.calc_username(),
1060 token=code, # deprecated
1061 login_token=code,
1062 login_link=login_link,
1063 )
1064 elif method == "sms":
1065 m, c = get_message("USE_CODE", code=code)
1066 from_number = cv("SMS_SERVICE_CONFIG")["PHONE_NUMBER"]
1067 to_number = phone_number
1068 sms_sender = SmsSenderFactory.createSender(cv("SMS_SERVICE"))
1069 sms_sender.send_sms(from_number=from_number, to_number=to_number, msg=m)
1070
1071 elif method == "authenticator" or method == "password":
1072 # tokens are generated automatically with authenticator apps
1073 # and passwords are well passwords
1074 # Still go ahead and notify signal receivers that they requested it.
1075 code = None
1076 us_security_token_sent.send(
1077 current_app._get_current_object(),
1078 _async_wrapper=current_app.ensure_sync,
1079 user=user,
1080 method=method,
1081 token=code,
1082 login_token=code,
1083 phone_number=phone_number,
1084 send_magic_link=send_magic_link,
1085 )