codekingpro/portable-devtools
114k
1"""2 flask_security.password_util3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~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 12from __future__ import annotations13 14import typing as t15import unicodedata16 17from .utils import (18 config_value,19 password_length_validator,20 password_breached_validator,21 password_complexity_validator,22)23 24if t.TYPE_CHECKING: # pragma: no cover25 import flask26 27 28class 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.036 """37 38 def __init__(self, app: flask.Flask):39 """Instantiate class.40 41 :param app: The Flask application being initialized.42 """43 pass44 45 def normalize(self, password: str) -> str:46 """47 Given an input password - return a normalized version (using Python's48 unicodedata.normalize()).49 Must be called in app context and uses50 :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 password56 57 def validate(58 self, password: str, is_register: bool, **kwargs: t.Any59 ) -> 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 the66 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, pnorm76 77 notok = password_breached_validator(pnorm)78 if notok:79 return notok, pnorm80 81 return password_complexity_validator(pnorm, is_register, **kwargs), pnorm82 