model_forms.py 13 KB

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