model_forms.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import json
  2. from collections import defaultdict
  3. from django import forms
  4. from django.apps import apps
  5. from django.contrib.auth import password_validation
  6. from django.contrib.postgres.forms import SimpleArrayField
  7. from django.core.exceptions import FieldError
  8. from django.utils.safestring import mark_safe
  9. from django.utils.translation import gettext_lazy as _
  10. from core.models import ObjectType
  11. from ipam.formfields import IPNetworkFormField
  12. from ipam.validators import prefix_validator
  13. from netbox.config import get_config
  14. from netbox.preferences import PREFERENCES
  15. from users.choices import TokenVersionChoices
  16. from users.constants import *
  17. from users.models import *
  18. from utilities.data import flatten_dict
  19. from utilities.forms.fields import (
  20. ContentTypeMultipleChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, JSONField,
  21. )
  22. from utilities.forms.rendering import FieldSet
  23. from utilities.forms.widgets import DateTimePicker, SplitMultiSelectWidget
  24. from utilities.permissions import qs_filter_from_constraints
  25. from utilities.string import title
  26. __all__ = (
  27. 'GroupForm',
  28. 'ObjectPermissionForm',
  29. 'OwnerForm',
  30. 'OwnerGroupForm',
  31. 'TokenForm',
  32. 'UserConfigForm',
  33. 'UserForm',
  34. 'UserTokenForm',
  35. )
  36. class UserConfigFormMetaclass(forms.models.ModelFormMetaclass):
  37. def __new__(mcs, name, bases, attrs):
  38. # Emulate a declared field for each supported user preference
  39. preference_fields = {}
  40. for field_name, preference in PREFERENCES.items():
  41. help_text = f'<code>{field_name}</code>'
  42. if preference.description:
  43. help_text = f'{preference.description}<br />{help_text}'
  44. if warning := preference.warning:
  45. help_text = f'<span class="text-danger"><i class="mdi mdi-alert"></i> {warning}</span><br />{help_text}'
  46. field_kwargs = {
  47. 'label': preference.label,
  48. 'choices': preference.choices,
  49. 'help_text': mark_safe(help_text),
  50. 'coerce': preference.coerce,
  51. 'required': False,
  52. 'widget': forms.Select,
  53. }
  54. preference_fields[field_name] = forms.TypedChoiceField(**field_kwargs)
  55. attrs.update(preference_fields)
  56. return super().__new__(mcs, name, bases, attrs)
  57. class UserConfigForm(forms.ModelForm, metaclass=UserConfigFormMetaclass):
  58. fieldsets = (
  59. FieldSet(
  60. 'locale.language', 'ui.copilot_enabled', 'pagination.per_page', 'pagination.placement',
  61. 'ui.tables.striping', name=_('User Interface')
  62. ),
  63. FieldSet('data_format', 'csv_delimiter', name=_('Miscellaneous')),
  64. )
  65. # List of clearable preferences
  66. pk = forms.MultipleChoiceField(
  67. choices=[],
  68. required=False
  69. )
  70. class Meta:
  71. model = UserConfig
  72. fields = ()
  73. def __init__(self, *args, instance=None, **kwargs):
  74. # Get initial data from UserConfig instance
  75. kwargs['initial'] = flatten_dict(instance.data)
  76. super().__init__(*args, instance=instance, **kwargs)
  77. # Compile clearable preference choices
  78. self.fields['pk'].choices = (
  79. (f'tables.{table_name}', '') for table_name in instance.data.get('tables', [])
  80. )
  81. # Disable Copilot preference if it has been disabled globally
  82. if not get_config().COPILOT_ENABLED:
  83. self.fields['ui.copilot_enabled'].disabled = True
  84. def save(self, *args, **kwargs):
  85. # Set UserConfig data
  86. for pref_name, value in self.cleaned_data.items():
  87. if pref_name == 'pk':
  88. continue
  89. self.instance.set(pref_name, value, commit=False)
  90. # Clear selected preferences
  91. for preference in self.cleaned_data['pk']:
  92. self.instance.clear(preference)
  93. return super().save(*args, **kwargs)
  94. @property
  95. def plugin_fields(self):
  96. return [
  97. name for name in self.fields.keys() if name.startswith('plugins.')
  98. ]
  99. class UserTokenForm(forms.ModelForm):
  100. token = forms.CharField(
  101. label=_('Token'),
  102. help_text=_(
  103. 'Tokens must be at least 40 characters in length. <strong>Be sure to record your key</strong> prior to '
  104. 'submitting this form, as it will no longer be accessible once the token has been created.'
  105. ),
  106. widget=forms.TextInput(
  107. attrs={'data-clipboard': 'true'}
  108. )
  109. )
  110. allowed_ips = SimpleArrayField(
  111. base_field=IPNetworkFormField(validators=[prefix_validator]),
  112. required=False,
  113. label=_('Allowed IPs'),
  114. help_text=_(
  115. 'Allowed IPv4/IPv6 networks from where the token can be used. Leave blank for no restrictions. '
  116. 'Example: <code>10.1.1.0/24,192.168.10.16/32,2001:db8:1::/64</code>'
  117. ),
  118. )
  119. class Meta:
  120. model = Token
  121. fields = [
  122. 'version', 'token', 'enabled', 'write_enabled', 'expires', 'description', 'allowed_ips',
  123. ]
  124. widgets = {
  125. 'expires': DateTimePicker(),
  126. }
  127. def __init__(self, *args, **kwargs):
  128. super().__init__(*args, **kwargs)
  129. if self.instance.pk:
  130. # Disable the version & user fields for existing Tokens
  131. self.fields['version'].disabled = True
  132. self.fields['user'].disabled = True
  133. # Omit the key field when editing an existing Token
  134. del self.fields['token']
  135. # Generate an initial random key if none has been specified
  136. elif self.instance._state.adding and not self.initial.get('token'):
  137. self.initial['version'] = TokenVersionChoices.V2
  138. self.initial['token'] = Token.generate()
  139. def save(self, commit=True):
  140. if self.instance._state.adding and self.cleaned_data.get('token'):
  141. self.instance.token = self.cleaned_data['token']
  142. return super().save(commit=commit)
  143. class TokenForm(UserTokenForm):
  144. user = forms.ModelChoiceField(
  145. queryset=User.objects.order_by('username'),
  146. label=_('User')
  147. )
  148. class Meta(UserTokenForm.Meta):
  149. fields = [
  150. 'version', 'token', 'user', 'enabled', 'write_enabled', 'expires', 'description', 'allowed_ips',
  151. ]
  152. def __init__(self, *args, **kwargs):
  153. super().__init__(*args, **kwargs)
  154. # If not creating a new Token, disable the user field
  155. if self.instance and not self.instance._state.adding:
  156. self.fields['user'].disabled = True
  157. class UserForm(forms.ModelForm):
  158. password = forms.CharField(
  159. label=_('Password'),
  160. widget=forms.PasswordInput(),
  161. required=True,
  162. )
  163. confirm_password = forms.CharField(
  164. label=_('Confirm password'),
  165. widget=forms.PasswordInput(),
  166. required=True,
  167. help_text=_("Enter the same password as before, for verification."),
  168. )
  169. groups = DynamicModelMultipleChoiceField(
  170. label=_('Groups'),
  171. required=False,
  172. queryset=Group.objects.all()
  173. )
  174. object_permissions = DynamicModelMultipleChoiceField(
  175. required=False,
  176. label=_('Permissions'),
  177. queryset=ObjectPermission.objects.all()
  178. )
  179. fieldsets = (
  180. FieldSet('username', 'password', 'confirm_password', 'first_name', 'last_name', 'email', name=_('User')),
  181. FieldSet('groups', name=_('Groups')),
  182. FieldSet('is_active', 'is_superuser', name=_('Status')),
  183. FieldSet('object_permissions', name=_('Permissions')),
  184. )
  185. class Meta:
  186. model = User
  187. fields = [
  188. 'username', 'first_name', 'last_name', 'email', 'groups', 'object_permissions',
  189. 'is_active', 'is_superuser',
  190. ]
  191. def __init__(self, *args, **kwargs):
  192. super().__init__(*args, **kwargs)
  193. if self.instance.pk:
  194. # Password fields are optional for existing Users
  195. self.fields['password'].required = False
  196. self.fields['confirm_password'].required = False
  197. def save(self, *args, **kwargs):
  198. instance = super().save(*args, **kwargs)
  199. # On edit, check if we have to save the password
  200. if self.cleaned_data.get('password'):
  201. instance.set_password(self.cleaned_data.get('password'))
  202. instance.save()
  203. return instance
  204. def clean(self):
  205. # Check that password confirmation matches if password is set
  206. if self.cleaned_data['password'] and self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
  207. raise forms.ValidationError(_("Passwords do not match! Please check your input and try again."))
  208. # Enforce password validation rules (if configured)
  209. if self.cleaned_data['password']:
  210. password_validation.validate_password(self.cleaned_data['password'], self.instance)
  211. class GroupForm(forms.ModelForm):
  212. users = DynamicModelMultipleChoiceField(
  213. label=_('Users'),
  214. required=False,
  215. queryset=User.objects.all()
  216. )
  217. object_permissions = DynamicModelMultipleChoiceField(
  218. required=False,
  219. label=_('Permissions'),
  220. queryset=ObjectPermission.objects.all()
  221. )
  222. fieldsets = (
  223. FieldSet('name', 'description'),
  224. FieldSet('users', name=_('Users')),
  225. FieldSet('object_permissions', name=_('Permissions')),
  226. )
  227. class Meta:
  228. model = Group
  229. fields = [
  230. 'name', 'description', 'users', 'object_permissions',
  231. ]
  232. def __init__(self, *args, **kwargs):
  233. super().__init__(*args, **kwargs)
  234. # Populate assigned users and permissions
  235. if self.instance.pk:
  236. self.fields['users'].initial = self.instance.users.values_list('id', flat=True)
  237. def save(self, *args, **kwargs):
  238. instance = super().save(*args, **kwargs)
  239. # Update assigned users
  240. instance.users.set(self.cleaned_data['users'])
  241. return instance
  242. def get_object_types_choices():
  243. """
  244. Generate choices for object types grouped by app label using optgroups.
  245. Returns nested structure: [(app_label, [(id, model_name), ...]), ...]
  246. """
  247. app_label_map = {
  248. app_config.label: app_config.verbose_name
  249. for app_config in apps.get_app_configs()
  250. }
  251. choices_by_app = defaultdict(list)
  252. for ot in ObjectType.objects.filter(OBJECTPERMISSION_OBJECT_TYPES).order_by('app_label', 'model'):
  253. app_label = app_label_map.get(ot.app_label, ot.app_label)
  254. model_class = ot.model_class()
  255. model_name = model_class._meta.verbose_name if model_class else ot.model
  256. choices_by_app[app_label].append((ot.pk, title(model_name)))
  257. return list(choices_by_app.items())
  258. class ObjectPermissionForm(forms.ModelForm):
  259. object_types = ContentTypeMultipleChoiceField(
  260. label=_('Object types'),
  261. queryset=ObjectType.objects.all(),
  262. widget=SplitMultiSelectWidget(
  263. choices=get_object_types_choices
  264. ),
  265. help_text=_('Select the types of objects to which the permission will appy.')
  266. )
  267. can_view = forms.BooleanField(
  268. required=False
  269. )
  270. can_add = forms.BooleanField(
  271. required=False
  272. )
  273. can_change = forms.BooleanField(
  274. required=False
  275. )
  276. can_delete = forms.BooleanField(
  277. required=False
  278. )
  279. actions = SimpleArrayField(
  280. label=_('Additional actions'),
  281. base_field=forms.CharField(),
  282. required=False,
  283. help_text=_('Actions granted in addition to those listed above')
  284. )
  285. users = DynamicModelMultipleChoiceField(
  286. label=_('Users'),
  287. required=False,
  288. queryset=User.objects.all()
  289. )
  290. groups = DynamicModelMultipleChoiceField(
  291. label=_('Groups'),
  292. required=False,
  293. queryset=Group.objects.all()
  294. )
  295. constraints = JSONField(
  296. required=False,
  297. label=_('Constraints'),
  298. help_text=_(
  299. 'JSON expression of a queryset filter that will return only permitted objects. Leave null '
  300. 'to match all objects of this type. A list of multiple objects will result in a logical OR '
  301. 'operation.'
  302. ),
  303. )
  304. fieldsets = (
  305. FieldSet('name', 'description', 'enabled'),
  306. FieldSet('can_view', 'can_add', 'can_change', 'can_delete', 'actions', name=_('Actions')),
  307. FieldSet('object_types', name=_('Objects')),
  308. FieldSet('groups', 'users', name=_('Assignment')),
  309. FieldSet('constraints', name=_('Constraints')),
  310. )
  311. class Meta:
  312. model = ObjectPermission
  313. fields = [
  314. 'name', 'description', 'enabled', 'object_types', 'users', 'groups', 'constraints', 'actions',
  315. ]
  316. def __init__(self, *args, **kwargs):
  317. super().__init__(*args, **kwargs)
  318. # Make the actions field optional since the form uses it only for non-CRUD actions
  319. self.fields['actions'].required = False
  320. # Prepare the appropriate fields when editing an existing ObjectPermission
  321. if self.instance.pk:
  322. # Populate assigned users and groups
  323. self.fields['groups'].initial = self.instance.groups.values_list('id', flat=True)
  324. self.fields['users'].initial = self.instance.users.values_list('id', flat=True)
  325. # Check the appropriate checkboxes when editing an existing ObjectPermission
  326. for action in ['view', 'add', 'change', 'delete']:
  327. if action in self.instance.actions:
  328. self.fields[f'can_{action}'].initial = True
  329. self.instance.actions.remove(action)
  330. # Populate initial data for a new ObjectPermission
  331. elif self.initial:
  332. # Handle cloned objects - actions come from initial data (URL parameters)
  333. if 'actions' in self.initial:
  334. # Normalize actions to a list of strings
  335. if isinstance(self.initial['actions'], str):
  336. self.initial['actions'] = [self.initial['actions']]
  337. if cloned_actions := self.initial['actions']:
  338. for action in ['view', 'add', 'change', 'delete']:
  339. if action in cloned_actions:
  340. self.fields[f'can_{action}'].initial = True
  341. self.initial['actions'].remove(action)
  342. # Convert data delivered via initial data to JSON data
  343. if 'constraints' in self.initial:
  344. if type(self.initial['constraints']) is str:
  345. self.initial['constraints'] = json.loads(self.initial['constraints'])
  346. def clean(self):
  347. super().clean()
  348. object_types = self.cleaned_data.get('object_types')
  349. constraints = self.cleaned_data.get('constraints')
  350. # Append any of the selected CRUD checkboxes to the actions list
  351. if not self.cleaned_data.get('actions'):
  352. self.cleaned_data['actions'] = list()
  353. for action in ['view', 'add', 'change', 'delete']:
  354. if self.cleaned_data[f'can_{action}'] and action not in self.cleaned_data['actions']:
  355. self.cleaned_data['actions'].append(action)
  356. # At least one action must be specified
  357. if not self.cleaned_data['actions']:
  358. raise forms.ValidationError(_("At least one action must be selected."))
  359. # Validate the specified model constraints by attempting to execute a query. We don't care whether the query
  360. # returns anything; we just want to make sure the specified constraints are valid.
  361. if object_types and constraints:
  362. # Normalize the constraints to a list of dicts
  363. if type(constraints) is not list:
  364. constraints = [constraints]
  365. for ct in object_types:
  366. model = ct.model_class()
  367. try:
  368. tokens = {
  369. CONSTRAINT_TOKEN_USER: 0, # Replace token with a null user ID
  370. }
  371. model.objects.filter(qs_filter_from_constraints(constraints, tokens)).exists()
  372. except (FieldError, ValueError) as e:
  373. raise forms.ValidationError({
  374. 'constraints': _('Invalid filter for {model}: {error}').format(model=model, error=e)
  375. })
  376. def save(self, *args, **kwargs):
  377. instance = super().save(*args, **kwargs)
  378. # Update assigned users and groups
  379. instance.users.set(self.cleaned_data['users'])
  380. instance.groups.set(self.cleaned_data['groups'])
  381. return instance
  382. class OwnerGroupForm(forms.ModelForm):
  383. fieldsets = (
  384. FieldSet('name', 'description', name=_('Owner Group')),
  385. )
  386. class Meta:
  387. model = OwnerGroup
  388. fields = [
  389. 'name', 'description',
  390. ]
  391. class OwnerForm(forms.ModelForm):
  392. fieldsets = (
  393. FieldSet('name', 'group', 'description', name=_('Owner')),
  394. FieldSet('user_groups', name=_('Groups')),
  395. FieldSet('users', name=_('Users')),
  396. )
  397. group = DynamicModelChoiceField(
  398. label=_('Group'),
  399. queryset=OwnerGroup.objects.all(),
  400. required=False,
  401. selector=True,
  402. quick_add=True
  403. )
  404. user_groups = DynamicModelMultipleChoiceField(
  405. label=_('User groups'),
  406. queryset=Group.objects.all(),
  407. required=False
  408. )
  409. users = DynamicModelMultipleChoiceField(
  410. label=_('Users'),
  411. queryset=User.objects.all(),
  412. required=False
  413. )
  414. class Meta:
  415. model = Owner
  416. fields = [
  417. 'name', 'group', 'description', 'user_groups', 'users',
  418. ]