Debian Codegraph @

docs/mfa/django-allauth-2fa.rst

raw
1 Upgrading from django-allauth-2fa
2 =================================
3
4 In case you are currently using django-allauth-2fa and want to switch to the
5 built-in implementation, you will need to migrate the existing TOTP keys and recovery codes. For that purpose, the following reference code is available::
6
7 import base64
8
9 from allauth.mfa.adapter import get_adapter
10 from allauth.mfa.models import Authenticator
11 from django.core.management.base import BaseCommand
12 from django_otp.plugins.otp_static.models import StaticDevice
13 from django_otp.plugins.otp_totp.models import TOTPDevice
14
15
16 class Command(BaseCommand):
17 def handle(self, **options):
18 adapter = get_adapter()
19 authenticators = []
20 for totp in TOTPDevice.objects.filter(confirmed=True).iterator():
21 recovery_codes = set()
22 for sdevice in StaticDevice.objects.filter(confirmed=True, user_id=totp.user_id).iterator():
23 recovery_codes.update(sdevice.token_set.values_list("token", flat=True))
24 secret = base64.b32encode(bytes.fromhex(totp.key)).decode("ascii")
25 totp_authenticator = Authenticator(
26 user_id=totp.user_id,
27 type=Authenticator.Type.TOTP,
28 data={"secret": adapter.encrypt(secret)},
29 )
30 authenticators.append(totp_authenticator)
31 authenticators.append(
32 Authenticator(
33 user_id=totp.user_id,
34 type=Authenticator.Type.RECOVERY_CODES,
35 data={
36 "migrated_codes": [adapter.encrypt(c) for c in recovery_codes],
37 },
38 )
39 )
40 Authenticator.objects.bulk_create(authenticators)