Debian Codegraph @

allauth/mfa/totp/forms.py

raw
1 from __future__ import annotations
2
3 from typing import Any
4
5 from django import forms
6 from django.utils.translation import gettext_lazy as _
7
8 from allauth.mfa.adapter import get_adapter
9 from allauth.mfa.internal.flows.add import validate_can_add_authenticator
10 from allauth.mfa.totp.internal import auth
11
12
13 class ActivateTOTPForm(forms.Form):
14 code = forms.CharField(
15 label=_("Authenticator code"),
16 widget=forms.TextInput(
17 attrs={"placeholder": _("Code"), "autocomplete": "one-time-code"},
18 ),
19 )
20
21 def __init__(self, *args, **kwargs) -> None:
22 self.user = kwargs.pop("user")
23 super().__init__(*args, **kwargs)
24 self.secret = auth.get_totp_secret(regenerate=not self.is_bound)
25
26 def clean_code(self) -> str:
27 validate_can_add_authenticator(self.user)
28 code = self.cleaned_data["code"]
29 if not auth.validate_totp_code(self.secret, code):
30 raise get_adapter().validation_error("incorrect_code")
31 return code
32
33
34 class DeactivateTOTPForm(forms.Form):
35 def __init__(self, *args, **kwargs) -> None:
36 self.authenticator = kwargs.pop("authenticator")
37 super().__init__(*args, **kwargs)
38
39 def clean(self) -> dict[str, Any] | None:
40 cleaned_data = super().clean()
41 adapter = get_adapter()
42 if not adapter.can_delete_authenticator(self.authenticator):
43 raise adapter.validation_error("cannot_delete_authenticator")
44 return cleaned_data