model_forms.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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.tables.striping',
  55. name=_('User Interface')
  56. ),
  57. FieldSet('data_format', 'csv_delimiter', name=_('Miscellaneous')),
  58. )
  59. # List of clearable preferences
  60. pk = forms.MultipleChoiceField(
  61. choices=[],
  62. required=False
  63. )
  64. class Meta:
  65. model = UserConfig
  66. fields = ()
  67. def __init__(self, *args, instance=None, **kwargs):
  68. # Get initial data from UserConfig instance
  69. initial_data = flatten_dict(instance.data)
  70. kwargs['initial'] = initial_data
  71. super().__init__(*args, instance=instance, **kwargs)
  72. # Compile clearable preference choices
  73. self.fields['pk'].choices = (
  74. (f'tables.{table_name}', '') for table_name in instance.data.get('tables', [])
  75. )
  76. def save(self, *args, **kwargs):
  77. # Set UserConfig data
  78. for pref_name, value in self.cleaned_data.items():
  79. if pref_name == 'pk':
  80. continue
  81. self.instance.set(pref_name, value, commit=False)
  82. # Clear selected preferences
  83. for preference in self.cleaned_data['pk']:
  84. self.instance.clear(preference)
  85. return super().save(*args, **kwargs)
  86. @property
  87. def plugin_fields(self):
  88. return [
  89. name for name in self.fields.keys() if name.startswith('plugins.')
  90. ]
  91. class UserTokenForm(forms.ModelForm):
  92. token = forms.CharField(
  93. label=_('Token'),
  94. help_text=_(
  95. 'Tokens must be at least 40 characters in length. <strong>Be sure to record your key</strong> prior to '
  96. 'submitting this form, as it may no longer be accessible once the token has been created.'
  97. ),
  98. widget=forms.TextInput(
  99. attrs={'data-clipboard': 'true'}
  100. )
  101. )
  102. allowed_ips = SimpleArrayField(
  103. base_field=IPNetworkFormField(validators=[prefix_validator]),
  104. required=False,
  105. label=_('Allowed IPs'),
  106. help_text=_(
  107. 'Allowed IPv4/IPv6 networks from where the token can be used. Leave blank for no restrictions. '
  108. 'Example: <code>10.1.1.0/24,192.168.10.16/32,2001:db8:1::/64</code>'
  109. ),
  110. )
  111. class Meta:
  112. model = Token
  113. fields = [
  114. 'version', 'token', 'write_enabled', 'expires', 'description', 'allowed_ips',
  115. ]
  116. widgets = {
  117. 'expires': DateTimePicker(),
  118. }
  119. def __init__(self, *args, **kwargs):
  120. super().__init__(*args, **kwargs)
  121. if self.instance.pk:
  122. # Disable the version & user fields for existing Tokens
  123. self.fields['version'].disabled = True
  124. self.fields['user'].disabled = True
  125. # Omit the key field when editing an existing token if token retrieval is not permitted
  126. if self.instance.v1 and settings.ALLOW_TOKEN_RETRIEVAL:
  127. self.initial['token'] = self.instance.plaintext
  128. else:
  129. del self.fields['token']
  130. # Generate an initial random key if none has been specified
  131. elif self.instance._state.adding and not self.initial.get('token'):
  132. self.initial['version'] = TokenVersionChoices.V2
  133. self.initial['token'] = Token.generate()
  134. def save(self, commit=True):
  135. if self.instance._state.adding and self.cleaned_data.get('token'):
  136. self.instance.token = self.cleaned_data['token']
  137. return super().save(commit=commit)
  138. class TokenForm(UserTokenForm):
  139. user = forms.ModelChoiceField(
  140. queryset=User.objects.order_by('username'),
  141. label=_('User')
  142. )
  143. class Meta(UserTokenForm.Meta):
  144. fields = [
  145. 'version', 'token', 'user', 'write_enabled', 'expires', 'description', 'allowed_ips',
  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_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_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. if cloned_actions := self.initial['actions']:
  314. for action in ['view', 'add', 'change', 'delete']:
  315. if action in cloned_actions:
  316. self.fields[f'can_{action}'].initial = True
  317. self.initial['actions'].remove(action)
  318. # Convert data delivered via initial data to JSON data
  319. if 'constraints' in self.initial:
  320. if type(self.initial['constraints']) is str:
  321. self.initial['constraints'] = json.loads(self.initial['constraints'])
  322. def clean(self):
  323. super().clean()
  324. object_types = self.cleaned_data.get('object_types')
  325. constraints = self.cleaned_data.get('constraints')
  326. # Append any of the selected CRUD checkboxes to the actions list
  327. if not self.cleaned_data.get('actions'):
  328. self.cleaned_data['actions'] = list()
  329. for action in ['view', 'add', 'change', 'delete']:
  330. if self.cleaned_data[f'can_{action}'] and action not in self.cleaned_data['actions']:
  331. self.cleaned_data['actions'].append(action)
  332. # At least one action must be specified
  333. if not self.cleaned_data['actions']:
  334. raise forms.ValidationError(_("At least one action must be selected."))
  335. # Validate the specified model constraints by attempting to execute a query. We don't care whether the query
  336. # returns anything; we just want to make sure the specified constraints are valid.
  337. if object_types and constraints:
  338. # Normalize the constraints to a list of dicts
  339. if type(constraints) is not list:
  340. constraints = [constraints]
  341. for ct in object_types:
  342. model = ct.model_class()
  343. try:
  344. tokens = {
  345. CONSTRAINT_TOKEN_USER: 0, # Replace token with a null user ID
  346. }
  347. model.objects.filter(qs_filter_from_constraints(constraints, tokens)).exists()
  348. except (FieldError, ValueError) as e:
  349. raise forms.ValidationError({
  350. 'constraints': _('Invalid filter for {model}: {error}').format(model=model, error=e)
  351. })
  352. def save(self, *args, **kwargs):
  353. instance = super().save(*args, **kwargs)
  354. # Update assigned users and groups
  355. instance.users.set(self.cleaned_data['users'])
  356. instance.groups.set(self.cleaned_data['groups'])
  357. return instance