| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.contrib import messages |
| 4 |
from django.http import HttpRequest |
| 5 |
|
| 6 |
from allauth.account.adapter import get_adapter as get_account_adapter |
| 7 |
from allauth.account.internal.flows.reauthentication import ( |
| 8 |
raise_if_reauthentication_required, |
| 9 |
) |
| 10 |
from allauth.core.internal.httpkit import authenticated_user |
| 11 |
from allauth.mfa import signals |
| 12 |
from allauth.mfa.base.internal.flows import delete_and_cleanup |
| 13 |
from allauth.mfa.models import Authenticator |
| 14 |
from allauth.mfa.recovery_codes.internal.flows import auto_generate_recovery_codes |
| 15 |
from allauth.mfa.totp.internal.auth import TOTP, clear_totp_secret |
| 16 |
|
| 17 |
|
| 18 |
def activate_totp( |
| 19 |
request: HttpRequest, form |
| 20 |
) -> tuple[Authenticator, Authenticator | None]: |
| 21 |
raise_if_reauthentication_required(request) |
| 22 |
user = authenticated_user(request) |
| 23 |
totp_auth = TOTP.activate(user, form.secret).instance |
| 24 |
clear_totp_secret(request) |
| 25 |
signals.authenticator_added.send( |
| 26 |
sender=Authenticator, |
| 27 |
request=request, |
| 28 |
user=user, |
| 29 |
authenticator=totp_auth, |
| 30 |
) |
| 31 |
adapter = get_account_adapter(request) |
| 32 |
adapter.add_message(request, messages.SUCCESS, "mfa/messages/totp_activated.txt") |
| 33 |
adapter.send_notification_mail("mfa/email/totp_activated", user) |
| 34 |
rc_auth = auto_generate_recovery_codes(request) |
| 35 |
return totp_auth, rc_auth |
| 36 |
|
| 37 |
|
| 38 |
def deactivate_totp(request: HttpRequest, authenticator: Authenticator) -> None: |
| 39 |
raise_if_reauthentication_required(request) |
| 40 |
delete_and_cleanup(request, authenticator) |
| 41 |
adapter = get_account_adapter(request) |
| 42 |
adapter.add_message(request, messages.SUCCESS, "mfa/messages/totp_deactivated.txt") |
| 43 |
adapter.send_notification_mail( |
| 44 |
"mfa/email/totp_deactivated", authenticated_user(request) |
| 45 |
) |