model_forms.py 20 KB

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