models.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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.config import get_config
  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. try:
  66. for key in keys:
  67. d = d[key]
  68. return d
  69. except (TypeError, KeyError):
  70. pass
  71. # If the key is not found in the user's config, check for an application-wide default
  72. config = get_config()
  73. d = config.DEFAULT_USER_PREFERENCES
  74. try:
  75. for key in keys:
  76. d = d[key]
  77. return d
  78. except (TypeError, KeyError):
  79. pass
  80. # Finally, return the specified default value (if any)
  81. return default
  82. def all(self):
  83. """
  84. Return a dictionary of all defined keys and their values.
  85. """
  86. return flatten_dict(self.data)
  87. def set(self, path, value, commit=False):
  88. """
  89. Define or overwrite a configuration parameter. Example:
  90. userconfig.set('foo.bar.baz', 123)
  91. Leaf nodes (those which are not dictionaries of other nodes) cannot be overwritten as dictionaries. Similarly,
  92. branch nodes (dictionaries) cannot be overwritten as single values. (A TypeError exception will be raised.) In
  93. both cases, the existing key must first be cleared. This safeguard is in place to help avoid inadvertently
  94. overwriting the wrong key.
  95. :param path: Dotted path to the configuration key. For example, 'foo.bar' sets self.data['foo']['bar'].
  96. :param value: The value to be written. This can be any type supported by JSON.
  97. :param commit: If true, the UserConfig instance will be saved once the new value has been applied.
  98. """
  99. d = self.data
  100. keys = path.split('.')
  101. # Iterate through the hierarchy to find the key we're setting. Raise TypeError if we encounter any
  102. # interim leaf nodes (keys which do not contain dictionaries).
  103. for i, key in enumerate(keys[:-1]):
  104. if key in d and type(d[key]) is dict:
  105. d = d[key]
  106. elif key in d:
  107. err_path = '.'.join(path.split('.')[:i + 1])
  108. raise TypeError(f"Key '{err_path}' is a leaf node; cannot assign new keys")
  109. else:
  110. d = d.setdefault(key, {})
  111. # Set a key based on the last item in the path. Raise TypeError if attempting to overwrite a non-leaf node.
  112. key = keys[-1]
  113. if key in d and type(d[key]) is dict:
  114. raise TypeError(f"Key '{path}' has child keys; cannot assign a value")
  115. else:
  116. d[key] = value
  117. if commit:
  118. self.save()
  119. def clear(self, path, commit=False):
  120. """
  121. Delete a configuration parameter specified by its dotted path. The key and any child keys will be deleted.
  122. Example:
  123. userconfig.clear('foo.bar.baz')
  124. Invalid keys will be ignored silently.
  125. :param path: Dotted path to the configuration key. For example, 'foo.bar' deletes self.data['foo']['bar'].
  126. :param commit: If true, the UserConfig instance will be saved once the new value has been applied.
  127. """
  128. d = self.data
  129. keys = path.split('.')
  130. for key in keys[:-1]:
  131. if key not in d:
  132. break
  133. if type(d[key]) is dict:
  134. d = d[key]
  135. key = keys[-1]
  136. d.pop(key, None) # Avoid a KeyError on invalid keys
  137. if commit:
  138. self.save()
  139. @receiver(post_save, sender=User)
  140. def create_userconfig(instance, created, raw=False, **kwargs):
  141. """
  142. Automatically create a new UserConfig when a new User is created. Skip this if importing a user from a fixture.
  143. """
  144. if created and not raw:
  145. config = get_config()
  146. UserConfig(user=instance, data=config.DEFAULT_USER_PREFERENCES).save()
  147. #
  148. # REST API
  149. #
  150. class Token(models.Model):
  151. """
  152. An API token used for user authentication. This extends the stock model to allow each user to have multiple tokens.
  153. It also supports setting an expiration time and toggling write ability.
  154. """
  155. user = models.ForeignKey(
  156. to=User,
  157. on_delete=models.CASCADE,
  158. related_name='tokens'
  159. )
  160. created = models.DateTimeField(
  161. auto_now_add=True
  162. )
  163. expires = models.DateTimeField(
  164. blank=True,
  165. null=True
  166. )
  167. key = models.CharField(
  168. max_length=40,
  169. unique=True,
  170. validators=[MinLengthValidator(40)]
  171. )
  172. write_enabled = models.BooleanField(
  173. default=True,
  174. help_text='Permit create/update/delete operations using this key'
  175. )
  176. description = models.CharField(
  177. max_length=200,
  178. blank=True
  179. )
  180. class Meta:
  181. pass
  182. def __str__(self):
  183. # Only display the last 24 bits of the token to avoid accidental exposure.
  184. return f"{self.key[-6:]} ({self.user})"
  185. def save(self, *args, **kwargs):
  186. if not self.key:
  187. self.key = self.generate_key()
  188. return super().save(*args, **kwargs)
  189. @staticmethod
  190. def generate_key():
  191. # Generate a random 160-bit key expressed in hexadecimal.
  192. return binascii.hexlify(os.urandom(20)).decode()
  193. @property
  194. def is_expired(self):
  195. if self.expires is None or timezone.now() < self.expires:
  196. return False
  197. return True
  198. #
  199. # Permissions
  200. #
  201. class ObjectPermission(models.Model):
  202. """
  203. A mapping of view, add, change, and/or delete permission for users and/or groups to an arbitrary set of objects
  204. identified by ORM query parameters.
  205. """
  206. name = models.CharField(
  207. max_length=100
  208. )
  209. description = models.CharField(
  210. max_length=200,
  211. blank=True
  212. )
  213. enabled = models.BooleanField(
  214. default=True
  215. )
  216. object_types = models.ManyToManyField(
  217. to=ContentType,
  218. limit_choices_to=OBJECTPERMISSION_OBJECT_TYPES,
  219. related_name='object_permissions'
  220. )
  221. groups = models.ManyToManyField(
  222. to=Group,
  223. blank=True,
  224. related_name='object_permissions'
  225. )
  226. users = models.ManyToManyField(
  227. to=User,
  228. blank=True,
  229. related_name='object_permissions'
  230. )
  231. actions = ArrayField(
  232. base_field=models.CharField(max_length=30),
  233. help_text="The list of actions granted by this permission"
  234. )
  235. constraints = models.JSONField(
  236. blank=True,
  237. null=True,
  238. help_text="Queryset filter matching the applicable objects of the selected type(s)"
  239. )
  240. objects = RestrictedQuerySet.as_manager()
  241. class Meta:
  242. ordering = ['name']
  243. verbose_name = "permission"
  244. def __str__(self):
  245. return self.name
  246. def list_constraints(self):
  247. """
  248. Return all constraint sets as a list (even if only a single set is defined).
  249. """
  250. if type(self.constraints) is not list:
  251. return [self.constraints]
  252. return self.constraints