notify/notify/models/code.py

58 lines
1.9 KiB
Python

import uuid
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.crypto import constant_time_compare, salted_hmac
from notify.models.choices import DeliveryChannel
__all__ = [
"VerificationCode",
]
CODE_HASH_SALT = "notify.code"
class VerificationCode(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
null=True,
blank=True,
on_delete=models.CASCADE,
related_name="verification_codes",
)
purpose = models.CharField(max_length=100)
channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
target_key = models.CharField(max_length=255)
delivery_target = models.JSONField(null=True, blank=True, default=None)
code_hash = models.CharField(max_length=128)
expires_at = models.DateTimeField(db_index=True)
attempts = models.PositiveSmallIntegerField(default=0)
max_attempts = models.PositiveSmallIntegerField()
consumed_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ("-created_at",)
indexes = [
models.Index(fields=["purpose", "channel", "target_key", "created_at"], name="idx_code_lookup"),
]
def __str__(self):
return f"{self.purpose} via {self.channel} to {self.target_key}"
def _hash(self, code: str) -> str:
return salted_hmac(CODE_HASH_SALT, f"{self.id}:{code}", algorithm="sha256").hexdigest()
def set_code(self, code: str) -> None:
self.code_hash = self._hash(code)
def check_code(self, code: str) -> bool:
return constant_time_compare(self.code_hash, self._hash(code))
@property
def is_expired(self) -> bool:
return self.expires_at <= timezone.now()