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