Debian Codegraph @

allauth/account/app_settings.py

raw
1 from __future__ import annotations
2
3 import warnings
4 from enum import Enum
5 from typing import Literal, TypeVar
6
7 from allauth import app_settings as allauth_settings
8 from allauth.core.internal.cryptokit import UserCodeFormat
9
10
11 _T = TypeVar("_T")
12
13
14 class AppSettings:
15 class AuthenticationMethod(str, Enum):
16 USERNAME = "username"
17 EMAIL = "email"
18 USERNAME_EMAIL = "username_email"
19
20 class LoginMethod(str, Enum):
21 USERNAME = "username"
22 EMAIL = "email"
23 PHONE = "phone"
24
25 class EmailVerificationMethod(str, Enum):
26 # After signing up, keep the user account inactive until the email
27 # address is verified
28 MANDATORY = "mandatory"
29 # Allow login with unverified email (email verification is
30 # still sent)
31 OPTIONAL = "optional"
32 # Don't send email verification mails during signup
33 NONE = "none"
34
35 def __init__(self, prefix) -> None:
36 self.prefix = prefix
37
38 def _setting(self, name: str, dflt: _T) -> _T:
39 from allauth.utils import get_setting
40
41 return get_setting(self.prefix + name, dflt)
42
43 @property
44 def PREVENT_ENUMERATION(self) -> bool | Literal["strict"]:
45 return self._setting("PREVENT_ENUMERATION", True)
46
47 @property
48 def DEFAULT_HTTP_PROTOCOL(self) -> str:
49 return self._setting("DEFAULT_HTTP_PROTOCOL", "http").lower()
50
51 @property
52 def EMAIL_CONFIRMATION_EXPIRE_DAYS(self) -> int:
53 """
54 Determines the expiration date of email confirmation mails (#
55 of days)
56 """
57 from django.conf import settings
58
59 return self._setting(
60 "EMAIL_CONFIRMATION_EXPIRE_DAYS",
61 getattr(settings, "EMAIL_CONFIRMATION_DAYS", 3),
62 )
63
64 @property
65 def EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL(self) -> str | None:
66 """
67 The URL to redirect to after a successful email confirmation, in
68 case of an authenticated user
69 """
70 return self._setting("EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL", None)
71
72 @property
73 def EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL(self) -> str:
74 """
75 The URL to redirect to after a successful email confirmation, in
76 case no user is logged in
77 """
78 from django.conf import settings
79
80 return self._setting(
81 "EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL", settings.LOGIN_URL
82 )
83
84 @property
85 def EMAIL_REQUIRED(self):
86 """
87 The user is required to hand over an email address when signing up
88 """
89 warnings.warn(
90 "app_settings.EMAIL_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['email']['required']",
91 stacklevel=3,
92 )
93 email = self.SIGNUP_FIELDS.get("email")
94 return email and email["required"]
95
96 @property
97 def EMAIL_VERIFICATION(self):
98 """
99 See email verification method
100 """
101 ret = self._setting("EMAIL_VERIFICATION", self.EmailVerificationMethod.OPTIONAL)
102 # Deal with legacy (boolean based) setting
103 if ret is True:
104 ret = self.EmailVerificationMethod.MANDATORY
105 elif ret is False:
106 ret = self.EmailVerificationMethod.OPTIONAL
107 return self.EmailVerificationMethod(ret)
108
109 @property
110 def EMAIL_VERIFICATION_BY_CODE_ENABLED(self) -> bool:
111 return self._setting("EMAIL_VERIFICATION_BY_CODE_ENABLED", False)
112
113 @property
114 def EMAIL_VERIFICATION_BY_CODE_MAX_ATTEMPTS(self) -> int:
115 return self._setting("EMAIL_VERIFICATION_BY_CODE_MAX_ATTEMPTS", 3)
116
117 @property
118 def EMAIL_VERIFICATION_BY_CODE_TIMEOUT(self) -> int:
119 return self._setting("EMAIL_VERIFICATION_BY_CODE_TIMEOUT", 15 * 60)
120
121 @property
122 def EMAIL_VERIFICATION_MAX_CHANGE_COUNT(self) -> int:
123 """
124 The maximum number of times the email can be changed after signup at
125 the email veriication stage.
126 """
127 v: bool | int = self._setting("EMAIL_VERIFICATION_SUPPORTS_CHANGE", False)
128 if isinstance(v, bool):
129 v = 2 if v else 0
130 return v
131
132 @property
133 def EMAIL_VERIFICATION_MAX_RESEND_COUNT(self) -> int:
134 """
135 The maximum number of times the user can request a new email verification code.
136 """
137 v: bool | int = self._setting("EMAIL_VERIFICATION_SUPPORTS_RESEND", False)
138 if isinstance(v, bool):
139 v = 2 if v else 0
140 return v
141
142 @property
143 def MAX_EMAIL_ADDRESSES(self) -> int | None:
144 return self._setting("MAX_EMAIL_ADDRESSES", None)
145
146 @property
147 def CHANGE_EMAIL(self) -> bool:
148 return self._setting("CHANGE_EMAIL", False)
149
150 @property
151 def AUTHENTICATION_METHOD(self):
152 warnings.warn(
153 "app_settings.AUTHENTICATION_METHOD is deprecated, use: app_settings.LOGIN_METHODS",
154 stacklevel=3,
155 )
156 methods = self.LOGIN_METHODS
157 if self.LoginMethod.EMAIL in methods and self.LoginMethod.USERNAME in methods:
158 return "username_email"
159 elif self.LoginMethod.EMAIL in methods:
160 return "email"
161 elif self.LoginMethod.USERNAME in methods:
162 return "username"
163 else:
164 raise NotADirectoryError
165
166 @property
167 def LOGIN_METHODS(self) -> frozenset[LoginMethod]:
168 methods = self._setting("LOGIN_METHODS", None)
169 if methods is None:
170 auth_method = self._setting(
171 "AUTHENTICATION_METHOD", self.AuthenticationMethod.USERNAME
172 )
173 if auth_method == self.AuthenticationMethod.USERNAME_EMAIL:
174 methods = {self.LoginMethod.EMAIL, self.LoginMethod.USERNAME}
175 else:
176 methods = {self.LoginMethod(auth_method)}
177 return frozenset([self.LoginMethod(m) for m in methods])
178
179 @property
180 def EMAIL_MAX_LENGTH(self) -> int:
181 """
182 Adjust max_length of email addresses
183 """
184 return self._setting("EMAIL_MAX_LENGTH", 254)
185
186 @property
187 def PHONE_VERIFICATION_ENABLED(self) -> bool:
188 return self._setting("PHONE_VERIFICATION_ENABLED", True)
189
190 @property
191 def PHONE_VERIFICATION_MAX_ATTEMPTS(self) -> int:
192 return self._setting("PHONE_VERIFICATION_MAX_ATTEMPTS", 3)
193
194 @property
195 def PHONE_VERIFICATION_MAX_CHANGE_COUNT(self) -> int:
196 """
197 The maximum number of times the phone number can be changed after
198 signup at the phone number verification stage.
199 """
200 v: bool | int = self._setting("PHONE_VERIFICATION_SUPPORTS_CHANGE", False)
201 if isinstance(v, bool):
202 v = 2 if v else 0
203 return v
204
205 @property
206 def PHONE_VERIFICATION_MAX_RESEND_COUNT(self) -> int:
207 """
208 The maximum number of times the user can request a new phone number
209 verification code.
210 """
211 v: bool | int = self._setting("PHONE_VERIFICATION_SUPPORTS_RESEND", False)
212 if isinstance(v, bool):
213 v = 2 if v else 0
214 return v
215
216 @property
217 def PHONE_VERIFICATION_TIMEOUT(self) -> int:
218 return self._setting("PHONE_VERIFICATION_TIMEOUT", 15 * 60)
219
220 @property
221 def UNIQUE_EMAIL(self) -> bool:
222 """
223 Enforce uniqueness of email addresses
224 """
225 return self._setting("UNIQUE_EMAIL", True)
226
227 @property
228 def SIGNUP_EMAIL_ENTER_TWICE(self) -> bool:
229 """
230 Signup email verification
231 """
232 warnings.warn(
233 "app_settings.SIGNUP_EMAIL_ENTER_TWICE is deprecated, use: 'email2' in app_settings.SIGNUP_FIELDS",
234 stacklevel=3,
235 )
236 return "email2" in self.SIGNUP_FIELDS
237
238 @property
239 def SIGNUP_PASSWORD_ENTER_TWICE(self) -> bool:
240 """
241 Signup password verification
242 """
243 warnings.warn(
244 "app_settings.SIGNUP_PASSWORD_ENTER_TWICE is deprecated, use: 'password2' in app_settings.SIGNUP_FIELDS",
245 stacklevel=3,
246 )
247 return "password2" in self.SIGNUP_FIELDS
248
249 @property
250 def SIGNUP_REDIRECT_URL(self) -> str:
251 from django.conf import settings
252
253 return self._setting("SIGNUP_REDIRECT_URL", settings.LOGIN_REDIRECT_URL) # type: ignore[return-value]
254
255 @property
256 def PASSWORD_MIN_LENGTH(self) -> int | None:
257 """
258 Minimum password Length
259 """
260 from django.conf import settings
261
262 ret = None
263 if not settings.AUTH_PASSWORD_VALIDATORS:
264 ret = self._setting("PASSWORD_MIN_LENGTH", 6)
265 return ret
266
267 @property
268 def RATE_LIMITS(self) -> dict:
269 rls: dict = self._setting("RATE_LIMITS", {})
270 if rls is False:
271 return {}
272 attempts_amount = self._setting("LOGIN_ATTEMPTS_LIMIT", 5)
273 attempts_timeout = self._setting("LOGIN_ATTEMPTS_TIMEOUT", 60 * 5)
274 login_failed_rl = None
275 if attempts_amount and attempts_timeout:
276 login_failed_rl = f"10/m/ip,{attempts_amount}/{attempts_timeout}s/key"
277
278 if self.EMAIL_VERIFICATION_BY_CODE_ENABLED:
279 confirm_email_rl = "1/10s/key"
280 else:
281 cooldown = self._setting("EMAIL_CONFIRMATION_COOLDOWN", 3 * 60)
282 confirm_email_rl = None
283 if cooldown:
284 confirm_email_rl = f"1/{cooldown}s/key"
285 ret = {
286 # Change password view (for users already logged in)
287 "change_password": "5/m/user", # nosec
288 # Change phone number
289 "change_phone": "1/m/user",
290 # Email management (e.g. add, remove, change primary)
291 "manage_email": "10/m/user",
292 # Request a password reset, global rate limit per IP
293 "reset_password": "20/m/ip,5/m/key",
294 # Reauthentication for users already logged in
295 "reauthenticate": "10/m/user",
296 # Password reset (the view the password reset email links to).
297 "reset_password_from_key": "20/m/ip",
298 # Signups.
299 "signup": "20/m/ip",
300 # Logins.
301 "login": "30/m/ip",
302 # Request a login code: key is the email.
303 "request_login_code": "20/m/ip,3/m/key",
304 # Logins.
305 "login_failed": login_failed_rl,
306 # Verify email (to be renamed to verify_email)
307 "confirm_email": confirm_email_rl,
308 # Verify phone
309 "verify_phone": "1/30s/key,3/m/ip",
310 }
311 ret.update(rls)
312 return ret
313
314 @property
315 def EMAIL_SUBJECT_PREFIX(self) -> str | None:
316 """
317 Subject-line prefix to use for email messages sent
318 """
319 return self._setting("EMAIL_SUBJECT_PREFIX", None)
320
321 @property
322 def SIGNUP_FORM_CLASS(self) -> str | None:
323 """
324 Signup form
325 """
326 return self._setting("SIGNUP_FORM_CLASS", None)
327
328 @property
329 def SIGNUP_FORM_HONEYPOT_FIELD(self) -> str | None:
330 """
331 Honeypot field name. Empty string or ``None`` will disable honeypot behavior.
332 """
333 return self._setting("SIGNUP_FORM_HONEYPOT_FIELD", None)
334
335 @property
336 def SIGNUP_FIELDS(self) -> dict:
337 fields: list | None = self._setting("SIGNUP_FIELDS", None)
338 if not fields:
339 fields = []
340 username = self._setting("USERNAME_REQUIRED", True)
341 email = self._setting("EMAIL_REQUIRED", False)
342 email2 = self._setting("SIGNUP_EMAIL_ENTER_TWICE", False)
343 password2 = self._setting(
344 "SIGNUP_PASSWORD_ENTER_TWICE",
345 self._setting("SIGNUP_PASSWORD_VERIFICATION", True),
346 )
347 if email:
348 fields.append("email*")
349 else:
350 fields.append("email")
351 if email2:
352 fields.append("email2*" if email else "email2")
353 if username:
354 fields.append("username*")
355 fields.append("password1*")
356 if password2:
357 fields.append("password2*")
358 ret = {}
359 for field in fields:
360 f, req, _ = field.partition("*")
361 ret[f] = {"required": bool(req)}
362 return ret
363
364 @property
365 def USERNAME_REQUIRED(self) -> bool:
366 """
367 The user is required to enter a username when signing up
368 """
369 warnings.warn(
370 "app_settings.USERNAME_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['username']['required']",
371 stacklevel=3,
372 )
373 username = self.SIGNUP_FIELDS.get("username")
374 return bool(username and username["required"])
375
376 @property
377 def USERNAME_MIN_LENGTH(self) -> int:
378 """
379 Minimum username Length
380 """
381 return self._setting("USERNAME_MIN_LENGTH", 1)
382
383 @property
384 def USERNAME_BLACKLIST(self) -> list[str]:
385 """
386 List of usernames that are not allowed
387 """
388 return self._setting("USERNAME_BLACKLIST", [])
389
390 @property
391 def PASSWORD_INPUT_RENDER_VALUE(self) -> bool:
392 """
393 render_value parameter as passed to PasswordInput fields
394 """
395 return self._setting("PASSWORD_INPUT_RENDER_VALUE", False)
396
397 @property
398 def ADAPTER(self) -> str:
399 return self._setting("ADAPTER", "allauth.account.adapter.DefaultAccountAdapter")
400
401 @property
402 def CONFIRM_EMAIL_ON_GET(self) -> bool:
403 return self._setting("CONFIRM_EMAIL_ON_GET", False)
404
405 @property
406 def AUTHENTICATED_LOGIN_REDIRECTS(self) -> bool:
407 return self._setting("AUTHENTICATED_LOGIN_REDIRECTS", True)
408
409 @property
410 def LOGIN_ON_EMAIL_CONFIRMATION(self) -> bool:
411 """
412 Automatically log the user in once they confirmed their email address
413 """
414 return self._setting("LOGIN_ON_EMAIL_CONFIRMATION", False)
415
416 @property
417 def LOGIN_ON_PASSWORD_RESET(self) -> bool:
418 """
419 Automatically log the user in immediately after resetting
420 their password.
421 """
422 return self._setting("LOGIN_ON_PASSWORD_RESET", False)
423
424 @property
425 def LOGOUT_REDIRECT_URL(self) -> str:
426 from django.conf import settings
427
428 return self._setting("LOGOUT_REDIRECT_URL", settings.LOGOUT_REDIRECT_URL or "/") # type: ignore[return-value]
429
430 @property
431 def LOGOUT_ON_GET(self) -> bool:
432 return self._setting("LOGOUT_ON_GET", False)
433
434 @property
435 def LOGOUT_ON_PASSWORD_CHANGE(self) -> bool:
436 return self._setting("LOGOUT_ON_PASSWORD_CHANGE", False)
437
438 @property
439 def USER_MODEL_USERNAME_FIELD(self) -> str | None:
440 return self._setting("USER_MODEL_USERNAME_FIELD", "username")
441
442 @property
443 def USER_MODEL_EMAIL_FIELD(self) -> str | None:
444 return self._setting("USER_MODEL_EMAIL_FIELD", "email")
445
446 @property
447 def SESSION_COOKIE_AGE(self) -> int:
448 """
449 Deprecated -- use Django's settings.SESSION_COOKIE_AGE instead
450 """
451 from django.conf import settings
452
453 return self._setting("SESSION_COOKIE_AGE", settings.SESSION_COOKIE_AGE)
454
455 @property
456 def SESSION_REMEMBER(self) -> bool | None:
457 """
458 Controls the life time of the session. Set to `None` to ask the user
459 ("Remember me?"), `False` to not remember, and `True` to always
460 remember.
461 """
462 return self._setting("SESSION_REMEMBER", None)
463
464 @property
465 def TEMPLATE_EXTENSION(self) -> str:
466 """
467 A string defining the template extension to use, defaults to `html`.
468 """
469 return self._setting("TEMPLATE_EXTENSION", "html")
470
471 @property
472 def FORMS(self) -> dict:
473 return self._setting("FORMS", {})
474
475 @property
476 def EMAIL_CONFIRMATION_HMAC(self) -> bool:
477 return self._setting("EMAIL_CONFIRMATION_HMAC", True)
478
479 @property
480 def SALT(self) -> str:
481 return self._setting("SALT", "account")
482
483 @property
484 def PRESERVE_USERNAME_CASING(self) -> bool:
485 return self._setting("PRESERVE_USERNAME_CASING", True)
486
487 @property
488 def USERNAME_VALIDATORS(self):
489 from django.contrib.auth import get_user_model
490 from django.core.exceptions import ImproperlyConfigured
491 from django.utils.module_loading import import_string
492
493 path = self._setting("USERNAME_VALIDATORS", None)
494 if path:
495 ret = import_string(path)
496 if not isinstance(ret, list):
497 raise ImproperlyConfigured(
498 "ACCOUNT_USERNAME_VALIDATORS is expected to be a list"
499 )
500 else:
501 if self.USER_MODEL_USERNAME_FIELD is not None:
502 ret = (
503 get_user_model()
504 ._meta.get_field(self.USER_MODEL_USERNAME_FIELD)
505 .validators
506 )
507 else:
508 ret = []
509 return ret
510
511 @property
512 def PASSWORD_RESET_BY_CODE_ENABLED(self) -> bool:
513 return self._setting("PASSWORD_RESET_BY_CODE_ENABLED", False)
514
515 @property
516 def PASSWORD_RESET_BY_CODE_MAX_ATTEMPTS(self) -> int:
517 return self._setting("PASSWORD_RESET_BY_CODE_MAX_ATTEMPTS", 3)
518
519 @property
520 def PASSWORD_RESET_BY_CODE_TIMEOUT(self) -> int:
521 return self._setting("PASSWORD_RESET_BY_CODE_TIMEOUT", 3 * 60)
522
523 @property
524 def PASSWORD_RESET_TOKEN_GENERATOR(self):
525 from django.utils.module_loading import import_string
526
527 from allauth.account.forms import EmailAwarePasswordResetTokenGenerator
528
529 token_generator_path = self._setting("PASSWORD_RESET_TOKEN_GENERATOR", None)
530 if token_generator_path is not None:
531 token_generator = import_string(token_generator_path)
532 else:
533 token_generator = EmailAwarePasswordResetTokenGenerator
534 return token_generator
535
536 @property
537 def EMAIL_UNKNOWN_ACCOUNTS(self) -> bool:
538 return self._setting("EMAIL_UNKNOWN_ACCOUNTS", True)
539
540 @property
541 def REAUTHENTICATION_TIMEOUT(self) -> int:
542 return self._setting("REAUTHENTICATION_TIMEOUT", 300)
543
544 @property
545 def EMAIL_NOTIFICATIONS(self) -> bool:
546 return self._setting("EMAIL_NOTIFICATIONS", False)
547
548 @property
549 def REAUTHENTICATION_REQUIRED(self) -> bool:
550 return self._setting("REAUTHENTICATION_REQUIRED", False)
551
552 @property
553 def LOGIN_BY_CODE_ENABLED(self) -> bool:
554 return self._setting("LOGIN_BY_CODE_ENABLED", False)
555
556 @property
557 def LOGIN_BY_CODE_TRUST_ENABLED(self) -> bool:
558 return self._setting("LOGIN_BY_CODE_TRUST_ENABLED", False)
559
560 @property
561 def LOGIN_BY_CODE_MAX_ATTEMPTS(self) -> int:
562 return self._setting("LOGIN_BY_CODE_MAX_ATTEMPTS", 3)
563
564 @property
565 def LOGIN_BY_CODE_MAX_RESEND_COUNT(self) -> int:
566 """
567 The maximum number of times the user can request a new login code.
568 """
569 v: bool | int = self._setting("LOGIN_BY_CODE_SUPPORTS_RESEND", False)
570 if isinstance(v, bool):
571 v = 2 if v else 0
572 return v
573
574 @property
575 def LOGIN_BY_CODE_TIMEOUT(self) -> int:
576 return self._setting("LOGIN_BY_CODE_TIMEOUT", 3 * 60)
577
578 @property
579 def LOGIN_TIMEOUT(self) -> int:
580 """
581 The maximum allowed time (in seconds) for a login to go through the
582 various login stages. This limits, for example, the time span that the
583 2FA stage remains available.
584 """
585 return self._setting("LOGIN_TIMEOUT", 15 * 60)
586
587 @property
588 def LOGIN_BY_CODE_REQUIRED(self) -> bool | set[str]:
589 """
590 When enabled (in case of ``True``), every user logging in is
591 required to input a login confirmation code sent by email.
592 Alternatively, you can specify a set of authentication methods
593 (``"password"``, ``"mfa"``, or ``"socialaccount"``) for which login
594 codes are required.
595 """
596 value = self._setting("LOGIN_BY_CODE_REQUIRED", False)
597 if isinstance(value, bool):
598 return value
599 return set(value)
600
601 @property
602 def LOGIN_BY_CODE_FORMAT(self) -> UserCodeFormat:
603 """
604 Controls the format of the login code.
605 """
606 return self._setting("LOGIN_BY_CODE_FORMAT", allauth_settings.USER_CODE_FORMAT)
607
608 @property
609 def PHONE_VERIFICATION_CODE_FORMAT(self) -> UserCodeFormat:
610 """
611 Controls the format of the phone verification code.
612 """
613 return self._setting(
614 "PHONE_VERIFICATION_CODE_FORMAT", allauth_settings.USER_CODE_FORMAT
615 )
616
617 @property
618 def PASSWORD_RESET_BY_CODE_FORMAT(self) -> UserCodeFormat:
619 """
620 Controls the format of the password reset code.
621 """
622 return self._setting(
623 "PASSWORD_RESET_BY_CODE_CODE_FORMAT", allauth_settings.USER_CODE_FORMAT
624 )
625
626 @property
627 def EMAIL_VERIFICATION_BY_CODE_FORMAT(self) -> UserCodeFormat:
628 """
629 Controls the format of the email verification code.
630 """
631 return self._setting(
632 "EMAIL_VERIFICATION_BY_CODE_FORMAT", allauth_settings.USER_CODE_FORMAT
633 )
634
635
636 _app_settings = AppSettings("ACCOUNT_")
637
638
639 def __getattr__(name):
640 # See https://peps.python.org/pep-0562/
641 return getattr(_app_settings, name)