Debian Codegraph @

flask_security/twofactor.py

raw
1 """
2 flask_security.two_factor
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security two_factor module
6
7 :copyright: (c) 2016 by Gal Stainfeld, at Emedgene
8 :copyright: (c) 2019-2025 by J. Christopher Wagner (jwag).
9 """
10
11 from __future__ import annotations
12
13 import typing as t
14 from datetime import timedelta
15
16 from flask import current_app, redirect, request, session
17
18 from .forms import (
19 _setup_methods_xlate,
20 get_form_field_xlate,
21 DummyForm,
22 TwoFactorRescueForm,
23 )
24 from .proxies import _security, _datastore
25 from .tf_plugin import TfPluginBase, tf_clean_session
26 from .utils import (
27 _,
28 SmsSenderFactory,
29 base_render_json,
30 _config_value as cv,
31 do_flash,
32 get_message,
33 localize_callback,
34 json_error_response,
35 send_mail,
36 url_for_security,
37 _td_format,
38 )
39 from .signals import (
40 tf_code_confirmed,
41 tf_disabled,
42 tf_security_token_sent,
43 tf_profile_changed,
44 )
45
46 if t.TYPE_CHECKING: # pragma: no cover
47 import flask
48 from flask_security import Security, UserMixin
49 from flask.typing import ResponseValue
50
51
52 def tf_send_security_token(
53 user: UserMixin, method: str, totp_secret: str, phone_number: str | None
54 ) -> None:
55 """Sends the security token via email/sms for the specified user.
56
57 :param user: The user to send the code to
58 :param method: The method in which the code will be sent
59 ('email' or 'sms', or 'authenticator') at the moment
60 :param totp_secret: a unique shared secret of the user
61 :param phone_number: If 'sms' phone number to send to
62
63 There is no return value - it is assumed that exceptions are thrown by underlying
64 methods that callers can catch.
65
66 Flask-Security code should NOT call this directly -
67 call :meth:`.UserMixin.tf_send_security_token`
68 """
69 token_to_be_sent: str | None = _security.totp_factory.generate_totp_password(
70 totp_secret
71 )
72 if method == "email" or method == "mail":
73 send_mail(
74 cv("EMAIL_SUBJECT_TWO_FACTOR"),
75 user.email,
76 cv("TWO_FACTOR_EMAIL_TEMPLATE"),
77 user=user,
78 token=token_to_be_sent,
79 username=user.calc_username(),
80 within=_td_format(timedelta(seconds=cv("TWO_FACTOR_MAIL_VALIDITY"))),
81 )
82 elif method == "sms":
83 m, c = get_message("USE_CODE", code=token_to_be_sent)
84 from_number = cv("SMS_SERVICE_CONFIG")["PHONE_NUMBER"]
85 assert phone_number
86 to_number = phone_number
87 sms_sender = SmsSenderFactory.createSender(cv("SMS_SERVICE"))
88 sms_sender.send_sms(from_number=from_number, to_number=to_number, msg=m)
89
90 else:
91 # password are generated automatically in the authenticator apps or not needed
92 token_to_be_sent = None
93
94 tf_security_token_sent.send(
95 current_app._get_current_object(), # type: ignore[attr-defined]
96 _async_wrapper=current_app.ensure_sync,
97 user=user,
98 method=method,
99 token=token_to_be_sent,
100 login_token=token_to_be_sent,
101 phone_number=phone_number,
102 )
103
104
105 def _complete_two_factor_process(user, primary_method, totp_secret, is_changing):
106 """clean session according to process (login or changing two-factor method)
107 and perform action accordingly
108 """
109
110 _datastore.tf_set(user, primary_method, totp_secret=totp_secret)
111
112 # if we are changing two-factor method
113 dologin = False
114 if is_changing:
115 # As of 5.5.0 this is the legacy path (using session data)
116 completion_message = "TWO_FACTOR_CHANGE_METHOD_SUCCESSFUL"
117 tf_profile_changed.send(
118 current_app._get_current_object(),
119 _async_wrapper=current_app.ensure_sync,
120 user=user,
121 method=primary_method,
122 )
123 # if we are logging in for the first time
124 else:
125 completion_message = "TWO_FACTOR_LOGIN_SUCCESSFUL"
126 tf_code_confirmed.send(
127 current_app._get_current_object(),
128 _async_wrapper=current_app.ensure_sync,
129 user=user,
130 method=primary_method,
131 )
132 dologin = True
133 token = _security.two_factor_plugins.tf_complete(user, dologin)
134 return completion_message, token
135
136
137 def _set_rescue_options(form: TwoFactorRescueForm, user: UserMixin) -> dict[str, str]:
138 # Based on config - set up options for rescue.
139 # Note that this modifies the passed in Form as well as returns
140 # a dict that can be returned as part of a JSON response.
141 recovery_options = dict(help=url_for_security("two_factor_rescue"))
142
143 if cv("TWO_FACTOR_RESCUE_EMAIL"):
144 recovery_options["email"] = url_for_security("two_factor_rescue")
145 assert isinstance(form.help_setup.choices, list)
146 form.help_setup.choices.append(
147 ("email", get_form_field_xlate(_("Send code via email")))
148 )
149
150 if (
151 _security.support_mfa
152 and cv("MULTI_FACTOR_RECOVERY_CODES")
153 and _datastore.mf_get_recovery_codes(user)
154 ):
155 recovery_options["recovery_code"] = url_for_security("mf_recovery")
156 assert isinstance(form.help_setup.choices, list)
157 form.help_setup.choices.append(
158 (
159 "recovery_code",
160 get_form_field_xlate(_("Use previously downloaded recovery code")),
161 )
162 )
163 return recovery_options
164
165
166 def tf_disable(user: UserMixin) -> None:
167 """Disable two factor for user"""
168 tf_clean_session()
169 _datastore.tf_reset(user)
170 tf_disabled.send(
171 current_app._get_current_object(), # type: ignore[attr-defined]
172 _async_wrapper=current_app.ensure_sync,
173 user=user,
174 )
175
176
177 def is_tf_setup(user: UserMixin) -> bool:
178 """Return True is user account is setup for 2FA."""
179 return bool(user.tf_totp_secret and user.tf_primary_method)
180
181
182 class CodeTfPlugin(TfPluginBase):
183 def __init__(self, app: flask.Flask):
184 super().__init__(app)
185
186 def create_blueprint(
187 self, app: flask.Flask, bp: flask.Blueprint, state: Security
188 ) -> None:
189 pass
190
191 def get_setup_methods(self, user: UserMixin) -> list[tuple[str, str]]:
192 if is_tf_setup(user):
193 assert user.tf_primary_method is not None
194 return [
195 (
196 user.tf_primary_method,
197 localize_callback(_setup_methods_xlate[user.tf_primary_method]),
198 )
199 ]
200 return []
201
202 def tf_login(
203 self, user: UserMixin, json_payload: dict[str, t.Any], next_loc: str | None
204 ) -> ResponseValue:
205 """Helper for two-factor authentication login
206
207 This is called only when login/password have already been validated.
208 This can be from login, register, confirm, unified sign in, unified magic link.
209
210 If two-factor is already setup then this sends a code if the method requires it.
211 If not, then user is redirected to two-factor-setup.
212 In either case we do NOT log in user, so we must store some info in session to
213 track our state (including what user).
214 """
215
216 # if user's two-factor properties are not configured
217 if not is_tf_setup(user):
218 session["tf_state"] = "setup_from_login"
219 json_payload["tf_state"] = "setup_from_login"
220 if not _security._want_json(request):
221 return redirect(url_for_security("two_factor_setup"))
222
223 # if user's two-factor properties are configured
224 else:
225 session["tf_state"] = "ready"
226 json_payload["tf_state"] = "ready"
227 json_payload["tf_primary_method"] = user.tf_primary_method
228 json_payload["tf_method"] = user.tf_primary_method
229
230 if user.tf_primary_method in ["mail", "email", "sms"]:
231 msg = user.tf_send_security_token(
232 method=user.tf_primary_method,
233 totp_secret=user.tf_totp_secret,
234 phone_number=getattr(user, "tf_phone_number", None),
235 )
236 if msg:
237 # send code didn't work
238 if not _security._want_json(request):
239 # This is a mess -
240 # we are deep down in the login/unified sign in flow.
241 do_flash(msg, "error")
242 return redirect(url_for_security("login"))
243 else:
244 payload = json_error_response(errors=msg)
245 return _security._render_json(payload, 500, None, None)
246
247 if not _security._want_json(request):
248 values = dict(next=next_loc) if next_loc else dict()
249 return redirect(
250 url_for_security("two_factor_token_validation", **values)
251 )
252
253 # JSON response - Fake up a form - doesn't really matter which.
254 form = DummyForm(formdata=None)
255 return base_render_json(form, include_user=False, additional=json_payload)