Debian Codegraph @

allauth/mfa/base/internal/flows.py

raw
1 from __future__ import annotations
2
3 from collections.abc import Callable
4
5 from django.contrib.auth.base_user import AbstractBaseUser
6 from django.http import HttpRequest
7
8 from allauth.account.adapter import get_adapter as get_account_adapter
9 from allauth.account.internal.flows.login import record_authentication
10 from allauth.core import context, ratelimit
11 from allauth.mfa import signals
12 from allauth.mfa.models import Authenticator
13
14
15 def delete_dangling_recovery_codes(user: AbstractBaseUser) -> Authenticator | None:
16 deleted_authenticator = None
17 qs = Authenticator.objects.filter(user_id=user.pk)
18 if not qs.exclude(type=Authenticator.Type.RECOVERY_CODES).exists():
19 deleted_authenticator = qs.first()
20 qs.delete()
21 return deleted_authenticator
22
23
24 def delete_and_cleanup(request: HttpRequest, authenticator) -> None:
25 authenticator.delete()
26 rc_auth = delete_dangling_recovery_codes(authenticator.user)
27 for auth in [authenticator, rc_auth]:
28 if auth:
29 signals.authenticator_removed.send(
30 sender=Authenticator,
31 request=request,
32 user=request.user,
33 authenticator=auth,
34 )
35
36
37 def post_authentication(
38 request: HttpRequest,
39 authenticator: Authenticator,
40 reauthenticated: bool = False,
41 passwordless: bool = False,
42 ) -> None:
43 authenticator.record_usage()
44 extra_data = {
45 "id": authenticator.pk,
46 "type": authenticator.type,
47 }
48 if reauthenticated:
49 extra_data["reauthenticated"] = True
50 if passwordless:
51 extra_data["passwordless"] = True
52 record_authentication(request, authenticator.user, "mfa", **extra_data)
53 signals.authenticator_used.send(
54 sender=Authenticator,
55 request=request,
56 user=authenticator.user,
57 authenticator=authenticator,
58 reauthenticated=reauthenticated,
59 passwordless=passwordless,
60 )
61
62
63 def check_rate_limit(user: AbstractBaseUser) -> Callable[[], None]:
64 key = f"mfa-auth-user-{str(user.pk)}"
65 if not ratelimit.consume(
66 context.request,
67 action="login_failed",
68 key=key,
69 ):
70 raise get_account_adapter().validation_error("too_many_login_attempts")
71 return lambda: ratelimit.clear(context.request, action="login_failed", key=key)