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 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)