model_forms.py 15 KB

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