Debian Codegraph @

allauth/account/adapter.py

raw
1 from __future__ import annotations
2
3 import html
4 import inspect
5 import json
6 import warnings
7 from http import HTTPStatus
8 from typing import TYPE_CHECKING, Any
9 from urllib.parse import urlparse
10
11 from django.conf import settings
12 from django.contrib import messages
13 from django.contrib.auth import (
14 authenticate,
15 get_backends,
16 get_user_model,
17 login as django_login,
18 logout as django_logout,
19 )
20 from django.contrib.auth.base_user import AbstractBaseUser
21 from django.contrib.auth.models import AbstractUser, AnonymousUser
22 from django.contrib.auth.password_validation import (
23 MinimumLengthValidator,
24 validate_password,
25 )
26 from django.contrib.sites.shortcuts import get_current_site
27 from django.core.exceptions import FieldDoesNotExist, PermissionDenied
28 from django.core.mail import EmailMessage, EmailMultiAlternatives
29 from django.http import (
30 HttpRequest,
31 HttpResponse,
32 HttpResponseBase,
33 HttpResponseRedirect,
34 )
35 from django.http.request import validate_host
36 from django.shortcuts import resolve_url
37 from django.template import TemplateDoesNotExist
38 from django.template.loader import render_to_string
39 from django.urls import reverse
40 from django.utils import timezone
41 from django.utils.crypto import get_random_string
42 from django.utils.encoding import force_str
43 from django.utils.module_loading import import_string
44 from django.utils.translation import gettext_lazy as _
45
46 from allauth import app_settings as allauth_settings
47 from allauth.account import app_settings, signals
48 from allauth.core import context
49 from allauth.core.internal import ratelimit
50 from allauth.core.internal.adapter import BaseAdapter
51 from allauth.core.internal.cryptokit import generate_user_code
52 from allauth.core.internal.httpkit import (
53 HTTP_USER_AGENT_MAX_LENGTH,
54 get_client_ip,
55 headed_redirect_response,
56 is_headless_request,
57 )
58 from allauth.utils import generate_unique_username
59
60
61 if TYPE_CHECKING:
62 from django.contrib.auth.backends import BaseBackend
63 from django.forms import BaseForm
64
65 from allauth.account.models import EmailAddress, EmailConfirmation, Login
66
67
68 class DefaultAccountAdapter(BaseAdapter):
69 """The adapter class allows you to override various functionality of the
70 ``allauth.account`` app. To do so, point ``settings.ACCOUNT_ADAPTER`` to
71 your own class that derives from ``DefaultAccountAdapter`` and override the
72 behavior by altering the implementation of the methods according to your own
73 needs.
74 """
75
76 error_messages = {
77 "account_inactive": _("This account is currently inactive."),
78 "cannot_remove_primary_email": _(
79 "You cannot remove your primary email address."
80 ),
81 "duplicate_email": _(
82 "This email address is already associated with this account."
83 ),
84 "email_password_mismatch": _(
85 "The email address and/or password you specified are not correct."
86 ),
87 "phone_password_mismatch": _(
88 "The phone number and/or password you specified are not correct."
89 ),
90 "email_taken": _("A user is already registered with this email address."),
91 "enter_current_password": _("Please type your current password."),
92 "incorrect_code": _("Incorrect code."),
93 "incorrect_password": _("Incorrect password."),
94 "invalid_or_expired_key": _("Invalid or expired key."),
95 "invalid_login": _("Invalid login."),
96 "invalid_password_reset": _("The password reset token was invalid."),
97 "max_email_addresses": _("You cannot add more than %d email addresses."),
98 "phone_taken": _("A user is already registered with this phone number."),
99 "too_many_login_attempts": _(
100 "Too many failed login attempts. Try again later."
101 ),
102 "unknown_email": _("The email address is not assigned to any user account."),
103 "unknown_phone": _("The phone number is not assigned to any user account."),
104 "unverified_primary_email": _("Your primary email address must be verified."),
105 "username_blacklisted": _(
106 "Username can not be used. Please use other username."
107 ),
108 "username_password_mismatch": _(
109 "The username and/or password you specified are not correct."
110 ),
111 "username_taken": AbstractUser._meta.get_field("username").error_messages[
112 "unique"
113 ],
114 "select_only_one": _("Please select only one."),
115 "same_as_current": _("The new value must be different from the current one."),
116 "rate_limited": _("Be patient, you are sending too many requests."),
117 }
118
119 def stash_verified_email(self, request: HttpRequest, email: str) -> None:
120 request.session["account_verified_email"] = email
121
122 def unstash_verified_email(self, request: HttpRequest) -> str | None:
123 ret = request.session.get("account_verified_email")
124 request.session["account_verified_email"] = None
125 return ret
126
127 def is_email_verified(self, request: HttpRequest, email: str) -> bool:
128 """
129 Checks whether or not the email address is already verified
130 beyond allauth scope, for example, by having accepted an
131 invitation before signing up.
132 """
133 ret = False
134 verified_email = request.session.get("account_verified_email")
135 if verified_email:
136 ret = verified_email.lower() == email.lower()
137 return ret
138
139 def can_delete_email(self, email_address: EmailAddress) -> bool:
140 """
141 Returns whether or not the given email address can be deleted.
142 """
143 from allauth.account.models import EmailAddress
144
145 if not email_address.pk:
146 return True
147 has_other = (
148 EmailAddress.objects.filter(user_id=email_address.user_id)
149 .exclude(pk=email_address.pk)
150 .exists()
151 )
152 login_by_email = app_settings.LOGIN_METHODS == {app_settings.LoginMethod.EMAIL}
153 if email_address.primary:
154 if has_other:
155 # Don't allow, let the user mark one of the others as primary
156 # first.
157 return False
158 elif login_by_email:
159 # Last email & login is by email, prevent dangling account.
160 return False
161 return True
162 elif has_other:
163 # Account won't be dangling.
164 return True
165 elif login_by_email:
166 # This is the last email.
167 return False
168 else:
169 return True
170
171 def format_email_subject(self, subject: str) -> str:
172 """
173 Formats the given email subject.
174 """
175 prefix = app_settings.EMAIL_SUBJECT_PREFIX
176 if prefix is None:
177 site = get_current_site(context.request)
178 prefix = f"[{site.name}] "
179 return prefix + force_str(subject)
180
181 def get_from_email(self) -> str:
182 """
183 This is a hook that can be overridden to programmatically
184 set the 'from' email address for sending emails
185 """
186 return settings.DEFAULT_FROM_EMAIL
187
188 def render_mail(
189 self,
190 template_prefix: str,
191 email: str | list[str],
192 context: dict[str, Any],
193 headers: dict[str, str] | None = None,
194 ) -> EmailMessage:
195 """
196 Renders an email to `email`. `template_prefix` identifies the
197 email that is to be sent, e.g. "account/email/email_confirmation"
198 """
199 to = [email] if isinstance(email, str) else email
200 subject: str = render_to_string(f"{template_prefix}_subject.txt", context)
201 # remove superfluous line breaks
202 subject = " ".join(subject.splitlines()).strip()
203 subject = self.format_email_subject(subject)
204
205 from_email = self.get_from_email()
206
207 bodies = {}
208 html_ext = app_settings.TEMPLATE_EXTENSION
209 for ext in [html_ext, "txt"]:
210 try:
211 template_name = f"{template_prefix}_message.{ext}"
212 bodies[ext] = render_to_string(
213 template_name,
214 context,
215 globals()["context"].request,
216 ).strip()
217 except TemplateDoesNotExist:
218 if ext == "txt" and not bodies:
219 # We need at least one body
220 raise
221 msg: EmailMessage
222 if "txt" in bodies:
223 msg = EmailMultiAlternatives(
224 subject, bodies["txt"], from_email, to, headers=headers
225 )
226 if html_ext in bodies:
227 msg.attach_alternative(bodies[html_ext], "text/html")
228 else:
229 msg = EmailMessage(
230 subject, bodies[html_ext], from_email, to, headers=headers
231 )
232 msg.content_subtype = "html" # Main content is now text/html
233 return msg
234
235 def send_mail(self, template_prefix: str, email: str, context: dict) -> None:
236 request = globals()["context"].request
237 ctx = {
238 "request": request,
239 "email": email,
240 "current_site": get_current_site(request),
241 }
242 ctx.update(context)
243 msg = self.render_mail(template_prefix, email, ctx)
244 msg.send()
245
246 def get_signup_redirect_url(self, request: HttpRequest) -> str:
247 """
248 Returns the default URL to redirect to directly after signing up.
249 """
250 return resolve_url(app_settings.SIGNUP_REDIRECT_URL)
251
252 def get_login_redirect_url(self, request: HttpRequest) -> str:
253 """
254 Returns the default URL to redirect to after logging in. Note
255 that URLs passed explicitly (e.g. by passing along a `next`
256 GET parameter) take precedence over the value returned here.
257 """
258 assert request.user.is_authenticated # nosec
259 url = getattr(settings, "LOGIN_REDIRECT_URLNAME", None)
260 if url:
261 warnings.warn(
262 "LOGIN_REDIRECT_URLNAME is deprecated, simply"
263 " use LOGIN_REDIRECT_URL with a URL name",
264 DeprecationWarning,
265 )
266 else:
267 url = settings.LOGIN_REDIRECT_URL
268 return resolve_url(url)
269
270 def get_logout_redirect_url(self, request: HttpRequest) -> str:
271 """
272 Returns the URL to redirect to after the user logs out. Note that
273 this method is also invoked if you attempt to log out while no users
274 is logged in. Therefore, request.user is not guaranteed to be an
275 authenticated user.
276 """
277 return resolve_url(app_settings.LOGOUT_REDIRECT_URL)
278
279 def get_email_verification_redirect_url(self, email_address: EmailAddress) -> str:
280 """
281 The URL to return to after email verification.
282 """
283 get_url = getattr(self, "get_email_confirmation_redirect_url", None)
284 if get_url:
285 # Deprecated.
286 return get_url(self.request)
287
288 if self.request.user.is_authenticated:
289 if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL:
290 return app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
291 else:
292 return self.get_login_redirect_url(self.request)
293 else:
294 return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL
295
296 def get_password_change_redirect_url(self, request: HttpRequest) -> str:
297 """
298 The URL to redirect to after a successful password change/set.
299
300 NOTE: Not called during the password reset flow.
301 """
302 return reverse("account_change_password")
303
304 def is_open_for_signup(self, request: HttpRequest) -> bool:
305 """
306 Checks whether or not the site is open for signups.
307
308 Next to simply returning True/False you can also intervene the
309 regular flow by raising an ImmediateHttpResponse
310 """
311 return True
312
313 def new_user(self, request: HttpRequest) -> AbstractBaseUser:
314 """
315 Instantiates a new User instance.
316 """
317 user = get_user_model()()
318 return user
319
320 def populate_username(self, request: HttpRequest, user: AbstractBaseUser) -> None:
321 """
322 Fills in a valid username, if required and missing. If the
323 username is already present it is assumed to be valid
324 (unique).
325 """
326 from .utils import user_email, user_field, user_username
327
328 first_name = user_field(user, "first_name")
329 last_name = user_field(user, "last_name")
330 email = user_email(user)
331 username = user_username(user)
332 if app_settings.USER_MODEL_USERNAME_FIELD:
333 user_username(
334 user,
335 username
336 or self.generate_unique_username(
337 [first_name, last_name, email, username, "user"]
338 ),
339 )
340
341 def generate_unique_username(
342 self, txts: list[str | None], regex: str | None = None
343 ) -> str:
344 return generate_unique_username(txts, regex)
345
346 def save_user(
347 self,
348 request: HttpRequest,
349 user: AbstractBaseUser,
350 form: BaseForm,
351 commit: bool = True,
352 ) -> AbstractBaseUser:
353 """
354 Saves a new `User` instance using information provided in the
355 signup form.
356 """
357 from .utils import user_email, user_field, user_username
358
359 data = form.cleaned_data
360 first_name = data.get("first_name")
361 last_name = data.get("last_name")
362 email = data.get("email")
363 username = data.get("username")
364 user_email(user, email)
365 user_username(user, username)
366 if first_name:
367 user_field(user, "first_name", first_name)
368 if last_name:
369 user_field(user, "last_name", last_name)
370
371 if "password1" in data:
372 password = data["password1"]
373 elif "password" in data:
374 password = data["password"]
375 else:
376 password = None
377 if password:
378 user.set_password(password)
379 else:
380 user.set_unusable_password()
381
382 self.populate_username(request, user)
383 if commit:
384 user.save()
385 if getattr(form, "_has_phone_field", False):
386 phone = form.cleaned_data.get("phone")
387 if phone:
388 self.set_phone(user, phone, False)
389 return user
390
391 def clean_username(self, username: str, shallow: bool = False) -> str:
392 """
393 Validates the username. You can hook into this if you want to
394 (dynamically) restrict what usernames can be chosen.
395 """
396 for validator in app_settings.USERNAME_VALIDATORS:
397 validator(username)
398
399 # TODO: Add regexp support to USERNAME_BLACKLIST
400 username_blacklist_lower = [
401 ub.lower() for ub in app_settings.USERNAME_BLACKLIST
402 ]
403 if username.lower() in username_blacklist_lower:
404 raise self.validation_error("username_blacklisted")
405 # Skipping database lookups when shallow is True, needed for unique
406 # username generation.
407 if not shallow:
408 from .utils import filter_users_by_username
409
410 if filter_users_by_username(username).exists():
411 raise self.validation_error("username_taken")
412 return username
413
414 def clean_email(self, email: str) -> str:
415 """
416 Validates an email value. You can hook into this if you want to
417 (dynamically) restrict what email addresses can be chosen.
418 """
419 return email
420
421 def clean_password(
422 self, password: str, user: AbstractBaseUser | None = None
423 ) -> str:
424 """
425 Validates a password. You can hook into this if you want to
426 restric the allowed password choices.
427 """
428 min_length = app_settings.PASSWORD_MIN_LENGTH
429 if min_length:
430 MinimumLengthValidator(min_length).validate(password)
431 validate_password(password, user) # type:ignore[arg-type]
432 return password
433
434 def clean_phone(self, phone: str) -> str:
435 """
436 Validates a phone number. You can hook into this if you want to
437 (dynamically) restrict what phone numbers can be chosen.
438 """
439 return phone
440
441 def validate_unique_email(self, email: str) -> str:
442 return email
443
444 def add_message(
445 self,
446 request: HttpRequest,
447 level: int,
448 message_template: str | None = None,
449 message_context: dict[str, Any] | None = None,
450 extra_tags: str = "",
451 message: str | None = None,
452 ) -> None:
453 """
454 Wrapper of `django.contrib.messages.add_message`, that reads
455 the message text from a template.
456 """
457 if is_headless_request(request):
458 return
459 if "django.contrib.messages" in settings.INSTALLED_APPS:
460 if message:
461 messages.add_message(request, level, message, extra_tags=extra_tags)
462 return
463 if not message_template:
464 return
465 try:
466 if message_context is None:
467 message_context = {}
468 escaped_message = render_to_string(
469 message_template,
470 message_context,
471 context.request,
472 ).strip()
473 if escaped_message:
474 message = html.unescape(escaped_message)
475 messages.add_message(request, level, message, extra_tags=extra_tags)
476 except TemplateDoesNotExist:
477 pass
478
479 def ajax_response(
480 self,
481 request: HttpRequest,
482 response: HttpResponse,
483 redirect_to: str | None = None,
484 form: BaseForm | None = None,
485 data: Any = None,
486 ) -> HttpResponse:
487 resp: dict[str, Any] = {}
488 status = response.status_code
489
490 if redirect_to:
491 status = HTTPStatus.OK
492 resp["location"] = redirect_to
493 if form:
494 if request.method == "POST":
495 if form.is_valid():
496 status = HTTPStatus.OK
497 else:
498 status = HTTPStatus.BAD_REQUEST
499 else:
500 status = HTTPStatus.OK
501 resp["form"] = self.ajax_response_form(form)
502 if hasattr(response, "render"):
503 response.render()
504 resp["html"] = response.content.decode("utf8")
505 if data is not None:
506 resp["data"] = data
507 return HttpResponse(
508 json.dumps(resp), status=status, content_type="application/json"
509 )
510
511 def ajax_response_form(self, form: BaseForm) -> dict[str, Any]:
512 form_spec: dict[str, Any] = {
513 "fields": {},
514 "field_order": [],
515 "errors": form.non_field_errors(),
516 }
517 for field in form:
518 field_spec: dict[str, Any] = {
519 "label": force_str(field.label),
520 "value": field.value(),
521 "help_text": force_str(field.help_text),
522 "errors": [force_str(e) for e in field.errors],
523 "widget": {
524 "attrs": {
525 k: force_str(v) for k, v in field.field.widget.attrs.items()
526 }
527 },
528 }
529 form_spec["fields"][field.html_name] = field_spec
530 form_spec["field_order"].append(field.html_name)
531 return form_spec
532
533 def pre_login(
534 self,
535 request: HttpRequest,
536 user: AbstractBaseUser,
537 *,
538 email_verification: str,
539 signal_kwargs: dict[str, Any] | None,
540 email: str | None,
541 signup: bool,
542 redirect_url: str | None,
543 ) -> HttpResponse | None:
544 if not user.is_active:
545 return self.respond_user_inactive(request, user)
546 return None
547
548 def post_login(
549 self,
550 request: HttpRequest,
551 user: AbstractBaseUser,
552 *,
553 email_verification: str,
554 signal_kwargs: dict[str, Any] | None,
555 email: str | None,
556 signup: bool,
557 redirect_url: str | None,
558 ) -> HttpResponse:
559 from .utils import get_login_redirect_url
560
561 response: HttpResponseBase
562 if is_headless_request(request):
563 from allauth.headless.base.response import AuthenticationResponse
564
565 response = AuthenticationResponse(request)
566 else:
567 response = HttpResponseRedirect(
568 get_login_redirect_url(request, redirect_url, signup=signup)
569 )
570
571 if signal_kwargs is None:
572 signal_kwargs = {}
573 signals.user_logged_in.send(
574 sender=user.__class__,
575 request=request,
576 response=response,
577 user=user,
578 **signal_kwargs,
579 )
580 self.add_message(
581 request,
582 messages.SUCCESS,
583 "account/messages/logged_in.txt",
584 {"user": user},
585 )
586 return response
587
588 def login(self, request: HttpRequest, user: AbstractBaseUser) -> None:
589 # HACK: This is not nice. The proper Django way is to use an
590 # authentication backend
591 if not hasattr(user, "backend"):
592 from .auth_backends import AuthenticationBackend
593
594 backends = get_backends()
595 backend: BaseBackend | None = None
596 for b in backends:
597 if isinstance(b, AuthenticationBackend):
598 # prefer our own backend
599 backend = b
600 break
601 elif not backend and hasattr(b, "get_user"):
602 # Pick the first valid one
603 backend = b
604 backend_path = f"{backend.__module__}.{backend.__class__.__name__}"
605 user.backend = backend_path # type:ignore[attr-defined]
606 django_login(request, user) # type:ignore[arg-type]
607
608 def logout(self, request: HttpRequest) -> None:
609 django_logout(request)
610
611 def confirm_email(self, request: HttpRequest, email_address: EmailAddress) -> bool:
612 """
613 Marks the email address as confirmed on the db
614 """
615 from allauth.account.internal.flows import email_verification
616
617 return email_verification.verify_email(request, email_address)
618
619 def set_password(self, user: AbstractBaseUser, password: str) -> None:
620 """
621 Sets the password for the user.
622 """
623 user.set_password(password)
624 user.save()
625
626 def get_user_search_fields(self) -> list[str]:
627 ret = []
628 User = get_user_model()
629 candidates = [
630 app_settings.USER_MODEL_USERNAME_FIELD,
631 "first_name",
632 "last_name",
633 "email",
634 ]
635 for candidate in candidates:
636 try:
637 User._meta.get_field(candidate)
638 ret.append(candidate)
639 except FieldDoesNotExist:
640 pass
641 return ret
642
643 def is_safe_url(self, url: str) -> bool:
644 from django.utils.http import url_has_allowed_host_and_scheme
645
646 # get_host already validates the given host, so no need to check it again
647 allowed_hosts = {context.request.get_host()} | set(settings.ALLOWED_HOSTS)
648
649 # Include hosts derived from CSRF_TRUSTED_ORIGINS
650 trusted_hosts = {
651 urlparse(origin).netloc for origin in settings.CSRF_TRUSTED_ORIGINS
652 }
653 allowed_hosts.update(trusted_hosts)
654
655 # ALLOWED_HOSTS supports wildcards, and subdomains using a '.' prefix.
656 # But, `url_has_allowed_host_and_scheme()` doesn't support that. So,
657 # let's check the domain using the ALLOWED_HOSTS logic, and if valid,
658 # add it as allowed so that we can then call
659 # `url_has_allowed_host_and_scheme()`.
660 parsed_host = urlparse(url).netloc
661 if parsed_host:
662 if validate_host(parsed_host, allowed_hosts):
663 allowed_hosts.add(parsed_host)
664
665 return url_has_allowed_host_and_scheme(url, allowed_hosts=allowed_hosts)
666
667 def send_password_reset_mail(
668 self, user: AbstractBaseUser, email: str, context: dict[str, Any]
669 ) -> None:
670 """
671 Method intended to be overridden in case you need to customize the logic
672 used to determine whether a user is permitted to request a password reset.
673 For example, if you are enforcing something like "social only" authentication
674 in your app, you may want to intervene here by checking `user.has_usable_password`
675
676 """
677 return self.send_mail("account/email/password_reset_key", email, context)
678
679 def get_reset_password_from_key_url(self, key: str) -> str:
680 """
681 Method intended to be overridden in case the password reset email
682 needs to be adjusted.
683 """
684 from allauth.account.internal import flows
685
686 return flows.password_reset.get_reset_password_from_key_url(self.request, key)
687
688 def get_email_confirmation_url(
689 self, request: HttpRequest, emailconfirmation: EmailConfirmation
690 ) -> str:
691 """Constructs the email confirmation (activation) url.
692
693 Note that if you have architected your system such that email
694 confirmations are sent outside of the request context `request`
695 can be `None` here.
696 """
697 from allauth.account.internal import flows
698
699 return flows.email_verification.get_email_verification_url(
700 request, emailconfirmation
701 )
702
703 def should_send_confirmation_mail(
704 self, request: HttpRequest, email_address: EmailAddress, signup: bool
705 ) -> bool:
706 return True
707
708 def send_account_already_exists_mail(self, email: str) -> None:
709 from allauth.account.internal import flows
710
711 signup_url = flows.signup.get_signup_url(context.request)
712 password_reset_url = flows.password_reset.get_reset_password_url(
713 context.request
714 )
715 ctx = {
716 "signup_url": signup_url,
717 "password_reset_url": password_reset_url,
718 }
719 self.send_mail("account/email/account_already_exists", email, ctx)
720
721 def send_confirmation_mail(
722 self, request: HttpRequest, emailconfirmation, signup: bool
723 ) -> None:
724 ctx: dict[str, Any] = {
725 "user": emailconfirmation.email_address.user,
726 }
727 if app_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED:
728 ctx.update({"code": emailconfirmation.key})
729 else:
730 ctx.update(
731 {
732 "key": emailconfirmation.key,
733 "activate_url": self.get_email_confirmation_url(
734 request, emailconfirmation
735 ),
736 }
737 )
738 if signup:
739 email_template = "account/email/email_confirmation_signup"
740 else:
741 email_template = "account/email/email_confirmation"
742 self.send_mail(email_template, emailconfirmation.email_address.email, ctx)
743
744 def respond_user_inactive(
745 self, request: HttpRequest, user: AbstractBaseUser
746 ) -> HttpResponse:
747 return headed_redirect_response("account_inactive")
748
749 def respond_email_verification_sent(
750 self, request: HttpRequest, user: AbstractBaseUser | None
751 ) -> HttpResponseBase:
752 return headed_redirect_response("account_email_verification_sent")
753
754 def _get_login_attempts_cache_key(
755 self, request: HttpRequest, **credentials: Any
756 ) -> str:
757 site = get_current_site(request)
758 login = credentials.get("email", credentials.get("username", "")).lower()
759 return f"{site.domain}:{login}"
760
761 def _delete_login_attempts_cached_email(
762 self, request: HttpRequest, **credentials: Any
763 ) -> None:
764 cache_key = self._get_login_attempts_cache_key(request, **credentials)
765 # Here, we wipe the login failed rate limit, completely. This is safe,
766 # as we only do this on a succesful password reset, which is rate limited
767 # on itself (e.g. sending of email etc.).
768 ratelimit.clear(
769 request,
770 config=app_settings.RATE_LIMITS,
771 action="login_failed",
772 key=cache_key,
773 )
774
775 def _rollback_login_failed_rl_usage(self) -> None:
776 usage = getattr(self, "_login_failed_rl_usage", None)
777 if usage:
778 usage.rollback()
779
780 def pre_authenticate(self, request: HttpRequest, **credentials: Any) -> None:
781 cache_key = self._get_login_attempts_cache_key(request, **credentials)
782 self._login_failed_rl_usage = ratelimit.consume(
783 request,
784 config=app_settings.RATE_LIMITS,
785 action="login_failed",
786 key=cache_key,
787 )
788 if not self._login_failed_rl_usage:
789 raise self.validation_error("too_many_login_attempts")
790
791 def authenticate(
792 self, request: HttpRequest, **credentials: Any
793 ) -> AbstractBaseUser | None:
794 """Only authenticates, does not actually login. See `login`"""
795 from allauth.account.auth_backends import AuthenticationBackend
796
797 self.pre_authenticate(request, **credentials)
798 AuthenticationBackend.unstash_authenticated_user()
799 user: AbstractBaseUser | None = authenticate(request, **credentials)
800 alt_user = AuthenticationBackend.unstash_authenticated_user()
801 user = user or alt_user
802 if user:
803 # On a succesful login, we cannot just wipe the login failed rate
804 # limit. That consists of 2 parts, a per IP limit, and, a per
805 # key(email) limit. Wiping it completely would allow an attacker to
806 # insert periodic successful logins during a brute force
807 # process. So instead, we are rolling back our consumption.
808 self._rollback_login_failed_rl_usage()
809 else:
810 self.authentication_failed(request, **credentials)
811 return user
812
813 def authentication_failed(self, request: HttpRequest, **credentials: Any) -> None:
814 pass
815
816 def reauthenticate(self, user: AbstractBaseUser, password: str) -> bool:
817 from allauth.account.models import EmailAddress
818 from allauth.account.utils import user_username
819
820 credentials = {"password": password}
821 username = user_username(user)
822 if username:
823 credentials["username"] = username
824 email = EmailAddress.objects.get_primary_email(user)
825 if email:
826 credentials["email"] = email
827 if app_settings.LoginMethod.PHONE in app_settings.LOGIN_METHODS:
828 phone_verified = self.get_phone(user)
829 if phone_verified:
830 credentials["phone"] = phone_verified[0]
831 reauth_user = self.authenticate(context.request, **credentials)
832 return reauth_user is not None and reauth_user.pk == user.pk
833
834 def is_ajax(self, request: HttpRequest) -> bool:
835 return any(
836 [
837 request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest",
838 request.content_type == "application/json",
839 request.META.get("HTTP_ACCEPT") == "application/json",
840 ]
841 )
842
843 def get_client_ip(self, request: HttpRequest) -> str:
844 """
845 Returns the IP address of the client.
846 """
847 ip = get_client_ip(request)
848 if not ip:
849 raise PermissionDenied("Unable to determine client IP address")
850 return ip
851
852 def get_http_user_agent(self, request: HttpRequest) -> str:
853 return request.META.get("HTTP_USER_AGENT", "Unspecified")
854
855 def generate_emailconfirmation_key(self, email: str) -> str:
856 key = get_random_string(64).lower()
857 return key
858
859 def get_login_stages(self) -> list[str]:
860 ret = []
861 ret.append("allauth.account.stages.LoginByCodeStage")
862 ret.append("allauth.account.stages.PhoneVerificationStage")
863 ret.append("allauth.account.stages.EmailVerificationStage")
864 if allauth_settings.MFA_ENABLED:
865 from allauth.mfa import app_settings as mfa_settings
866
867 ret.append("allauth.mfa.stages.AuthenticateStage")
868 if mfa_settings._TRUST_STAGE_ENABLED:
869 ret.append("allauth.mfa.stages.TrustStage")
870
871 if mfa_settings.PASSKEY_SIGNUP_ENABLED:
872 ret.append("allauth.mfa.webauthn.stages.PasskeySignupStage")
873 return ret
874
875 def get_reauthentication_methods(
876 self, user: AbstractBaseUser | AnonymousUser
877 ) -> list[dict]:
878 """The order of the methods returned matters. The first method is the
879 default when using the `@reauthentication_required` decorator.
880 """
881 from allauth.account.internal.flows.reauthentication import (
882 get_reauthentication_flows,
883 )
884
885 if not user.is_authenticated:
886 return []
887 flow_by_id = {f["id"]: f for f in get_reauthentication_flows(user)}
888 ret = []
889 if "reauthenticate" in flow_by_id:
890 entry = {
891 "id": "reauthenticate",
892 "description": _("Use your password"),
893 "url": reverse("account_reauthenticate"),
894 }
895 ret.append(entry)
896 if "mfa_reauthenticate" in flow_by_id:
897 types = flow_by_id["mfa_reauthenticate"]["types"]
898 if "recovery_codes" in types or "totp" in types:
899 entry = {
900 "id": "mfa_reauthenticate",
901 "description": _("Use authenticator app or code"),
902 "url": reverse("mfa_reauthenticate"),
903 }
904 ret.append(entry)
905 if "webauthn" in types:
906 entry = {
907 "id": "mfa_reauthenticate:webauthn",
908 "description": _("Use a security key"),
909 "url": reverse("mfa_reauthenticate_webauthn"),
910 }
911 ret.append(entry)
912 return ret
913
914 def send_notification_mail(
915 self,
916 template_prefix: str,
917 user: AbstractBaseUser,
918 context: dict[str, Any] | None = None,
919 email: str | None = None,
920 ) -> None:
921 from allauth.account.models import EmailAddress
922
923 if not app_settings.EMAIL_NOTIFICATIONS:
924 return
925 if not email:
926 email = EmailAddress.objects.get_primary_email(user)
927 if not email:
928 return
929 ctx = {
930 "timestamp": timezone.now(),
931 "ip": self.get_client_ip(self.request),
932 "user_agent": self.get_http_user_agent(self.request)[
933 :HTTP_USER_AGENT_MAX_LENGTH
934 ],
935 }
936 if context:
937 ctx.update(context)
938 self.send_mail(template_prefix, email, ctx)
939
940 def generate_login_code(self) -> str:
941 """
942 Generates a new login code.
943 """
944 return generate_user_code(**app_settings.LOGIN_BY_CODE_FORMAT)
945
946 def generate_password_reset_code(self) -> str:
947 """
948 Generates a new password reset code.
949 """
950 return generate_user_code(**app_settings.PASSWORD_RESET_BY_CODE_FORMAT)
951
952 def generate_email_verification_code(self) -> str:
953 """
954 Generates a new email verification code.
955 """
956 return generate_user_code(**app_settings.EMAIL_VERIFICATION_BY_CODE_FORMAT)
957
958 def generate_phone_verification_code(
959 self, *, user: AbstractBaseUser, phone: str
960 ) -> str:
961 """
962 Generates a new phone verification code.
963 """
964 return generate_user_code(**app_settings.PHONE_VERIFICATION_CODE_FORMAT)
965
966 def _generate_phone_verification_code_compat(
967 self, *, user: AbstractBaseUser, phone: str
968 ) -> str:
969 sig = inspect.signature(self.generate_phone_verification_code)
970 if len(sig.parameters) == 0:
971 warnings.warn(
972 "generate_phone_verification_code(self) is deprecated, use generate_phone_verification_code(self, *, user, phone)",
973 DeprecationWarning,
974 )
975 return self.generate_phone_verification_code() # type: ignore[call-arg]
976
977 return self.generate_phone_verification_code(user=user, phone=phone)
978
979 def is_login_by_code_required(self, login: Login) -> bool:
980 """
981 Returns whether or not login-by-code is required for the given
982 login.
983 """
984 from allauth.account import authentication
985
986 method = None
987 records = authentication.get_authentication_records(self.request)
988 if records:
989 method = records[-1]["method"]
990 if method == "code":
991 return False
992 value = app_settings.LOGIN_BY_CODE_REQUIRED
993 if isinstance(value, bool):
994 return value
995 if not value:
996 return False
997 return method is None or method in value
998
999 def phone_form_field(self, **kwargs: Any) -> Any:
1000 """
1001 Returns a form field used to input phone numbers.
1002 """
1003 from allauth.account.fields import PhoneField
1004
1005 return PhoneField(**kwargs)
1006
1007 def send_unknown_account_sms(self, phone: str, **kwargs: Any) -> None:
1008 """
1009 In case enumeration prevention is enabled, and, a verification code
1010 is requested for an unlisted phone number, this method is invoked to
1011 send a text explaining that no account is on file.
1012 """
1013 pass
1014
1015 def send_account_already_exists_sms(self, phone: str) -> None:
1016 pass
1017
1018 def send_verification_code_sms(
1019 self, user: AbstractBaseUser, phone: str, code: str, **kwargs: Any
1020 ) -> None:
1021 """
1022 Sends a verification code.
1023 """
1024 raise NotImplementedError
1025
1026 @property
1027 def _has_phone_impl(self) -> bool:
1028 """
1029 Checks whether the phone number adapter is fully implemented.
1030 """
1031 methods = (
1032 "send_verification_code_sms",
1033 "set_phone",
1034 "get_phone",
1035 "set_phone_verified",
1036 "get_user_by_phone",
1037 )
1038 return all(
1039 getattr(self.__class__, method) != getattr(DefaultAccountAdapter, method)
1040 for method in methods
1041 )
1042
1043 def set_phone(self, user: AbstractBaseUser, phone: str, verified: bool) -> None:
1044 """
1045 Sets the phone number (and verified status) for the given user.
1046 """
1047 raise NotImplementedError
1048
1049 def get_phone(self, user: AbstractBaseUser) -> tuple[str, bool] | None:
1050 """
1051 Returns the phone number stored for the given user. A tuple of the
1052 phone number itself, and whether or not the phone number was verified is
1053 returned.
1054 """
1055 raise NotImplementedError
1056
1057 def set_phone_verified(self, user: AbstractBaseUser, phone: str) -> None:
1058 """
1059 Marks the specified phone number for the given user as
1060 verified. Note that the user is already expected to have
1061 the phone number attached to the account.
1062 """
1063 raise NotImplementedError
1064
1065 def get_user_by_phone(self, phone: str) -> AbstractBaseUser | None:
1066 """
1067 Looks up a user given the specified phone number. Returns ``None`` if no user
1068 was found.
1069 """
1070 raise NotImplementedError
1071
1072
1073 def get_adapter(request: HttpRequest | None = None) -> DefaultAccountAdapter:
1074 return import_string(app_settings.ADAPTER)(request)