| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django import forms |
| 4 |
from django.utils.translation import gettext_lazy as _ |
| 5 |
|
| 6 |
from allauth.core import context |
| 7 |
from allauth.mfa import signals |
| 8 |
from allauth.mfa.adapter import get_adapter |
| 9 |
from allauth.mfa.base.internal.flows import check_rate_limit, post_authentication |
| 10 |
from allauth.mfa.models import Authenticator |
| 11 |
|
| 12 |
|
| 13 |
class BaseAuthenticateForm(forms.Form): |
| 14 |
code = forms.CharField( |
| 15 |
label=_("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 |
|
| 25 |
def clean_code(self) -> str: |
| 26 |
clear_rl = check_rate_limit(self.user) |
| 27 |
code = self.cleaned_data["code"] |
| 28 |
main_auth: Authenticator | None = None |
| 29 |
for auth in Authenticator.objects.filter(user=self.user).exclude( |
| 30 |
# WebAuthn cannot validate manual codes. |
| 31 |
type=Authenticator.Type.WEBAUTHN |
| 32 |
): |
| 33 |
if not main_auth or auth.type == Authenticator.Type.TOTP: |
| 34 |
# Don't emit failure signals to all authenticator, just to the |
| 35 |
# main one. |
| 36 |
main_auth = auth |
| 37 |
if auth.wrap().validate_code(code): |
| 38 |
auth.user = self.user |
| 39 |
self.authenticator = auth |
| 40 |
clear_rl() |
| 41 |
return code |
| 42 |
|
| 43 |
if main_auth: |
| 44 |
self._emit_authentication_failed(main_auth) |
| 45 |
raise get_adapter().validation_error("incorrect_code") |
| 46 |
|
| 47 |
def _emit_authentication_failed(self, authenticator: Authenticator) -> None: |
| 48 |
signals.authentication_failed.send( |
| 49 |
sender=Authenticator, |
| 50 |
request=context.request, |
| 51 |
user=self.user, |
| 52 |
authenticator=authenticator, |
| 53 |
reauthentication=False, |
| 54 |
) |
| 55 |
|
| 56 |
|
| 57 |
class AuthenticateForm(BaseAuthenticateForm): |
| 58 |
def save(self) -> None: |
| 59 |
post_authentication(context.request, self.authenticator) |
| 60 |
|
| 61 |
|
| 62 |
class ReauthenticateForm(BaseAuthenticateForm): |
| 63 |
def save(self) -> None: |
| 64 |
post_authentication(context.request, self.authenticator, reauthenticated=True) |
| 65 |
|
| 66 |
def _emit_authentication_failed(self, authenticator: Authenticator) -> None: |
| 67 |
signals.authentication_failed.send( |
| 68 |
sender=Authenticator, |
| 69 |
request=context.request, |
| 70 |
user=self.user, |
| 71 |
authenticator=authenticator, |
| 72 |
reauthentication=True, |
| 73 |
) |