model_forms.py 17 KB

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