from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from uuid import uuid4 from pyotp import TOTP from dbsettings.functions import getValue from ..managers import UserManager class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', unique=True) totp = models.CharField('TOTP secret', max_length=40, null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Profile(models.Model): user = models.OneToOneField(User, models.CASCADE) first_name = models.CharField(max_length=128, null=True, blank=True) last_name = models.CharField(max_length=128, null=True, blank=True) def get_full_name(self): return f"{self.first_name or ''} {self.last_name or ''}" __str__ = get_full_name class OTPSession(models.Model): uuid = models.UUIDField(default=uuid4) user = models.ForeignKey(User, models.CASCADE) created = models.DateTimeField(auto_now_add=True) def is_alive(self): timeout = int(getValue("totp.timeout", 300)) return (timezone.now() - self.created).total_seconds() <= timeout def validate_token(self, token): totp = TOTP(self.user.totp) return totp.verify(token)