Debian Codegraph @

flask_security/username_util.py

raw
1 """
2 flask_security.username_util
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Utility class providing methods for validating and normalizing usernames.
6
7 :copyright: (c) 2020-2026 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
16 from .utils import (
17 _config_value as cv,
18 get_message,
19 input_svn,
20 )
21
22 if t.TYPE_CHECKING: # pragma: no cover
23 import flask
24
25
26 class UsernameUtil:
27 """
28 Utility class providing methods for validating and normalizing usernames.
29
30 To provide your own implementation, pass in the class as ``username_util_cls``
31 at init time. Your class will be instantiated once as part of app initialization.
32
33 .. versionadded:: 4.1.0
34 """
35
36 def __init__(self, app: flask.Flask):
37 """Instantiate class.
38
39 :param app: The Flask application being initialized.
40 """
41 pass
42
43 def normalize(self, username: str) -> str | None:
44 """
45 Given an input username - return a clean (using nh3) and normalized
46 (using Python's unicodedata.normalize()) version.
47 Must be called in app context and uses
48 :py:data:`SECURITY_INPUT_NORMALIZE_FORM` and
49 :py:data:`SECURITY_USERNAME_ALLOWED_CHARS` config variables.
50 """
51 reason, clean_input = input_svn(
52 username, cv("USERNAME_ALLOWED_CHARS"), cv("INPUT_NORMALIZE_FORM")
53 )
54 return clean_input
55
56 def validate(self, username: str) -> tuple[str | None, str | None]:
57 """
58 Username validation.
59 Called in app/request context.
60
61 The username is first validated then normalized.
62 Return value is a tuple (msg, normalized_username). msg will be None if
63 properly validated.
64
65 It is important that None be returned if data is an empty string since
66 otherwise DBs will complain since the field is unique/nullable.
67 """
68 if not username:
69 return None, None
70 reason, clean_input = input_svn(
71 username, cv("USERNAME_ALLOWED_CHARS"), cv("INPUT_NORMALIZE_FORM")
72 )
73 if clean_input is None:
74 msg = (
75 "USERNAME_DISALLOWED_CHARACTERS"
76 if reason == "unallowed"
77 else "INVALID_INPUT"
78 )
79 return get_message(msg)[0], None
80 umin = cv("USERNAME_MIN_LENGTH")
81 umax = cv("USERNAME_MAX_LENGTH")
82 if len(clean_input) < umin or len(clean_input) > umax:
83 return (
84 get_message("USERNAME_INVALID_LENGTH", min=umin, max=umax)[0],
85 clean_input,
86 )
87 return None, clean_input