Debian Codegraph @

flask_security/phone_util.py

raw
1 """
2 flask_security.phone_util
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Utility class for managing phone numbers
6
7 :copyright: (c) 2020-2024 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9
10 Avoid making 'phonenumbers' a required package unless needed.
11 """
12
13 from __future__ import annotations
14
15 import typing as t
16
17 from .utils import _config_value, get_message
18
19 if t.TYPE_CHECKING: # pragma: no cover
20 import flask
21
22
23 class PhoneUtil:
24 """
25 Provide parsing and validation for user inputted phone numbers.
26 Subclass this to use a different underlying phone number parsing library.
27
28 To provide your own implementation, pass in the class as ``phone_util_cls``
29 at init time. Your class will be instantiated once as part of
30 Flask-Security initialization.
31
32 .. versionadded:: 3.4.0
33
34 .. versionchanged:: 4.0.0
35 __init__ takes app argument, and is instantiated at Flask-Security
36 initialization time rather than at first request.
37 """
38
39 def __init__(self, app: flask.Flask):
40 """Instantiate class.
41
42 :param app: The Flask application being initialized.
43 """
44 pass
45
46 def validate_phone_number(self, input_data: str) -> str | None:
47 """Return ``None`` if a valid phone number else
48 the ``PHONE_INVALID`` error message."""
49 import phonenumbers
50
51 try:
52 z = phonenumbers.parse(
53 input_data, region=_config_value("PHONE_REGION_DEFAULT")
54 )
55 if phonenumbers.is_valid_number(z):
56 return None
57 except phonenumbers.phonenumberutil.NumberParseException:
58 pass
59 return get_message("PHONE_INVALID")[0]
60
61 def get_canonical_form(self, input_data: str) -> str | None:
62 """Validate and return a canonical form to be stored in DB
63 and compared against.
64 Returns ``None`` if input isn't a valid phone number.
65 """
66 import phonenumbers
67
68 try:
69 z = phonenumbers.parse(
70 input_data, region=_config_value("PHONE_REGION_DEFAULT")
71 )
72 if phonenumbers.is_valid_number(z):
73 return phonenumbers.format_number(
74 z, phonenumbers.PhoneNumberFormat.E164
75 )
76 return None
77 except phonenumbers.phonenumberutil.NumberParseException:
78 return None