Debian Codegraph @

flask_security/password_util.py

raw
1 """
2 flask_security.password_util
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Utility class providing methods for validating and normalizing passwords.
6
7 :copyright: (c) 2020-2024 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9
10 """
11
12 from __future__ import annotations
13
14 import typing as t
15 import unicodedata
16
17 from .utils import (
18 config_value,
19 password_length_validator,
20 password_breached_validator,
21 password_complexity_validator,
22 )
23
24 if t.TYPE_CHECKING: # pragma: no cover
25 import flask
26
27
28 class PasswordUtil:
29 """
30 Utility class providing methods for validating and normalizing passwords.
31
32 To provide your own implementation, pass in the class as ``password_util_cls``
33 at init time. Your class will be instantiated once as part of app initialization.
34
35 .. versionadded:: 4.0.0
36 """
37
38 def __init__(self, app: flask.Flask):
39 """Instantiate class.
40
41 :param app: The Flask application being initialized.
42 """
43 pass
44
45 def normalize(self, password: str) -> str:
46 """
47 Given an input password - return a normalized version (using Python's
48 unicodedata.normalize()).
49 Must be called in app context and uses
50 :py:data:`SECURITY_PASSWORD_NORMALIZE_FORM` config variable.
51 """
52 cf = config_value("PASSWORD_NORMALIZE_FORM")
53 if cf:
54 return unicodedata.normalize(cf, password)
55 return password
56
57 def validate(
58 self, password: str, is_register: bool, **kwargs: t.Any
59 ) -> tuple[list | None, str]:
60 """
61 Password validation.
62 Called in app/request context.
63
64 If is_register is True then kwargs will be the contents of the register form.
65 If is_register is False, then there is a single kwarg "user" which has the
66 current user data model.
67
68 The password is first normalized then validated.
69 Return value is a tuple ([msgs], normalized_password)
70 """
71
72 pnorm = self.normalize(password)
73 notok = password_length_validator(pnorm)
74 if notok:
75 return notok, pnorm
76
77 notok = password_breached_validator(pnorm)
78 if notok:
79 return notok, pnorm
80
81 return password_complexity_validator(pnorm, is_register, **kwargs), pnorm