Debian Codegraph @

allauth/utils.py

raw
1 from __future__ import annotations
2
3 import random
4 import re
5 import string
6 import unicodedata
7 import warnings
8 from collections import OrderedDict
9 from urllib.parse import urlsplit
10
11 from django.conf import settings
12 from django.contrib.auth import get_user_model
13 from django.core.exceptions import ImproperlyConfigured, ValidationError
14 from django.http import HttpRequest
15 from django.utils.encoding import force_str
16 from django.utils.module_loading import import_string
17
18 from allauth import app_settings
19 from allauth.core import context
20
21
22 # Magic number 7: if you run into collisions with this number, then you are
23 # of big enough scale to start investing in a decent user model...
24 MAX_USERNAME_SUFFIX_LENGTH = 7
25 USERNAME_SUFFIX_CHARS = [string.digits] * 4 + [string.ascii_letters] * (
26 MAX_USERNAME_SUFFIX_LENGTH - 4
27 )
28
29
30 def _generate_unique_username_base(txts: list[str | None], regex=None) -> str:
31 from .account.adapter import get_adapter
32
33 adapter = get_adapter()
34 username = None
35 regex = regex or r"[^\w\s@+.-]"
36 for txt in txts:
37 if not txt:
38 continue
39 username = unicodedata.normalize("NFKD", force_str(txt))
40 username = username.encode("ascii", "ignore").decode("ascii")
41 if len(username) == 0:
42 continue
43 username = force_str(re.sub(regex, "", username).lower())
44 # Django allows for '@' in usernames in order to accommodate for
45 # project wanting to use email for username. In allauth we don't
46 # use this, we already have a proper place for putting email
47 # addresses (EmailAddress), so let's not use the full email
48 # address and only take the part leading up to the '@'.
49 username = username.split("@")[0]
50 username = username.strip()
51 username = re.sub(r"\s+", "_", username)
52 # Finally, validating base username without database lookups etc.
53 try:
54 username = adapter.clean_username(username, shallow=True)
55 break
56 except ValidationError:
57 pass
58 return username or "user"
59
60
61 def get_username_max_length() -> int | None:
62 from .account.app_settings import USER_MODEL_USERNAME_FIELD
63
64 if USER_MODEL_USERNAME_FIELD is not None:
65 User = get_user_model()
66 max_length: int = User._meta.get_field(
67 USER_MODEL_USERNAME_FIELD
68 ).max_length # type:ignore[union-attr,assignment]
69 else:
70 max_length = 0
71 return max_length
72
73
74 def generate_username_candidate(basename, suffix_length) -> str:
75 max_length = get_username_max_length()
76 suffix = "".join(
77 random.choice(USERNAME_SUFFIX_CHARS[i]) for i in range(suffix_length) # nosec
78 )
79 if max_length is not None:
80 return basename[0 : max_length - len(suffix)] + suffix
81 return basename + suffix
82
83
84 def generate_username_candidates(basename) -> list:
85 from .account.app_settings import USERNAME_MIN_LENGTH
86
87 if len(basename) >= USERNAME_MIN_LENGTH:
88 ret = [basename]
89 else:
90 ret = []
91 min_suffix_length = max(1, USERNAME_MIN_LENGTH - len(basename))
92 username_max_length = get_username_max_length()
93 if username_max_length is None:
94 max_suffix_length = MAX_USERNAME_SUFFIX_LENGTH
95 else:
96 max_suffix_length = min(username_max_length, MAX_USERNAME_SUFFIX_LENGTH)
97 for suffix_length in range(min_suffix_length, max_suffix_length):
98 ret.append(generate_username_candidate(basename, suffix_length))
99 return ret
100
101
102 def generate_unique_username(txts: list[str | None], regex=None) -> str:
103 from allauth.account.utils import filter_users_by_username
104
105 from .account.adapter import get_adapter
106 from .account.app_settings import USER_MODEL_USERNAME_FIELD
107
108 adapter = get_adapter()
109 basename = _generate_unique_username_base(txts, regex)
110 candidates = generate_username_candidates(basename)
111 existing_usernames_q = filter_users_by_username(*candidates).values_list(
112 USER_MODEL_USERNAME_FIELD, flat=True
113 )
114 existing_usernames = {n.lower() for n in existing_usernames_q}
115 for candidate in candidates:
116 if candidate.lower() not in existing_usernames:
117 try:
118 return adapter.clean_username(candidate, shallow=True)
119 except ValidationError:
120 pass
121 # This really should not happen
122 raise NotImplementedError("Unable to find a unique username")
123
124
125 def import_attribute(path):
126 warnings.warn(
127 "allauth.utils.import_attribute is deprecated, use "
128 "django.utils.module_loading.import_string instead.",
129 DeprecationWarning,
130 stacklevel=2,
131 )
132 return import_string(path)
133
134
135 def import_callable(path_or_callable):
136 if not callable(path_or_callable):
137 ret = import_string(path_or_callable)
138 else:
139 ret = path_or_callable
140 return ret
141
142
143 def set_form_field_order(form, field_order) -> None:
144 """
145 This function is a verbatim copy of django.forms.Form.order_fields() to
146 support field ordering below Django 1.9.
147
148 field_order is a list of field names specifying the order. Append fields
149 not included in the list in the default order for backward compatibility
150 with subclasses not overriding field_order. If field_order is None, keep
151 all fields in the order defined in the class. Ignore unknown fields in
152 field_order to allow disabling fields in form subclasses without
153 redefining ordering.
154 """
155 if field_order is None:
156 return
157 fields = OrderedDict()
158 for key in field_order:
159 try:
160 fields[key] = form.fields.pop(key)
161 except KeyError: # ignore unknown fields
162 pass
163 fields.update(form.fields) # add remaining fields in original order
164 form.fields = fields
165
166
167 def build_absolute_uri(
168 request: HttpRequest | None, location: str, protocol: str | None = None
169 ) -> str:
170 """request.build_absolute_uri() helper
171
172 Like request.build_absolute_uri, but gracefully handling
173 the case where request is None.
174 """
175 from .account import app_settings as account_settings
176
177 if request is None:
178 request = context.request
179
180 if request is None:
181 if not app_settings.SITES_ENABLED:
182 raise ImproperlyConfigured(
183 "Passing `request=None` requires `sites` to be enabled."
184 )
185 from django.contrib.sites.models import Site
186
187 site = Site.objects.get_current()
188 bits = urlsplit(location)
189 if not (bits.scheme and bits.netloc):
190 uri = f"{account_settings.DEFAULT_HTTP_PROTOCOL}://{site.domain}{location}"
191 else:
192 uri = location
193 else:
194 uri = request.build_absolute_uri(location)
195 # NOTE: We only force a protocol if we are instructed to do so
196 # (via the `protocol` parameter, or, if the default is set to
197 # HTTPS. The latter keeps compatibility with the debatable use
198 # case of running your site under both HTTP and HTTPS, where one
199 # would want to make sure HTTPS links end up in password reset
200 # mails even while they were initiated on an HTTP password reset
201 # form.
202 if not protocol and account_settings.DEFAULT_HTTP_PROTOCOL == "https":
203 protocol = account_settings.DEFAULT_HTTP_PROTOCOL
204 # (end NOTE)
205 if protocol:
206 uri = f"{protocol}:{uri.partition(':')[2]}"
207 return uri
208
209
210 def get_form_class(forms, form_id, default_form):
211 form_class = forms.get(form_id, default_form)
212 if isinstance(form_class, str):
213 form_class = import_string(form_class)
214 return form_class
215
216
217 def get_request_param(request: HttpRequest, param, default=None):
218 if request is None:
219 return default
220 return request.POST.get(param) or request.GET.get(param, default)
221
222
223 def get_setting(name, dflt):
224 getter = getattr(
225 settings,
226 "ALLAUTH_SETTING_GETTER",
227 lambda name, dflt: getattr(settings, name, dflt),
228 )
229 getter = import_callable(getter)
230 return getter(name, dflt)