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