models.py
1 from django.db import models 2 import secrets 3 4 5 def _gen_token(): 6 return secrets.token_urlsafe(32) 7 8 9 class AccessToken(models.Model): 10 """A token that grants access to a protected URL path. 11 12 Tokens are generated automatically using ``secrets.token_urlsafe(32)``. 13 They can be constrained by expiration time (``expires_at``) and usage 14 count (``max_uses``), and revoked by setting ``is_valid`` to ``False``. 15 """ 16 17 description = models.CharField(max_length=255, null=False, blank=False) 18 path = models.CharField(max_length=255, null=False, blank=False) 19 token = models.CharField(max_length=64, default=_gen_token, null=False, unique=True) 20 21 is_valid = models.BooleanField(default=True) 22 expires_at = models.DateTimeField(null=True, blank=True) 23 max_uses = models.PositiveIntegerField(null=True, blank=True) 24 25 created_at = models.DateTimeField(auto_now_add=True, null=False, blank=False) 26 times_accessed = models.IntegerField(default=0) 27 last_accessed = models.DateTimeField(null=True, blank=True) 28 29 def __str__(self): 30 return f"{self.description} ({self.path})" 31 32 def __repr__(self): 33 return f"<AccessToken: {self.description} ({self.path})>" 34