Debian Codegraph @

allauth/mfa/adapter.py

raw
1 from __future__ import annotations
2
3 from io import BytesIO
4 from urllib.parse import quote, urlencode
5
6 from django.contrib.auth.base_user import AbstractBaseUser
7 from django.utils.module_loading import import_string
8 from django.utils.translation import gettext, gettext_lazy as _
9
10 from allauth import app_settings as allauth_settings
11 from allauth.account.adapter import get_adapter as get_account_adapter
12 from allauth.account.utils import (
13 user_display,
14 user_email,
15 user_pk_to_url_str,
16 user_username,
17 )
18 from allauth.core import context
19 from allauth.core.internal.adapter import BaseAdapter
20 from allauth.mfa import app_settings
21 from allauth.mfa.models import Authenticator
22
23
24 class DefaultMFAAdapter(BaseAdapter):
25 """The adapter class allows you to override various functionality of the
26 ``allauth.mfa`` app. To do so, point ``settings.MFA_ADAPTER`` to your own
27 class that derives from ``DefaultMFAAdapter`` and override the behavior by
28 altering the implementation of the methods according to your own needs.
29 """
30
31 error_messages = {
32 "add_email_blocked": _(
33 "You cannot add an email address to an account protected by two-factor authentication."
34 ),
35 "cannot_delete_authenticator": _(
36 "You cannot deactivate two-factor authentication."
37 ),
38 "cannot_generate_recovery_codes": _(
39 "You cannot generate recovery codes without having two-factor authentication enabled."
40 ),
41 "incorrect_code": _("Incorrect code."),
42 "unverified_email": _(
43 "You cannot activate two-factor authentication until you have verified your email address."
44 ),
45 }
46 "The error messages that can occur as part of MFA form handling."
47
48 def get_totp_label(self, user: AbstractBaseUser) -> str:
49 """Returns the label used for representing the given user in a TOTP QR
50 code.
51 """
52 return self._get_user_identifier(user)
53
54 def _get_user_identifier(self, user: AbstractBaseUser) -> str:
55 """Human-palatable identifier for a user account. It is intended only
56 for display.
57 """
58 label = user_email(user)
59 if not label:
60 label = user_username(user)
61 if not label:
62 label = str(user)
63 return label
64
65 def get_totp_issuer(self) -> str:
66 """Returns the TOTP issuer name that will be contained in the TOTP QR
67 code.
68 """
69 issuer = app_settings.TOTP_ISSUER
70 if not issuer:
71 issuer = self._get_site_name()
72 return issuer
73
74 def build_totp_url(self, user: AbstractBaseUser, secret: str) -> str:
75 label = self.get_totp_label(user)
76 issuer = self.get_totp_issuer()
77 params = {
78 "secret": secret,
79 # This is the default
80 # "algorithm": "SHA1",
81 "issuer": issuer,
82 }
83 if app_settings.TOTP_DIGITS != 6:
84 params["digits"] = app_settings.TOTP_DIGITS
85 if app_settings.TOTP_PERIOD != 30:
86 params["period"] = app_settings.TOTP_PERIOD
87 return f"otpauth://totp/{quote(label)}?{urlencode(params, quote_via=quote)}"
88
89 def build_totp_svg(self, url: str) -> str:
90 import qrcode
91 from qrcode.image.svg import SvgPathImage
92
93 img = qrcode.make(url, image_factory=SvgPathImage)
94 buf = BytesIO()
95 img.save(buf)
96 return buf.getvalue().decode("utf8")
97
98 def _get_site_name(self) -> str:
99 if allauth_settings.SITES_ENABLED:
100 from django.contrib.sites.models import Site
101
102 return Site.objects.get_current(context.request).name
103 else:
104 return context.request.get_host()
105
106 def encrypt(self, text: str) -> str:
107 """Secrets such as the TOTP key are stored in the database. This
108 hook can be used to encrypt those so that they are not stored in the
109 clear in the database.
110 """
111 return text
112
113 def decrypt(self, encrypted_text: str) -> str:
114 """Counter part of ``encrypt()``."""
115 text = encrypted_text
116 return text
117
118 def can_delete_authenticator(self, authenticator: Authenticator) -> bool:
119 return True
120
121 def send_notification_mail(self, *args, **kwargs) -> None:
122 return get_account_adapter().send_notification_mail(*args, **kwargs)
123
124 def is_mfa_enabled(self, user: AbstractBaseUser, types=None) -> bool:
125 """
126 Returns ``True`` if (and only if) the user has 2FA enabled.
127 """
128 if user.is_anonymous:
129 return False
130 qs = Authenticator.objects.filter(user_id=user.pk)
131 if types is not None:
132 qs = qs.filter(type__in=types)
133 return qs.exists()
134
135 def generate_authenticator_name(
136 self, user: AbstractBaseUser, type: Authenticator.Type
137 ) -> str:
138 """
139 Generate a human friendly name for the key. Used to prefill the "Add
140 key" form.
141 """
142 n = Authenticator.objects.filter(user_id=user.pk, type=type).count()
143 if n == 0:
144 return gettext("Master key")
145 elif n == 1:
146 return gettext("Backup key")
147 return gettext("Key nr. {number}").format(number=n + 1)
148
149 def get_public_key_credential_rp_entity(self) -> dict[str, str]:
150 name = self._get_site_name()
151 return {
152 "id": context.request.get_host().partition(":")[0],
153 "name": name,
154 }
155
156 def get_public_key_credential_user_entity(self, user: AbstractBaseUser) -> dict:
157 return {
158 "id": user_pk_to_url_str(user).encode("utf8"),
159 "display_name": user_display(user),
160 "name": self._get_user_identifier(user),
161 }
162
163
164 def get_adapter() -> DefaultMFAAdapter:
165 return import_string(app_settings.ADAPTER)()