models.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import binascii
  2. import os
  3. from django.contrib.auth.models import Group, User
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.contrib.postgres.fields import ArrayField
  6. from django.core.validators import MinLengthValidator
  7. from django.db import models
  8. from django.db.models.signals import post_save
  9. from django.dispatch import receiver
  10. from django.utils import timezone
  11. from netbox.models import BigIDModel
  12. from utilities.querysets import RestrictedQuerySet
  13. from utilities.utils import flatten_dict
  14. from .constants import *
  15. __all__ = (
  16. 'ObjectPermission',
  17. 'Token',
  18. 'UserConfig',
  19. )
  20. #
  21. # Proxy models for admin
  22. #
  23. class AdminGroup(Group):
  24. """
  25. Proxy contrib.auth.models.Group for the admin UI
  26. """
  27. class Meta:
  28. verbose_name = 'Group'
  29. proxy = True
  30. class AdminUser(User):
  31. """
  32. Proxy contrib.auth.models.User for the admin UI
  33. """
  34. class Meta:
  35. verbose_name = 'User'
  36. proxy = True
  37. #
  38. # User preferences
  39. #
  40. class UserConfig(models.Model):
  41. """
  42. This model stores arbitrary user-specific preferences in a JSON data structure.
  43. """
  44. user = models.OneToOneField(
  45. to=User,
  46. on_delete=models.CASCADE,
  47. related_name='config'
  48. )
  49. data = models.JSONField(
  50. default=dict
  51. )
  52. class Meta:
  53. ordering = ['user']
  54. verbose_name = verbose_name_plural = 'User Preferences'
  55. def get(self, path, default=None):
  56. """
  57. Retrieve a configuration parameter specified by its dotted path. Example:
  58. userconfig.get('foo.bar.baz')
  59. :param path: Dotted path to the configuration key. For example, 'foo.bar' returns self.data['foo']['bar'].
  60. :param default: Default value to return for a nonexistent key (default: None).
  61. """
  62. d = self.data
  63. keys = path.split('.')
  64. # Iterate down the hierarchy, returning the default value if any invalid key is encountered
  65. for key in keys:
  66. if type(d) is dict and key in d:
  67. d = d.get(key)
  68. else:
  69. return default
  70. return d
  71. def all(self):
  72. """
  73. Return a dictionary of all defined keys and their values.
  74. """
  75. return flatten_dict(self.data)
  76. def set(self, path, value, commit=False):
  77. """
  78. Define or overwrite a configuration parameter. Example:
  79. userconfig.set('foo.bar.baz', 123)
  80. Leaf nodes (those which are not dictionaries of other nodes) cannot be overwritten as dictionaries. Similarly,
  81. branch nodes (dictionaries) cannot be overwritten as single values. (A TypeError exception will be raised.) In
  82. both cases, the existing key must first be cleared. This safeguard is in place to help avoid inadvertently
  83. overwriting the wrong key.
  84. :param path: Dotted path to the configuration key. For example, 'foo.bar' sets self.data['foo']['bar'].
  85. :param value: The value to be written. This can be any type supported by JSON.
  86. :param commit: If true, the UserConfig instance will be saved once the new value has been applied.
  87. """
  88. d = self.data
  89. keys = path.split('.')
  90. # Iterate through the hierarchy to find the key we're setting. Raise TypeError if we encounter any
  91. # interim leaf nodes (keys which do not contain dictionaries).
  92. for i, key in enumerate(keys[:-1]):
  93. if key in d and type(d[key]) is dict:
  94. d = d[key]
  95. elif key in d:
  96. err_path = '.'.join(path.split('.')[:i + 1])
  97. raise TypeError(f"Key '{err_path}' is a leaf node; cannot assign new keys")
  98. else:
  99. d = d.setdefault(key, {})
  100. # Set a key based on the last item in the path. Raise TypeError if attempting to overwrite a non-leaf node.
  101. key = keys[-1]
  102. if key in d and type(d[key]) is dict:
  103. raise TypeError(f"Key '{path}' has child keys; cannot assign a value")
  104. else:
  105. d[key] = value
  106. if commit:
  107. self.save()
  108. def clear(self, path, commit=False):
  109. """
  110. Delete a configuration parameter specified by its dotted path. The key and any child keys will be deleted.
  111. Example:
  112. userconfig.clear('foo.bar.baz')
  113. Invalid keys will be ignored silently.
  114. :param path: Dotted path to the configuration key. For example, 'foo.bar' deletes self.data['foo']['bar'].
  115. :param commit: If true, the UserConfig instance will be saved once the new value has been applied.
  116. """
  117. d = self.data
  118. keys = path.split('.')
  119. for key in keys[:-1]:
  120. if key not in d:
  121. break
  122. if type(d[key]) is dict:
  123. d = d[key]
  124. key = keys[-1]
  125. d.pop(key, None) # Avoid a KeyError on invalid keys
  126. if commit:
  127. self.save()
  128. @receiver(post_save, sender=User)
  129. def create_userconfig(instance, created, **kwargs):
  130. """
  131. Automatically create a new UserConfig when a new User is created.
  132. """
  133. if created:
  134. UserConfig(user=instance).save()
  135. #
  136. # REST API
  137. #
  138. class Token(BigIDModel):
  139. """
  140. An API token used for user authentication. This extends the stock model to allow each user to have multiple tokens.
  141. It also supports setting an expiration time and toggling write ability.
  142. """
  143. user = models.ForeignKey(
  144. to=User,
  145. on_delete=models.CASCADE,
  146. related_name='tokens'
  147. )
  148. created = models.DateTimeField(
  149. auto_now_add=True
  150. )
  151. expires = models.DateTimeField(
  152. blank=True,
  153. null=True
  154. )
  155. key = models.CharField(
  156. max_length=40,
  157. unique=True,
  158. validators=[MinLengthValidator(40)]
  159. )
  160. write_enabled = models.BooleanField(
  161. default=True,
  162. help_text='Permit create/update/delete operations using this key'
  163. )
  164. description = models.CharField(
  165. max_length=200,
  166. blank=True
  167. )
  168. class Meta:
  169. pass
  170. def __str__(self):
  171. # Only display the last 24 bits of the token to avoid accidental exposure.
  172. return f"{self.key[-6:]} ({self.user})"
  173. def save(self, *args, **kwargs):
  174. if not self.key:
  175. self.key = self.generate_key()
  176. return super().save(*args, **kwargs)
  177. @staticmethod
  178. def generate_key():
  179. # Generate a random 160-bit key expressed in hexadecimal.
  180. return binascii.hexlify(os.urandom(20)).decode()
  181. @property
  182. def is_expired(self):
  183. if self.expires is None or timezone.now() < self.expires:
  184. return False
  185. return True
  186. #
  187. # Permissions
  188. #
  189. class ObjectPermission(BigIDModel):
  190. """
  191. A mapping of view, add, change, and/or delete permission for users and/or groups to an arbitrary set of objects
  192. identified by ORM query parameters.
  193. """
  194. name = models.CharField(
  195. max_length=100
  196. )
  197. description = models.CharField(
  198. max_length=200,
  199. blank=True
  200. )
  201. enabled = models.BooleanField(
  202. default=True
  203. )
  204. object_types = models.ManyToManyField(
  205. to=ContentType,
  206. limit_choices_to=OBJECTPERMISSION_OBJECT_TYPES,
  207. related_name='object_permissions'
  208. )
  209. groups = models.ManyToManyField(
  210. to=Group,
  211. blank=True,
  212. related_name='object_permissions'
  213. )
  214. users = models.ManyToManyField(
  215. to=User,
  216. blank=True,
  217. related_name='object_permissions'
  218. )
  219. actions = ArrayField(
  220. base_field=models.CharField(max_length=30),
  221. help_text="The list of actions granted by this permission"
  222. )
  223. constraints = models.JSONField(
  224. blank=True,
  225. null=True,
  226. help_text="Queryset filter matching the applicable objects of the selected type(s)"
  227. )
  228. objects = RestrictedQuerySet.as_manager()
  229. class Meta:
  230. ordering = ['name']
  231. verbose_name = "permission"
  232. def __str__(self):
  233. return self.name
  234. def list_constraints(self):
  235. """
  236. Return all constraint sets as a list (even if only a single set is defined).
  237. """
  238. if type(self.constraints) is not list:
  239. return [self.constraints]
  240. return self.constraints