models.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import binascii
  2. import os
  3. from django.contrib.auth.models import User
  4. from django.contrib.postgres.fields import JSONField
  5. from django.core.validators import MinLengthValidator
  6. from django.db import models
  7. from django.db.models.signals import post_save
  8. from django.dispatch import receiver
  9. from django.utils import timezone
  10. from utilities.utils import flatten_dict
  11. __all__ = (
  12. 'Token',
  13. 'UserConfig',
  14. )
  15. class UserConfig(models.Model):
  16. """
  17. This model stores arbitrary user-specific preferences in a JSON data structure.
  18. """
  19. user = models.OneToOneField(
  20. to=User,
  21. on_delete=models.CASCADE,
  22. related_name='config'
  23. )
  24. data = JSONField(
  25. default=dict
  26. )
  27. class Meta:
  28. ordering = ['user']
  29. verbose_name = verbose_name_plural = 'User Preferences'
  30. def get(self, path, default=None):
  31. """
  32. Retrieve a configuration parameter specified by its dotted path. Example:
  33. userconfig.get('foo.bar.baz')
  34. :param path: Dotted path to the configuration key. For example, 'foo.bar' returns self.data['foo']['bar'].
  35. :param default: Default value to return for a nonexistent key (default: None).
  36. """
  37. d = self.data
  38. keys = path.split('.')
  39. # Iterate down the hierarchy, returning the default value if any invalid key is encountered
  40. for key in keys:
  41. if type(d) is dict:
  42. d = d.get(key)
  43. else:
  44. return default
  45. return d
  46. def all(self):
  47. """
  48. Return a dictionary of all defined keys and their values.
  49. """
  50. return flatten_dict(self.data)
  51. def set(self, path, value, commit=False):
  52. """
  53. Define or overwrite a configuration parameter. Example:
  54. userconfig.set('foo.bar.baz', 123)
  55. Leaf nodes (those which are not dictionaries of other nodes) cannot be overwritten as dictionaries. Similarly,
  56. branch nodes (dictionaries) cannot be overwritten as single values. (A TypeError exception will be raised.) In
  57. both cases, the existing key must first be cleared. This safeguard is in place to help avoid inadvertently
  58. overwriting the wrong key.
  59. :param path: Dotted path to the configuration key. For example, 'foo.bar' sets self.data['foo']['bar'].
  60. :param value: The value to be written. This can be any type supported by JSON.
  61. :param commit: If true, the UserConfig instance will be saved once the new value has been applied.
  62. """
  63. d = self.data
  64. keys = path.split('.')
  65. # Iterate through the hierarchy to find the key we're setting. Raise TypeError if we encounter any
  66. # interim leaf nodes (keys which do not contain dictionaries).
  67. for i, key in enumerate(keys[:-1]):
  68. if key in d and type(d[key]) is dict:
  69. d = d[key]
  70. elif key in d:
  71. err_path = '.'.join(path.split('.')[:i + 1])
  72. raise TypeError(f"Key '{err_path}' is a leaf node; cannot assign new keys")
  73. else:
  74. d = d.setdefault(key, {})
  75. # Set a key based on the last item in the path. Raise TypeError if attempting to overwrite a non-leaf node.
  76. key = keys[-1]
  77. if key in d and type(d[key]) is dict:
  78. raise TypeError(f"Key '{path}' has child keys; cannot assign a value")
  79. else:
  80. d[key] = value
  81. if commit:
  82. self.save()
  83. def clear(self, path, commit=False):
  84. """
  85. Delete a configuration parameter specified by its dotted path. The key and any child keys will be deleted.
  86. Example:
  87. userconfig.clear('foo.bar.baz')
  88. A KeyError is raised in the event any key along the path does not exist.
  89. :param path: Dotted path to the configuration key. For example, 'foo.bar' deletes self.data['foo']['bar'].
  90. :param commit: If true, the UserConfig instance will be saved once the new value has been applied.
  91. """
  92. d = self.data
  93. keys = path.split('.')
  94. for key in keys[:-1]:
  95. if key in d and type(d[key]) is dict:
  96. d = d[key]
  97. key = keys[-1]
  98. del(d[key])
  99. if commit:
  100. self.save()
  101. @receiver(post_save, sender=User)
  102. def create_userconfig(instance, created, **kwargs):
  103. """
  104. Automatically create a new UserConfig when a new User is created.
  105. """
  106. if created:
  107. UserConfig(user=instance).save()
  108. class Token(models.Model):
  109. """
  110. An API token used for user authentication. This extends the stock model to allow each user to have multiple tokens.
  111. It also supports setting an expiration time and toggling write ability.
  112. """
  113. user = models.ForeignKey(
  114. to=User,
  115. on_delete=models.CASCADE,
  116. related_name='tokens'
  117. )
  118. created = models.DateTimeField(
  119. auto_now_add=True
  120. )
  121. expires = models.DateTimeField(
  122. blank=True,
  123. null=True
  124. )
  125. key = models.CharField(
  126. max_length=40,
  127. unique=True,
  128. validators=[MinLengthValidator(40)]
  129. )
  130. write_enabled = models.BooleanField(
  131. default=True,
  132. help_text='Permit create/update/delete operations using this key'
  133. )
  134. description = models.CharField(
  135. max_length=200,
  136. blank=True
  137. )
  138. class Meta:
  139. pass
  140. def __str__(self):
  141. # Only display the last 24 bits of the token to avoid accidental exposure.
  142. return "{} ({})".format(self.key[-6:], self.user)
  143. def save(self, *args, **kwargs):
  144. if not self.key:
  145. self.key = self.generate_key()
  146. return super().save(*args, **kwargs)
  147. def generate_key(self):
  148. # Generate a random 160-bit key expressed in hexadecimal.
  149. return binascii.hexlify(os.urandom(20)).decode()
  150. @property
  151. def is_expired(self):
  152. if self.expires is None or timezone.now() < self.expires:
  153. return False
  154. return True