model_forms.py 15 KB

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