2017-03-07 17:17:39 -05:00
|
|
|
import binascii
|
|
|
|
import os
|
|
|
|
|
|
|
|
from django.contrib.auth.models import User
|
2017-03-08 11:34:47 -05:00
|
|
|
from django.core.validators import MinLengthValidator
|
2017-03-07 17:17:39 -05:00
|
|
|
from django.db import models
|
2017-03-07 23:30:31 -05:00
|
|
|
from django.utils import timezone
|
2017-03-07 17:17:39 -05:00
|
|
|
|
|
|
|
|
|
|
|
class Token(models.Model):
|
|
|
|
"""
|
|
|
|
An API token used for user authentication. This extends the stock model to allow each user to have multiple tokens.
|
|
|
|
It also supports setting an expiration time and toggling write ability.
|
|
|
|
"""
|
2018-03-30 13:57:26 -04:00
|
|
|
user = models.ForeignKey(
|
|
|
|
to=User,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name='tokens'
|
|
|
|
)
|
|
|
|
created = models.DateTimeField(
|
|
|
|
auto_now_add=True
|
|
|
|
)
|
|
|
|
expires = models.DateTimeField(
|
|
|
|
blank=True,
|
|
|
|
null=True
|
|
|
|
)
|
|
|
|
key = models.CharField(
|
|
|
|
max_length=40,
|
|
|
|
unique=True,
|
|
|
|
validators=[MinLengthValidator(40)]
|
|
|
|
)
|
|
|
|
write_enabled = models.BooleanField(
|
|
|
|
default=True,
|
|
|
|
help_text='Permit create/update/delete operations using this key'
|
|
|
|
)
|
|
|
|
description = models.CharField(
|
|
|
|
max_length=100,
|
|
|
|
blank=True
|
|
|
|
)
|
2017-03-07 17:17:39 -05:00
|
|
|
|
2017-03-07 22:40:05 -05:00
|
|
|
class Meta:
|
2018-10-05 11:06:59 -04:00
|
|
|
pass
|
2017-03-07 22:40:05 -05:00
|
|
|
|
2017-03-07 17:17:39 -05:00
|
|
|
def __str__(self):
|
2017-03-08 11:34:47 -05:00
|
|
|
# Only display the last 24 bits of the token to avoid accidental exposure.
|
2017-05-24 11:33:11 -04:00
|
|
|
return "{} ({})".format(self.key[-6:], self.user)
|
2017-03-07 17:17:39 -05:00
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
if not self.key:
|
|
|
|
self.key = self.generate_key()
|
2018-11-27 10:52:24 -05:00
|
|
|
return super().save(*args, **kwargs)
|
2017-03-07 17:17:39 -05:00
|
|
|
|
|
|
|
def generate_key(self):
|
2017-03-07 22:56:29 -05:00
|
|
|
# Generate a random 160-bit key expressed in hexadecimal.
|
|
|
|
return binascii.hexlify(os.urandom(20)).decode()
|
2017-03-07 23:30:31 -05:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_expired(self):
|
2017-03-31 11:13:37 -04:00
|
|
|
if self.expires is None or timezone.now() < self.expires:
|
|
|
|
return False
|
|
|
|
return True
|