| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.conf import settings |
| 4 |
from django.core.exceptions import ImproperlyConfigured |
| 5 |
from django.db import models |
| 6 |
from django.db.models import Q |
| 7 |
from django.db.models.constraints import UniqueConstraint |
| 8 |
from django.utils import timezone |
| 9 |
from django.utils.translation import gettext_lazy as _ |
| 10 |
|
| 11 |
from allauth import app_settings as allauth_settings |
| 12 |
|
| 13 |
|
| 14 |
if not allauth_settings.MFA_ENABLED: |
| 15 |
raise ImproperlyConfigured( |
| 16 |
"allauth.mfa not installed, yet its models are imported." |
| 17 |
) |
| 18 |
|
| 19 |
|
| 20 |
class AuthenticatorManager(models.Manager): |
| 21 |
pass |
| 22 |
|
| 23 |
|
| 24 |
class Authenticator(models.Model): |
| 25 |
class Type(models.TextChoices): |
| 26 |
RECOVERY_CODES = "recovery_codes", _("Recovery codes") |
| 27 |
TOTP = "totp", _("TOTP Authenticator") |
| 28 |
WEBAUTHN = "webauthn", _("WebAuthn") |
| 29 |
|
| 30 |
objects = AuthenticatorManager() |
| 31 |
|
| 32 |
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) |
| 33 |
type = models.CharField(max_length=20, choices=Type.choices) |
| 34 |
data = models.JSONField() |
| 35 |
created_at = models.DateTimeField(default=timezone.now) |
| 36 |
last_used_at = models.DateTimeField(null=True) |
| 37 |
|
| 38 |
class Meta: |
| 39 |
constraints = [ |
| 40 |
UniqueConstraint( |
| 41 |
fields=["user", "type"], |
| 42 |
name="unique_authenticator_type", |
| 43 |
condition=Q( |
| 44 |
type__in=( |
| 45 |
"totp", |
| 46 |
"recovery_codes", |
| 47 |
) |
| 48 |
), |
| 49 |
) |
| 50 |
] |
| 51 |
|
| 52 |
def __str__(self) -> str: |
| 53 |
if self.type == self.Type.WEBAUTHN: |
| 54 |
return self.wrap().name |
| 55 |
return self.get_type_display() |
| 56 |
|
| 57 |
def wrap(self): |
| 58 |
from allauth.mfa.recovery_codes.internal.auth import RecoveryCodes |
| 59 |
from allauth.mfa.totp.internal.auth import TOTP |
| 60 |
from allauth.mfa.webauthn.internal.auth import WebAuthn |
| 61 |
|
| 62 |
return { |
| 63 |
self.Type.TOTP: TOTP, |
| 64 |
self.Type.RECOVERY_CODES: RecoveryCodes, |
| 65 |
self.Type.WEBAUTHN: WebAuthn, |
| 66 |
}[self.type](self) |
| 67 |
|
| 68 |
def record_usage(self) -> None: |
| 69 |
self.last_used_at = timezone.now() |
| 70 |
self.save(update_fields=["last_used_at"]) |