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