Debian Codegraph @

flask_security/utils.py

raw
1 """
2 flask_security.utils
3 ~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security utils module
6
7 :copyright: (c) 2012-2019 by Matt Wright.
8 :copyright: (c) 2019-2025 by J. Christopher Wagner (jwag).
9 :license: MIT, see LICENSE for more details.
10 """
11
12 from __future__ import annotations
13
14 import abc
15 import base64
16 from datetime import datetime, timedelta, timezone
17 from functools import partial
18 import hashlib
19 import hmac
20 import time
21 import typing as t
22 from urllib.parse import parse_qsl, quote, urlsplit, urlunsplit, urlencode
23 import urllib.request
24 import urllib.error
25 import warnings
26
27 from flask import (
28 Response,
29 after_this_request,
30 current_app,
31 flash,
32 g,
33 redirect,
34 request,
35 render_template,
36 session,
37 url_for,
38 )
39 from flask_login import login_user as _login_user
40 from flask_login import logout_user as _logout_user
41 from flask_login import current_user
42 from flask_login import COOKIE_NAME as REMEMBER_COOKIE_NAME
43 from flask_principal import AnonymousIdentity, Identity, identity_changed, Need
44 from flask_wtf import csrf, FlaskForm
45 from wtforms import ValidationError
46 from itsdangerous import BadSignature, SignatureExpired
47 from werkzeug.local import LocalProxy
48 from werkzeug.datastructures import MultiDict
49
50 from .quart_compat import best, get_quart_status
51 from .proxies import _security, _datastore, _pwd_context, _hashing_context
52 from .signals import user_authenticated
53
54 if t.TYPE_CHECKING: # pragma: no cover
55 from flask import Flask
56 from flask.typing import ResponseValue
57 from flask_security import UserMixin
58
59 localize_callback = LocalProxy(lambda: _security.i18n_domain.gettext)
60
61 FsPermNeed = partial(Need, "fsperm")
62 FsPermNeed.__doc__ = """A need with the method preset to `"fsperm"`."""
63
64
65 def _(translate):
66 """Identity function to mark strings for translation."""
67 return translate
68
69
70 def get_request_attr(name: str) -> t.Any:
71 """Retrieve a request local attribute.
72
73 Current public attributes are:
74
75 **fs_authn_via**
76 will be set to the authentication mechanism (session, token, basic)
77 that the current request was authenticated with.
78
79 Returns None if attribute doesn't exist.
80
81 .. versionadded:: 4.0.0
82 .. versionchanged:: 4.1.5
83 Use 'g' rather than request_ctx stack which is going away post Flask 2.2
84 """
85 return getattr(g, name, None)
86
87
88 def set_request_attr(name: str, value: t.Any) -> None:
89 """Set an attribute on Flask's application context global object (g).
90
91 :param name: The key/attribute name to store the value under
92 :param value: The value to store in the application context
93 """
94 return setattr(g, name, value)
95
96
97 """
98 Most view functions that modify the DB will call ``after_this_request(view_commit)``
99 Quart compatibility needs an async version
100 """
101 if get_quart_status(): # pragma: no cover
102
103 async def view_commit(response=None):
104 _datastore.commit()
105 return response
106
107 else:
108
109 def view_commit(response=None): # type: ignore[misc]
110 _datastore.commit()
111 return response
112
113
114 def aware_utcnow() -> datetime:
115 """Return a timezone-aware UTC datetime object.
116
117 From a miguel grinberg blog around dealing with 3.12.
118 Our default SQLAlchemy Datetime is naive.
119 Note that most code should call _security.datetime_factory()
120
121 :return: Current UTC datetime with timezone information
122 :rtype: datetime
123 """
124 return datetime.now(timezone.utc)
125
126
127 def aware_utcfromtimestamp(timestamp: float) -> datetime:
128 """Create timezone-aware UTC datetime from timestamp.
129
130 :param timestamp: Unix timestamp (seconds since epoch)
131 :type timestamp: float
132 :return: UTC datetime with timezone information
133 :rtype: datetime
134 """
135 return datetime.fromtimestamp(timestamp, timezone.utc)
136
137
138 def naive_utcnow() -> datetime:
139 """Return a naive UTC datetime (tzinfo removed).
140
141 :return: Current UTC datetime without timezone information
142 :rtype: datetime
143 """
144 return aware_utcnow().replace(tzinfo=None)
145
146
147 def naive_utcfromtimestamp(timestamp: float) -> datetime:
148 """Create naive UTC datetime from timestamp.
149
150 :param timestamp: Unix timestamp (seconds since epoch)
151 :type timestamp: float
152 :return: UTC datetime without timezone information
153 :rtype: datetime
154 """
155 return aware_utcfromtimestamp(timestamp).replace(tzinfo=None)
156
157
158 def find_csrf_field_name() -> t.Optional[str]:
159 """Retrieve the configured CSRF field name from Flask-WTF form configuration.
160
161 This is needed to properly clear CSRF tokens on logout since Flask-WTF doesn't
162 automatically handle this case. The field name can be configured through
163 Flask-WTF's settings or overridden in form classes.
164
165 :return: Configured CSRF field name if found, None otherwise
166 :rtype: Optional[str]
167
168 Note:
169 Uses the field name from the login form as set by the Flask-WTF configuration.
170 Requires a DummyForm class with Flask-WTF's meta configuration.
171 """
172 from .forms import DummyForm
173
174 form = DummyForm(formdata=None)
175 if hasattr(form.meta, "csrf_field_name"):
176 return form.meta.csrf_field_name
177 return None
178
179
180 def is_user_authenticated(user: UserMixin | None) -> bool:
181 """
182 return True if user is authenticated.
183
184 With Flask-Login <=0.6.x and Flask-Security <5.4 current_user was always
185 set - for non-authenticated users it pointed to an AnonymousUser
186 Flask-Login is experimenting (11/5/23) with a LOGIN_NO_ANONYMOUS which will set
187 current_user to None and deprecate is_authenticated (current_user non None implies
188 authenticated).
189 We have a configuration variable ANONYMOUS_USER_DISABLED which if true will force
190 current_user to None on unauthenticated as well
191 """
192 if config_value("ANONYMOUS_USER_DISABLED"):
193 # Note that user often is current_user which is a proxy and isn't ever actually
194 # 'None'
195 return bool(user)
196 return bool(user and user.is_authenticated)
197
198
199 def login_user(
200 user: UserMixin,
201 remember: bool | None = None,
202 authn_via: list[str] | None = None,
203 ) -> bool:
204 """Perform the login routine.
205
206 If :py:data:`SECURITY_TRACKABLE` is used, make sure you commit changes after this
207 request (i.e. ``app.security.datastore.commit()``).
208
209 :param user: The user to login
210 :param remember: Flag specifying if the remember cookie should be set.
211 If ``None`` use value of :py:data:`SECURITY_DEFAULT_REMEMBER_ME`
212 :param authn_via: A list of strings denoting which mechanism(s) the user
213 authenticated with.
214 These should be one or more of ["password", "sms", "authenticator", "email"] or
215 other 'auto-login' mechanisms.
216 :return: True if user successfully logged in.
217 """
218
219 if remember is None:
220 remember = config_value("DEFAULT_REMEMBER_ME")
221
222 if not _login_user(user, remember, force=True): # pragma: no cover
223 return False
224
225 if _security.trackable:
226 remote_addr = request.remote_addr or None # make sure it is None
227
228 old_current_login, new_current_login = (
229 user.current_login_at,
230 _security.datetime_factory(),
231 )
232 old_current_ip, new_current_ip = user.current_login_ip, remote_addr
233
234 user.last_login_at = old_current_login or new_current_login
235 user.current_login_at = new_current_login
236 user.last_login_ip = old_current_ip
237 user.current_login_ip = new_current_ip
238 user.login_count = user.login_count + 1 if user.login_count else 1
239
240 _datastore.put(user)
241
242 session["fs_cc"] = "set" # CSRF cookie
243 session["fs_paa"] = time.time() # Primary authentication at - timestamp
244
245 identity_changed.send(
246 current_app._get_current_object(), # type: ignore[attr-defined]
247 _async_wrapper=current_app.ensure_sync, # type: ignore[arg-type]
248 identity=Identity(user.fs_uniquifier),
249 )
250
251 user_authenticated.send(
252 current_app._get_current_object(), # type: ignore[attr-defined]
253 _async_wrapper=current_app.ensure_sync, # type: ignore[arg-type]
254 user=user,
255 authn_via=authn_via,
256 )
257 return True
258
259
260 def logout_user() -> None:
261 """Logs out the current user.
262
263 This will also clean up the remember me cookie if it exists.
264
265 This sends an ``identity_changed`` signal to note that the current
266 identity is now the `AnonymousIdentity`
267 """
268
269 for key in (
270 "identity.name",
271 "identity.auth_type",
272 "fs_paa",
273 "fs_gexp",
274 "fs_oauth_next",
275 ):
276 session.pop(key, None)
277
278 # Clear csrf token between sessions.
279 # Ideally this would be handled by Flask-WTF but...
280 # We don't clear entire session since Flask-Login seems to like having it.
281 csrf_field_name = find_csrf_field_name()
282 if csrf_field_name:
283 session.pop(csrf_field_name, None)
284 # Flask-WTF 'caches' csrf_token - and only set the session if not already
285 # in 'g'. Be sure to clear both. This affects at least /confirm
286 g.pop(csrf_field_name, None)
287 session["fs_cc"] = "clear"
288 identity_changed.send(
289 current_app._get_current_object(), # type: ignore
290 _async_wrapper=current_app.ensure_sync,
291 identity=AnonymousIdentity(),
292 )
293 _logout_user()
294
295
296 def check_and_update_authn_fresh(
297 within: timedelta,
298 grace: timedelta,
299 method: str | None = None,
300 ) -> bool:
301 """Check if user authenticated within specified time and update grace period.
302
303 :param within: A timedelta specifying the maximum time in the past that the caller
304 authenticated that is still considered 'fresh'.
305 :param grace: A timedelta that, if the current session is considered 'fresh'
306 will set a grace period for which freshness won't be checked.
307 The intent here is that the caller shouldn't get part-way though
308 a set of operations and suddenly be required to authenticate again.
309 This is not supported for authentication tokens.
310 :param method: Optional - if set and == "basic" then will always return True.
311 (since basic-auth sends username/password on every request)
312
313 If within.total_seconds() is negative, will always return True (always 'fresh').
314 This effectively just disables this entire mechanism.
315
316 within.total_seconds() == 0 results in undefined behavior.
317
318 If "fs_gexp" is in the session and the current timestamp is less than that,
319 return True and extend grace time (i.e. set fs_gexp to current time + grace).
320
321 Be aware that for this to work, state is required to be sent from the client.
322 Flask security adds this state to the session (cookie) and the auth token.
323 Without this state, 'False' is always returned - (not fresh).
324
325 .. warning::
326 Be sure the caller is already authenticated PRIOR to calling this method.
327
328 .. versionadded:: 3.4.0
329
330 .. versionchanged:: 4.0.0
331 Added `method` parameter.
332
333 .. versionchanged:: 5.5.0
334 Grab 'Primary Authenticated At' from request_attrs
335 which is set from either session or auth token
336 """
337
338 if method == "basic":
339 return True
340
341 if within.total_seconds() < 0:
342 # this means 'always fresh'
343 return True
344
345 if not (paa := get_request_attr("fs_paa")):
346 # No recorded primary authenticated at time, you can't play.
347 return False
348
349 now = naive_utcnow()
350 new_exp = now + grace
351 grace_ts = int(new_exp.timestamp())
352
353 if fs_gexp := session.get("fs_gexp", None):
354 if now.timestamp() < fs_gexp:
355 # Within grace period - extend it, and we're good.
356 session["fs_gexp"] = grace_ts
357 return True
358
359 authn_time = naive_utcfromtimestamp(paa)
360 # allow for some time drift where it's possible authn_time is in the future
361 # but let's be cautious and not allow arbitrary future times
362 delta = now - authn_time
363 if within > delta > -within:
364 session["fs_gexp"] = grace_ts
365 return True
366 return False
367
368
369 def get_hmac(password: str | bytes) -> bytes:
370 """Returns a Base64 encoded HMAC+SHA512 of the password signed with
371 the salt specified by :py:data:`SECURITY_PASSWORD_SALT`.
372
373 :param password: The password to sign
374 """
375 if not (salt := config_value("PASSWORD_SALT")):
376 raise RuntimeError(
377 "The configuration value `SECURITY_PASSWORD_SALT` must "
378 "not be None when the value of `SECURITY_PASSWORD_HASH` is "
379 'set to "%s"' % config_value("PASSWORD_HASH")
380 )
381
382 h = hmac.new(encode_string(salt), encode_string(password), hashlib.sha512)
383 return base64.b64encode(h.digest())
384
385
386 def verify_password(password: str | bytes, password_hash: str | bytes) -> bool:
387 """Returns ``True`` if the password matches the supplied hash.
388
389 :param password: A plaintext password to verify
390 :param password_hash: The expected hash value of the password
391 (usually from your database)
392
393 .. note::
394 Make sure that the password passed in has already been normalized.
395 """
396 if use_double_hash(password_hash):
397 password = get_hmac(password)
398 if _pwd_context.identify(password_hash) == "bcrypt":
399 password = password[:72]
400
401 return _pwd_context.verify(password, password_hash)
402
403
404 def verify_and_update_password(password: str | bytes, user: UserMixin) -> bool:
405 """Returns ``True`` if the password is valid for the specified user.
406
407 Additionally, the hashed password in the database is updated if the
408 hashing algorithm happens to have changed.
409
410 N.B. you MUST call DB commit if you are using a session-based datastore
411 (such as SqlAlchemy) since the user instance might have been altered
412 (i.e. ``app.security.datastore.commit()``).
413 This is usually handled in the view.
414
415 :param password: A plaintext password to verify
416 :param user: The user to verify against
417
418 .. tip::
419 This should not be called directly - rather use
420 :meth:`.UserMixin.verify_and_update_password`
421
422 """
423 # Capture the original input in case we need to pass the unaltered
424 # value to hash_password if the hashing algorithm has changed
425 input_password = password
426
427 if use_double_hash(user.password):
428 password = get_hmac(password)
429 if _pwd_context.identify(user.password) == "bcrypt":
430 password = password[:72]
431 verified = _pwd_context.verify(password, user.password)
432 else:
433 # Try with original password.
434 verified = _pwd_context.verify(password, user.password)
435
436 if verified and (user.password is None or _pwd_context.needs_update(user.password)):
437 user.password = hash_password(input_password)
438 _datastore.put(user)
439 return verified
440
441
442 def hash_password(password: str | bytes) -> str:
443 """Hash the specified plaintext password.
444
445 Unless the hash algorithm (as specified by
446 :py:data:`SECURITY_PASSWORD_HASH`) is listed in
447 the configuration variable :py:data:`SECURITY_PASSWORD_SINGLE_HASH`,
448 perform a double hash - first create an HMAC from the plaintext password
449 and the value of :py:data:`SECURITY_PASSWORD_SALT`,
450 then use the configured hashing algorithm.
451 This satisfies OWASP/ASVS section 2.4.5: 'provide additional
452 iteration of a key derivation'.
453
454 .. versionadded:: 2.0.2
455
456 .. versionchanged:: 5.7.0
457 Explicit check for bcrypt truncation
458
459 :param password: The plaintext password to hash
460 """
461 if use_double_hash():
462 password = get_hmac(password).decode("ascii")
463
464 # Passing in options as part of hash is deprecated in passlib 1.7
465 # and new algorithms like argon2 don't even support it.
466 if config_value("PASSWORD_HASH") == "bcrypt":
467 # bcrypt - OWASP says truncation concerns are negligible:
468 # https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#input-limits-of-bcrypt
469 password = password[:72]
470
471 return _pwd_context.hash(
472 password,
473 **config_value("PASSWORD_HASH_OPTIONS", default={}).get(
474 config_value("PASSWORD_HASH"), {}
475 ),
476 )
477
478
479 def encode_string(string: t.Union[str, bytes]) -> bytes:
480 """Encodes a string to bytes, if it isn't already.
481
482 :param string: The string to encode
483 :return: UTF-8 encoded bytes
484 """
485 if isinstance(string, str):
486 string = string.encode("utf-8")
487 return string
488
489
490 def hash_data(data: t.Union[str, bytes]) -> str:
491 """Hashes input data after ensuring proper encoding.
492
493 :param data: Input data to hash (will be encoded if not already bytes)
494 :return: Hashed data as bytes
495
496 Note: Uses application's configured _hashing_context
497 """
498 return _hashing_context.hash(encode_string(data))
499
500
501 def verify_hash(hashed_data: bytes, compare_data: t.Union[str, bytes]) -> bool:
502 """Verifies data against a previously hashed value.
503
504 :param hashed_data: Previously hashed data to compare against
505 :param compare_data: Input data to verify (will be encoded if not already bytes)
506 :return: True if data matches hash, False otherwise
507
508 Note: Uses application's configured _hashing_context
509 """
510 return _hashing_context.verify(encode_string(compare_data), hashed_data)
511
512
513 def suppress_form_csrf():
514 """
515 Return meta contents if we should suppress form from attempting to validate CSRF.
516
517 If app doesn't want CSRF for unauth endpoints then check if caller is authenticated
518 or not (many endpoints can be called either way).
519 """
520 if config_value("CSRF_IGNORE_UNAUTH_ENDPOINTS") and not is_user_authenticated(
521 current_user
522 ):
523 return {"csrf": False}
524 return {}
525
526
527 def confirm_redirect(form, identity_attribute):
528 """This is a very specific utility that all open endpoints call
529 to implement the confirm redirect feature.
530 """
531 if (
532 form.requires_confirmation
533 and config_value("REQUIRES_CONFIRMATION_ERROR_VIEW")
534 and not config_value("RETURN_GENERIC_RESPONSES")
535 ):
536 do_flash(*get_message("CONFIRMATION_REQUIRED"))
537 return redirect(
538 get_url(
539 config_value("REQUIRES_CONFIRMATION_ERROR_VIEW"),
540 qparams={identity_attribute: getattr(form.user, identity_attribute)},
541 )
542 )
543 return None
544
545
546 def do_flash(message: str, category: str) -> None:
547 """Flash a message depending on if the `FLASH_MESSAGES` configuration
548 value is set.
549
550 :param message: The flash message
551 :param category: The flash message category
552 """
553 if config_value("FLASH_MESSAGES"):
554 flash(message, category)
555
556
557 def parse_auth_token(auth_token: str) -> dict[str, t.Any]:
558 """Parse an authentication token.
559 This will raise an exception if not properly signed or expired
560 """
561 tdata = dict()
562
563 # This can raise BadSignature or SignatureExpired exceptions from itsdangerous
564 raw_data = _security.remember_token_serializer.loads(
565 auth_token, max_age=config_value("TOKEN_MAX_AGE")
566 )
567
568 # Version 3.x generated tokens that map to data with 3 elements,
569 # and fs_uniquifier was on last element.
570 # Version 4.0.0 generates tokens that map to data with only 1 element,
571 # which maps to fs_uniquifier.
572 # Version 5 and up are already a dict (with a version #)
573 if isinstance(raw_data, dict):
574 # new format - starting at ver=5
575 if not all(k in raw_data for k in ["ver", "uid", "exp"]):
576 raise ValueError("Token missing keys")
577 tdata = raw_data
578 if ts := tdata.get("exp"):
579 if ts < int(time.time()):
580 raise SignatureExpired("token[exp] value expired")
581 else:
582 # old tokens that were lists
583 if len(raw_data) == 1:
584 # version 4
585 tdata["ver"] = "4"
586 tdata["uid"] = raw_data[0]
587 else:
588 # version 3
589 tdata["ver"] = "3"
590 tdata["uid"] = raw_data[2]
591
592 return tdata
593
594
595 def get_url(endpoint_or_url: str, qparams: dict[str, str] | None = None) -> str:
596 """Returns a URL if a valid endpoint is found. Otherwise, returns the
597 provided value.
598
599 .. warning::
600 If an endpoint ISN'T provided, then it is assumed that the URL
601 is external to Flask and if the spa configuration REDIRECT_HOST
602 is set will redirect to that host. This could be an issue in
603 development.
604
605 :param endpoint_or_url: The endpoint name or URL to default to
606 :param qparams: additional query params to add to end of url
607 :return: URL
608 """
609 try:
610 return transform_url(url_for(endpoint_or_url), qparams)
611 except Exception:
612 # This is an external URL (no endpoint defined in app)
613 # For (mostly) testing - allow changing/adding the url - for example
614 # add a different host:port for cases where the UI is running
615 # separately.
616 if config_value("REDIRECT_HOST"):
617 url = transform_url(
618 endpoint_or_url, qparams, netloc=config_value("REDIRECT_HOST")
619 )
620 else:
621 url = transform_url(endpoint_or_url, qparams)
622
623 return url
624
625
626 def slash_url_suffix(url: str, suffix: str) -> str:
627 """
628 Formats a suffix to be appended to a URL, ensuring proper slash placement.
629
630 If the given `url` ends with a slash, this function adds a trailing slash
631 to the `suffix`.
632 Otherwise, it adds a leading slash to the `suffix`.
633 This helps prevent double slashes or missing slashes when constructing URLs.
634
635 :param url: The base URL to which the suffix will be appended.
636 :param suffix: The suffix to be appended to the URL.
637 :return: The formatted suffix with the appropriate leading or trailing slash.
638
639 Example:
640 >>> slash_url_suffix("https://example.com/api", "v1")
641 '/v1'
642 >>> slash_url_suffix("https://example.com/api/", "v1")
643 'v1/'
644 """
645 return url.endswith("/") and f"{suffix}/" or f"/{suffix}"
646
647
648 def transform_url(
649 url: str, qparams: dict[str, str] | None = None, **kwargs: str
650 ) -> str:
651 """Modify url
652
653 :param url: url to transform (can be relative)
654 :param qparams: additional query params to add to end of url
655 :param kwargs: pieces of URL to modify - e.g. netloc=localhost:8000
656 :return: Modified URL
657
658 .. versionadded:: 3.2.0
659 """
660 link_parse = urlsplit(url)
661 if qparams:
662 current_query = dict(parse_qsl(link_parse.query))
663 current_query.update(qparams)
664 link_parse = link_parse._replace(query=urlencode(current_query))
665 return urlunsplit(link_parse._replace(**kwargs))
666
667
668 def get_security_endpoint_name(endpoint: str) -> str:
669 """
670 Returns the fully qualified endpoint name by combining the blueprint name
671 and the endpoint.
672
673 :param endpoint: The endpoint name to be combined with the blueprint name.
674 :return: The fully qualified endpoint name in the format '<blueprint>.<endpoint>'.
675
676 Example:
677 >>> get_security_endpoint_name("login")
678 'my_blueprint.login'
679 """
680 return f"{config_value('BLUEPRINT_NAME')}.{endpoint}"
681
682
683 def url_for_security(endpoint: str, **values: t.Any) -> str:
684 """Return a URL for the security blueprint
685
686 :param endpoint: the endpoint of the URL (name of the function)
687 :param values: the variable arguments of the URL rule
688 :param _external: if set to `True`, an absolute URL is generated. Server
689 address can be changed via `SERVER_NAME` configuration variable which
690 defaults to `localhost`.
691 :param _anchor: if provided, this is added as anchor to the URL.
692 :param _method: if provided, this explicitly specifies an HTTP method.
693 """
694 endpoint = get_security_endpoint_name(endpoint)
695 # mypy is complaining about this - but I think it's wrong?
696 return url_for(endpoint, **values) # type: ignore
697
698
699 def validate_redirect_url(url: str) -> bool:
700 """Validate redirect URL
701 In the default configuration only redirects to the same domain (and scheme)
702 are allowed.
703 The REDIRECT_ALLOW_SUBDOMAINS allows ANY subdomain of SERVER_NAME
704 to be a redirect target.
705 The REDIRECT_BASE_DOMAIN and REDIRECT_ALLOWED_SUBDOMAINS allow specifying 'side'
706 redirects.
707 """
708
709 if url is None or url.strip() == "":
710 return False
711 url_next = urlsplit(url)
712 url_base = urlsplit(request.host_url)
713 if (url_next.netloc or url_next.scheme) and url_next.netloc != url_base.netloc:
714 base_domain = current_app.config.get("SERVER_NAME")
715 if (
716 config_value("REDIRECT_ALLOW_SUBDOMAINS")
717 and base_domain
718 and (
719 url_next.netloc == base_domain
720 or url_next.netloc.endswith(f".{base_domain}")
721 )
722 ):
723 return True
724 base_domain = config_value("REDIRECT_BASE_DOMAIN")
725 if base_domain:
726 allowable = [
727 f"{sub}.{base_domain}"
728 for sub in config_value("REDIRECT_ALLOWED_SUBDOMAINS")
729 ]
730 return url_next.netloc in allowable
731 return False
732 return True
733
734
735 def get_post_action_redirect(
736 config_key: str, next_loc: FlaskForm | MultiDict | dict | None
737 ) -> str:
738 """
739 There is a security angle here - the result of this method is
740 sent to Flask::redirect() - and we need to be sure that it can't be
741 interpreted as a user-input external URL - that would mean we would
742 have an 'open-redirect' vulnerability.
743
744 Allowing an absolute redirect is a security issue - a so-called open-redirect.
745
746 The complexity here is that urlsplit() does pretty well, but browsers even today
747 May 2021 are very lenient in what they accept as URLs - for example:
748 next=\\\\github.com
749 next=%5C%5C%5Cgithub.com
750 next=/////github.com
751 next=%20\\\\github.com
752 next=%20///github.com
753 next=%20//github.com
754 next=%19////github.com - i.e. browser will strip control chars
755 next=%E2%80%8A///github.com - doesn't redirect! That is a unicode thin space.
756
757 All will result in a null netloc and scheme from urlsplit - however many browsers
758 will gladly strip off uninteresting characters and convert backslashes to forward
759 slashes - and the cases above will actually cause a redirect to github.com
760 Sigh.
761
762 Some articles claim that a relative url has to start with a '/' - but that isn't
763 strictly true. From: https://datatracker.ietf.org/doc/html/rfc3986#section-5
764 a relative path can start with a "//", "/", a non-colon, or be empty. So it seems
765 that all the above URLs are valid.
766 By the time we get the URL it may or may not have been unencoded - if part of a
767 query string, then it has been, but if set in the form, not.
768 This means we can't really determine
769 if it is 'valid' since it appears that '/'s can appear in the URL if escaped.
770
771 The solution is to simply 'quote' the path.
772
773 netloc has a same issue: https://amazon.com\\.lp.com will cause many
774 browsers to redirect to amazon.com
775 """
776 rurl = propagate_next(find_redirect(config_key), next_loc)
777
778 u = urlsplit(rurl)
779 userinfo = ""
780 if u.username or u.password:
781 userinfo = f"{u.username}:{u.password}@"
782 hostname = quote(u.hostname) if u.hostname else ""
783 if u.port:
784 netloc = f"{userinfo}{hostname}:{u.port}"
785 else:
786 netloc = f"{userinfo}{hostname}"
787
788 safe_url = urlunsplit((u.scheme, netloc, quote(u.path), u.query, u.fragment))
789 return safe_url
790
791
792 def get_post_login_redirect() -> str:
793 return get_post_action_redirect("SECURITY_POST_LOGIN_VIEW", request.form)
794
795
796 def get_post_register_redirect() -> str:
797 return get_post_action_redirect("SECURITY_POST_REGISTER_VIEW", request.form)
798
799
800 def get_post_logout_redirect() -> str:
801 return get_post_action_redirect("SECURITY_POST_LOGOUT_VIEW", request.form)
802
803
804 def get_post_verify_redirect() -> str:
805 return get_post_action_redirect("SECURITY_POST_VERIFY_VIEW", request.form)
806
807
808 def find_redirect(key: str) -> str:
809 """Returns the URL to redirect to.
810
811 :param key: The application configuration key to search for
812 """
813 app_url = None
814 if app_value := current_app.config[key.upper()]:
815 app_url = get_url(app_value)
816 rv = app_url or str(current_app.config.get("APPLICATION_ROOT", "/"))
817 return rv
818
819
820 def propagate_next(fallback_url: str, form: FlaskForm | MultiDict | dict | None) -> str:
821 """Compute appropriate redirect URL
822 The application can add a 'next' query parameter or have 'next' as a form field.
823 If either exist, make sure they are valid (not pointing to external location)
824 If neither, return the fallback_url
825
826 Can be passed either request.form
827 (which is really a MultiDict OR a real form OR a dict with a 'next' key).
828 """
829 form_next = None
830 if form and isinstance(form, FlaskForm):
831 if hasattr(form, "next") and form.next.data:
832 form_next = form.next.data
833 elif form and form.get("next", None):
834 form_next = str(form.get("next"))
835 arg_next = request.args.get("next")
836
837 urls = [
838 get_url(form_next) if form_next else None,
839 get_url(arg_next) if arg_next else None,
840 fallback_url,
841 ]
842 for url in urls:
843 if url and validate_redirect_url(url):
844 return url
845 raise ValueError("No valid redirect URL found - configuration error")
846
847
848 def simplify_url(base_url: str, redirect_url: str) -> str:
849 """
850 Reduces the scheme and host from the redirect_url so it can be passed
851 as a relative URL in a query (e.g. next) param.
852 For this method we aren't worrying about a valid url (e.g. if it points
853 externally) - that will be handled by later requests.
854
855 :param base_url: The URL to simplify 'against'.
856 :param redirect_url: The URL to reduce.
857 """
858 b_url = urlsplit(base_url)
859 r_url = urlsplit(redirect_url)
860
861 if (not r_url.scheme or r_url.scheme == b_url.scheme) and (
862 not r_url.netloc or r_url.netloc == b_url.netloc
863 ):
864 return urlunsplit(("", "", r_url.path, r_url.query, r_url.fragment))
865 return redirect_url
866
867
868 def get_message(key: str, **kwargs: t.Any) -> tuple[str, str]:
869 rv = config_value("MSG_" + key)
870 return localize_callback(rv[0], **kwargs), rv[1]
871
872
873 def config_value(key, app=None, default=None, strict=True):
874 """Get a Flask-Security configuration value.
875
876 :param key: The configuration key without the prefix `SECURITY_`
877 :param app: An optional specific application to inspect. Defaults to
878 Flask's `current_app`
879 :param default: An optional default value if the value is not set
880 :param strict: if True, will raise ValueError if key doesn't exist
881 """
882 app = app or current_app
883 key = f"SECURITY_{key.upper()}"
884 # protect against spelling mistakes
885 if strict and key not in app.config:
886 raise ValueError(f"Key {key} doesn't exist")
887 return app.config.get(key, default)
888
889
890 def get_max_age(key, app=None):
891 td = get_within_delta(key + "_WITHIN", app)
892 return td.seconds + td.days * 24 * 3600
893
894
895 def get_within_delta(key, app=None):
896 """Get a timedelta object from the application configuration following
897 the internal convention of::
898
899 <Amount of Units> <Type of Units>
900
901 Examples of valid config values::
902
903 5 days
904 10 minutes
905
906 :param key: The config value key without the `SECURITY_` prefix
907 :param app: Optional application to inspect. Defaults to Flask's
908 `current_app`
909 """
910 txt = config_value(key, app=app)
911 values = txt.split()
912 return timedelta(**{values[1]: int(values[0])})
913
914
915 def send_mail(subject, recipient, template, **context):
916 """Send an email.
917
918 :param subject: Email subject
919 :param recipient: Email recipient
920 :param template: The name of the email template
921 :param context: The context to render the template with
922
923 This formats the email and passes it off to :class:`.MailUtil` to actually send the
924 message.
925 """
926
927 context.setdefault("security", _security)
928 context.update(_security._run_ctx_processor("mail"))
929
930 body = None
931 html = None
932 template_path = f"security/email/{template}"
933 if config_value("EMAIL_PLAINTEXT"):
934 body = _security.render_template(f"{template_path}.txt", **context)
935 if config_value("EMAIL_HTML"):
936 html = _security.render_template(f"{template_path}.html", **context)
937
938 subject = localize_callback(subject)
939
940 sender = config_value("EMAIL_SENDER")
941 if isinstance(sender, LocalProxy):
942 sender = sender._get_current_object()
943
944 _security.mail_util.send_mail(
945 template,
946 subject,
947 recipient,
948 sender,
949 body,
950 html,
951 **context,
952 )
953
954
955 def get_token_status(token, serializer, max_age=None, return_data=False):
956 """Get the status of a token.
957
958 :param token: The token to check
959 :param serializer: The name of the serializer. Can be one of the
960 following: ``confirm``, ``login``, ``reset``
961 :param max_age: The name of the max age config option. Can be one of
962 the following: ``CONFIRM_EMAIL``, ``LOGIN``,
963 ``RESET_PASSWORD``
964
965 .. deprecated:: 5.0.0
966 """
967 warnings.warn(
968 "'get_token_status' is deprecated - use check_and_get_token_status instead",
969 DeprecationWarning,
970 stacklevel=2,
971 )
972 serializer = getattr(_security, serializer + "_serializer")
973 max_age = get_max_age(max_age)
974 user, data = None, None
975 expired, invalid = False, False
976
977 try:
978 data = serializer.loads(token, max_age=max_age)
979 except SignatureExpired:
980 d, data = serializer.loads_unsafe(token)
981 expired = True
982 except (BadSignature, TypeError, ValueError):
983 invalid = True
984
985 if data:
986 user = _datastore.find_user(fs_uniquifier=data[0])
987
988 expired = expired and (user is not None)
989
990 if return_data:
991 return expired, invalid, user, data
992 else:
993 return expired, invalid, user
994
995
996 def check_and_get_token_status(
997 token: str, serializer_name: str, within: timedelta
998 ) -> tuple[bool, bool, t.Any]:
999 """Get the status of a token and return data.
1000
1001 :param token: The token to check
1002 :param serializer_name: The name of the serializer. Can be one of the
1003 following: ``confirm``, ``login``, ``reset``, ``us_setup``
1004 ``remember``, ``two_factor_validity``, ``wan``
1005 :param within: max age - passed as a timedelta
1006
1007 :return: a tuple of (expired, invalid, data)
1008
1009 .. versionadded:: 3.4.0
1010 """
1011 serializer = getattr(_security, serializer_name + "_serializer")
1012 max_age = within.total_seconds()
1013 data = None
1014 expired, invalid = False, False
1015
1016 try:
1017 data = serializer.loads(token, max_age=max_age)
1018 except SignatureExpired:
1019 d, data = serializer.loads_unsafe(token)
1020 expired = True
1021 except (BadSignature, TypeError, ValueError):
1022 invalid = True
1023
1024 return expired, invalid, data
1025
1026
1027 def get_identity_attributes(app: Flask | None = None) -> list[str]:
1028 # Return list of keys of identity attributes
1029 # Is it possible to not have any?
1030 app = app or current_app
1031 iattrs = app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"]
1032 if iattrs:
1033 return [[*f][0] for f in iattrs]
1034 return []
1035
1036
1037 def get_identity_attribute(attr: str, app: Flask | None = None) -> dict[str, t.Any]:
1038 """Given a user_identity_attribute, return the defining dict.
1039 A bit annoying since USER_IDENTITY_ATTRIBUTES is a list of dict
1040 where each dict has just one key.
1041 """
1042 app = app or current_app
1043 iattrs = app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"]
1044 if iattrs:
1045 details = [
1046 mapping[attr] for mapping in iattrs if list(mapping.keys())[0] == attr
1047 ]
1048 if details:
1049 return details[0]
1050 return {}
1051
1052
1053 def lookup_identity(identity):
1054 """
1055 Lookup identity in DB.
1056 This loops through, in order, :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`,
1057 and first calls the mapper function to normalize.
1058 Then the db.find_user is called on the specified user model attribute.
1059 """
1060 for mapping in config_value("USER_IDENTITY_ATTRIBUTES"):
1061 attr = list(mapping.keys())[0]
1062 details = mapping[attr]
1063 idata = details["mapper"](identity)
1064 if idata:
1065 user = _datastore.find_user(
1066 case_insensitive=details.get("case_insensitive", False), **{attr: idata}
1067 )
1068 return user
1069 return None
1070
1071
1072 def uia_phone_mapper(identity: str) -> str | None:
1073 """Used to normalize a phone number. This is a simple proxy
1074 to :py:meth:`PhoneUtil.get_canonical_form`
1075
1076 See :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`.
1077
1078 .. versionadded:: 3.4.0
1079 """
1080 ph = _security.phone_util.get_canonical_form(identity)
1081 return ph
1082
1083
1084 def uia_email_mapper(identity: str) -> str | None:
1085 """Used to normalize identity as an email.
1086 This is a simple proxy
1087 to :py:meth:`MailUtil.normalize`
1088
1089 :return: Normalized email or None if not valid email.
1090
1091 See :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`.
1092
1093 .. versionadded:: 3.4.0
1094 """
1095
1096 try:
1097 return _security.mail_util.normalize(identity)
1098 except ValueError:
1099 return None
1100
1101
1102 def uia_username_mapper(identity: str) -> str | None:
1103 """Used to normalize a username. This is a simple proxy
1104 to :py:meth:`UsernameUtil.normalize`
1105
1106 See :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`.
1107
1108 .. versionadded:: 4.1.0
1109 """
1110 return _security.username_util.normalize(identity)
1111
1112
1113 def use_double_hash(password_hash=None):
1114 """Return a bool indicating whether a password should be hashed twice."""
1115 # Default to plaintext for backward compatibility with
1116 # :py:data:`SECURITY_PASSWORD_SINGLE_HASH` = False
1117 single_hash = config_value("PASSWORD_SINGLE_HASH") or {"plaintext"}
1118
1119 if password_hash is None:
1120 scheme = config_value("PASSWORD_HASH")
1121 else:
1122 scheme = _pwd_context.identify(password_hash)
1123
1124 return not (single_hash is True or scheme in single_hash)
1125
1126
1127 def csrf_cookie_handler(response: Response) -> Response:
1128 """Called at end of every request.
1129 Uses session to track state (set/clear)
1130
1131 Ideally we just need to set this once - however by default
1132 Flask-WTF has a time-out on these tokens governed by *WTF_CSRF_TIME_LIMIT*.
1133 While we could set that to None - and OWASP implies this is fine - that might
1134 not be agreeable to everyone.
1135 So as a basic usability hack - we check if it is expired and re-generate so at least
1136 the user doesn't have to log out and back in (just refresh).
1137 We also support a *CSRF_COOKIE_REFRESH_EACH_REQUEST* analogous to Flask's
1138 *SESSION_REFRESH_EACH_REQUEST*
1139
1140 It is of course removed on logout/session end.
1141 Other info on web suggests replacing on every POST and accepting up to 'age' ago.
1142 """
1143 csrf_cookie = config_value("CSRF_COOKIE")
1144 csrf_cookie_name = config_value("CSRF_COOKIE_NAME")
1145 if not csrf_cookie_name:
1146 return response
1147
1148 op = session.get("fs_cc", None)
1149 if not op:
1150 remember_cookie_name = current_app.config.get(
1151 "REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME
1152 )
1153 has_remember_cookie = (
1154 remember_cookie_name in request.cookies
1155 and session.get("remember") != "clear"
1156 )
1157 # Set cookie if successfully logged in with flask_login's remember cookie
1158 if has_remember_cookie and is_user_authenticated(current_user):
1159 op = "set"
1160 else:
1161 return response
1162
1163 if op == "clear":
1164 # Alas delete_cookie only accepts some of the keywords set_cookie does
1165 allowed = ["path", "domain", "secure", "httponly", "samesite"]
1166 args = {k: csrf_cookie.get(k) for k in allowed if k in csrf_cookie}
1167 response.delete_cookie(csrf_cookie_name, **args)
1168 session.pop("fs_cc")
1169 return response
1170
1171 # Send a cookie if any of:
1172 # 1) CSRF_COOKIE_REFRESH_EACH_REQUEST is true
1173 # 2) fs_cc == "set" - this is on first login
1174 # 3) existing cookie has expired
1175 send = False
1176 if op == "set":
1177 send = True
1178 session["fs_cc"] = "sent"
1179 elif config_value("CSRF_COOKIE_REFRESH_EACH_REQUEST"):
1180 send = True
1181 elif current_app.config["WTF_CSRF_TIME_LIMIT"]:
1182 current_cookie = request.cookies.get(csrf_cookie_name, None)
1183 if current_cookie:
1184 # Let's make sure it isn't expired if app doesn't set TIME_LIMIT to None.
1185 try:
1186 csrf.validate_csrf(current_cookie)
1187 except ValidationError:
1188 send = True
1189
1190 if send:
1191 response.set_cookie(csrf_cookie_name, value=csrf.generate_csrf(), **csrf_cookie)
1192 return response
1193
1194
1195 def add_cache_control(resp: Response) -> Response:
1196 """Add cache control header attributes to response."""
1197 cc = config_value("CACHE_CONTROL") or dict()
1198 for attr, v in cc.items():
1199 resp.cache_control[attr] = v
1200 return resp
1201
1202
1203 def base_render_json(
1204 form: FlaskForm,
1205 include_user: bool = True,
1206 include_auth_token: bool = False,
1207 additional: dict[str, t.Any] | None = None,
1208 error_status_code: int = 400,
1209 ) -> ResponseValue:
1210 """
1211 This method is called by all views that return JSON responses.
1212 This fills in the response and then calls :meth:`.Security.render_json`
1213 which can be overridden by the app.
1214 """
1215 user = getattr(form, "user", None)
1216 if form.errors:
1217 code = error_status_code
1218 # wtforms 3.0 introduces form-level errors - these show up as part of the
1219 # errors dict with a key of 'None'
1220 payload = json_error_response(field_errors=form.errors)
1221 else:
1222 code = 200
1223 payload = dict()
1224 if user:
1225 # This allows anonymous GETs via JSON
1226 if include_user:
1227 payload["user"] = user.get_security_payload()
1228
1229 if include_auth_token:
1230 # view willing to return auth_token - check behavior config
1231 if (
1232 config_value("BACKWARDS_COMPAT_AUTH_TOKEN")
1233 or "include_auth_token" in request.args
1234 ):
1235 try:
1236 token = user.get_auth_token()
1237 except ValueError:
1238 # application has fs_token_uniquifier attribute but it
1239 # hasn't been initialized. Since we are in a request context
1240 # we can do that here.
1241 _datastore.set_token_uniquifier(user)
1242 after_this_request(view_commit)
1243 token = user.get_auth_token()
1244 payload["user"]["authentication_token"] = token
1245
1246 # Return csrf_token on each JSON response - just as every form
1247 # has it rendered.
1248 payload["csrf_token"] = csrf.generate_csrf()
1249 if additional:
1250 payload.update(additional)
1251
1252 return _security._render_json(payload, code, None, user)
1253
1254
1255 def simple_render_json(
1256 additional: dict[str, t.Any] | None = None,
1257 ) -> ResponseValue:
1258 payload = dict(csrf_token=csrf.generate_csrf())
1259 if additional:
1260 payload.update(additional)
1261 return _security._render_json(payload, 200, None, None)
1262
1263
1264 def default_want_json(req):
1265 """Return True if response should be in json
1266 N.B. do not call this directly - use security._want_json()
1267
1268 :param req: Flask/Werkzeug Request
1269 """
1270 if req.is_json:
1271 return True
1272 # TODO should this handle json sub-types?
1273 accept_mimetypes = req.accept_mimetypes
1274 if not hasattr(req.accept_mimetypes, "best"): # pragma: no cover
1275 # Alright. we don't have the best property, lets add it ourselves.
1276 # This is for quart compatibility
1277 accept_mimetypes.best = best
1278 if accept_mimetypes.best == "application/json":
1279 return True
1280 return False
1281
1282
1283 def json_error_response(
1284 errors: str | list | None = None,
1285 field_errors: dict[str | None, list] | None = None,
1286 ) -> dict[str, t.Any]:
1287 """Helper to create an error response.
1288
1289 The "errors" key holds a simple list of errors - which is made up of any passed
1290 errors (either a string or list) as well as the (localized) error msgs from the
1291 passed in field_errors.
1292
1293 The "field_errors" key which is exactly what is returned from WTForms - namely
1294 a dict of field-name: msg. For form-level errors (WTForms 3.0) the 'field-name' is
1295 None - which alas means it isn't sortable and Flask's default JSONProvider
1296 sorts keys - so we change that to '__all__' which is what django uses
1297 apparently and was suggested as part of WTForms 3.0.
1298 """
1299 response_json: dict[str, list | dict[str, list]] = dict()
1300 plain_errors = []
1301 if errors:
1302 if isinstance(errors, str):
1303 plain_errors = [errors]
1304 elif isinstance(errors, list):
1305 plain_errors = errors
1306 else:
1307 raise TypeError("The errors argument should be either a str or list.")
1308 if field_errors:
1309 # This is default from WTForms - a dictionary of field name and list of errors
1310 # we return that, as well as create a simple list of errors.
1311 for e in field_errors.values():
1312 plain_errors.extend(e)
1313 if None in field_errors.keys():
1314 # Ugh - wtforms decided to use None as a key - which json
1315 # a) can't sort
1316 # b) converts to "null"
1317 # Issue filed - maybe they will change it
1318 field_errors[""] = field_errors[None]
1319 del field_errors[None]
1320 response_json["field_errors"] = field_errors # type: ignore
1321 response_json["errors"] = plain_errors
1322
1323 return response_json
1324
1325
1326 def default_render_template(*args: t.Any, **kwargs: t.Any) -> str:
1327 return render_template(*args, **kwargs)
1328
1329
1330 class SmsSenderBaseClass(metaclass=abc.ABCMeta):
1331 @abc.abstractmethod
1332 def send_sms(
1333 self, from_number: str, to_number: str, msg: str
1334 ) -> None: # pragma: no cover
1335 """Abstract method for sending sms messages
1336
1337 .. versionadded:: 3.2.0
1338 """
1339 return
1340
1341
1342 class DummySmsSender(SmsSenderBaseClass):
1343 def send_sms(
1344 self, from_number: str, to_number: str, msg: str
1345 ) -> None: # pragma: no cover
1346 """Do nothing."""
1347 return None
1348
1349
1350 class SmsSenderFactory:
1351 senders: dict[str, t.Type[SmsSenderBaseClass]] = {"Dummy": DummySmsSender}
1352
1353 @classmethod
1354 def createSender(cls, name, *args, **kwargs):
1355 """Initialize an SMS sender.
1356
1357 :param name: Name as registered in SmsSenderFactory:senders (e.g. 'Twilio')
1358
1359 .. versionadded:: 3.2.0
1360 """
1361 return cls.senders[name](*args, **kwargs)
1362
1363
1364 try: # pragma: no cover
1365 from twilio.rest import Client
1366
1367 class TwilioSmsSender(SmsSenderBaseClass):
1368 def __init__(self):
1369 super().__init__()
1370 self.account_sid = config_value("SMS_SERVICE_CONFIG")["ACCOUNT_SID"]
1371 self.auth_token = config_value("SMS_SERVICE_CONFIG")["AUTH_TOKEN"]
1372
1373 def send_sms(self, from_number: str, to_number: str, msg: str) -> None:
1374 """Send message via twilio account."""
1375 client = Client(self.account_sid, self.auth_token)
1376 client.messages.create(to=to_number, from_=from_number, body=msg)
1377
1378 SmsSenderFactory.senders["Twilio"] = TwilioSmsSender
1379 except Exception:
1380 pass
1381
1382
1383 def password_length_validator(password: str) -> list[str] | None:
1384 """Test password for length.
1385
1386 :param password: Plain text password to check
1387
1388 :return: ``None`` if password conforms to length requirements,
1389 a list of error/suggestions if not.
1390
1391 .. versionadded:: 3.4.0
1392
1393 """
1394 if len(password) < config_value("PASSWORD_LENGTH_MIN") or len(password) > 128:
1395 return [
1396 get_message(
1397 "PASSWORD_INVALID_LENGTH", length=config_value("PASSWORD_LENGTH_MIN")
1398 )[0]
1399 ]
1400 return None
1401
1402
1403 def password_complexity_validator(
1404 password: str, is_register: bool, **kwargs: t.Any
1405 ) -> list[str] | None:
1406 """Test password for complexity.
1407
1408 Currently just supports 'zxcvbn'.
1409
1410 :param password: Plain text password to check
1411 :param is_register: if True then kwargs are arbitrary additional info. (e.g.
1412 info from a registration form). If False, must be a SINGLE key "user" that
1413 corresponds to the current_user. All string values will be extracted and
1414 sent to the complexity checker.
1415 :param kwargs:
1416
1417 :return: ``None`` if password is complex enough, a list of error/suggestions if not.
1418 Be aware that zxcvbn does not (easily) provide a way to localize messages.
1419
1420 .. versionadded:: 3.4.0
1421 """
1422
1423 if config_value("PASSWORD_COMPLEXITY_CHECKER") == "zxcvbn":
1424 import zxcvbn
1425
1426 user_info: list[t.Any] = []
1427 if not is_register:
1428 for v in kwargs["user"].__dict__.values():
1429 if v and isinstance(v, str):
1430 user_info.append(v)
1431 else:
1432 # This is usually all register form values that are in the user_model
1433 if kwargs:
1434 user_info = list(kwargs.values())
1435 results = zxcvbn.zxcvbn(password, user_inputs=user_info)
1436 if results["score"] >= config_value("ZXCVBN_MINIMUM_SCORE"):
1437 return None
1438 # Should we return suggestions? Default forms don't really know what to do.
1439 if results["feedback"]["warning"]:
1440 # Note that these come from zxcvbn and
1441 # aren't localizable via Flask-Security
1442 return [results["feedback"]["warning"]]
1443 return [get_message("PASSWORD_TOO_SIMPLE")[0]]
1444 else:
1445 return None
1446
1447
1448 def password_breached_validator(password: str) -> list[str] | None:
1449 """Check if password on breached list.
1450 Does nothing unless :py:data:`SECURITY_PASSWORD_CHECK_BREACHED` is set.
1451 If password is found on the breached list, return an error if the count is
1452 greater than or equal to :py:data:`SECURITY_PASSWORD_BREACHED_COUNT`.
1453 Uses :meth:`pwned`.
1454
1455 :param password: Plain text password to check
1456
1457 :return: ``None`` if password passes breached tests, else a list of error messages.
1458
1459 .. versionadded:: 3.4.0
1460 """
1461 if pwn := config_value("PASSWORD_CHECK_BREACHED"):
1462 try:
1463 cnt = pwned(password)
1464 if cnt >= config_value("PASSWORD_BREACHED_COUNT"):
1465 return [get_message("PASSWORD_BREACHED")[0]]
1466 except Exception:
1467 if pwn == "strict":
1468 return [get_message("PASSWORD_BREACHED_SITE_ERROR")[0]]
1469 return None
1470
1471
1472 def pwned(password: str) -> int:
1473 """
1474 Check password against pwnedpasswords API using k-Anonymity.
1475 https://haveibeenpwned.com/API/v3
1476
1477 :return: Count of password in DB (0 means hasn't been compromised)
1478
1479 Can raise HTTPError
1480
1481 .. versionadded:: 3.4.0
1482 """
1483
1484 def convert_password_tuple(value):
1485 hash_suffix, count = value.split(":")
1486 return hash_suffix, int(count)
1487
1488 sha1 = hashlib.sha1(password.encode("utf8")).hexdigest()
1489
1490 req = urllib.request.Request(
1491 url=f"https://api.pwnedpasswords.com/range/{sha1[:5].upper()}",
1492 headers={"User-Agent": "Flask-Security (Python)"},
1493 )
1494 # Might raise HTTPError
1495 with urllib.request.urlopen(req) as f:
1496 response = f.read()
1497
1498 raw = response.decode("utf-8-sig")
1499
1500 entries = dict(map(convert_password_tuple, raw.upper().split("\r\n")))
1501 return entries.get(sha1[5:].upper(), 0)
1502
1503
1504 def handle_already_auth(form, payload=None):
1505 """
1506 Allow already authenticated users. For GET this is useful for
1507 single-page-applications on refresh - session still active but need to
1508 access user info and csrf-token.
1509 For GET with forms - redirect to POST_LOGIN_VIEW.
1510 For POST - redirects to POST_LOGIN_VIEW (forms) or returns 400 (json).
1511
1512 This does NOT use get_post_login_redirect() so that it doesn't look at
1513 'next' - which can cause infinite redirect loops
1514 (see test_basic::test_authenticated_loop)
1515
1516 While it's tempting to try to logout the current user and login the
1517 new requested user - that simply doesn't work with CSRF.
1518 """
1519 if _security._want_json(request):
1520 if request.method == "POST":
1521 payload = json_error_response(
1522 errors=get_message("ANONYMOUS_USER_REQUIRED")[0]
1523 )
1524 return _security._render_json(payload, 400, None, None)
1525 else:
1526 form.user = current_user
1527 return base_render_json(form, additional=payload)
1528 else:
1529 return redirect(get_url(config_value("POST_LOGIN_VIEW")))