model_forms.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. from django import forms
  2. from django.conf import settings
  3. from django.contrib.auth import get_user_model, password_validation
  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 warning := preference.warning:
  38. help_text = f'<span class="text-danger"><i class="mdi mdi-alert"></i> {warning}</span><br />{help_text}'
  39. field_kwargs = {
  40. 'label': preference.label,
  41. 'choices': preference.choices,
  42. 'help_text': mark_safe(help_text),
  43. 'coerce': preference.coerce,
  44. 'required': False,
  45. 'widget': forms.Select,
  46. }
  47. preference_fields[field_name] = forms.TypedChoiceField(**field_kwargs)
  48. attrs.update(preference_fields)
  49. return super().__new__(mcs, name, bases, attrs)
  50. class UserConfigForm(forms.ModelForm, metaclass=UserConfigFormMetaclass):
  51. fieldsets = (
  52. FieldSet(
  53. 'locale.language', 'pagination.per_page', 'pagination.placement', 'ui.htmx_navigation',
  54. name=_('User Interface')
  55. ),
  56. FieldSet('data_format', name=_('Miscellaneous')),
  57. )
  58. # List of clearable preferences
  59. pk = forms.MultipleChoiceField(
  60. choices=[],
  61. required=False
  62. )
  63. class Meta:
  64. model = UserConfig
  65. fields = ()
  66. def __init__(self, *args, instance=None, **kwargs):
  67. # Get initial data from UserConfig instance
  68. initial_data = flatten_dict(instance.data)
  69. kwargs['initial'] = initial_data
  70. super().__init__(*args, instance=instance, **kwargs)
  71. # Compile clearable preference choices
  72. self.fields['pk'].choices = (
  73. (f'tables.{table_name}', '') for table_name in instance.data.get('tables', [])
  74. )
  75. def save(self, *args, **kwargs):
  76. # Set UserConfig data
  77. for pref_name, value in self.cleaned_data.items():
  78. if pref_name == 'pk':
  79. continue
  80. self.instance.set(pref_name, value, commit=False)
  81. # Clear selected preferences
  82. for preference in self.cleaned_data['pk']:
  83. self.instance.clear(preference)
  84. return super().save(*args, **kwargs)
  85. @property
  86. def plugin_fields(self):
  87. return [
  88. name for name in self.fields.keys() if name.startswith('plugins.')
  89. ]
  90. class UserTokenForm(forms.ModelForm):
  91. key = forms.CharField(
  92. label=_('Key'),
  93. help_text=_(
  94. 'Keys must be at least 40 characters in length. <strong>Be sure to record your key</strong> prior to '
  95. 'submitting this form, as it may no longer be accessible once the token has been created.'
  96. ),
  97. widget=forms.TextInput(
  98. attrs={'data-clipboard': 'true'}
  99. )
  100. )
  101. allowed_ips = SimpleArrayField(
  102. base_field=IPNetworkFormField(validators=[prefix_validator]),
  103. required=False,
  104. label=_('Allowed IPs'),
  105. help_text=_(
  106. 'Allowed IPv4/IPv6 networks from where the token can be used. Leave blank for no restrictions. '
  107. 'Example: <code>10.1.1.0/24,192.168.10.16/32,2001:db8:1::/64</code>'
  108. ),
  109. )
  110. class Meta:
  111. model = Token
  112. fields = [
  113. 'key', 'write_enabled', 'expires', 'description', 'allowed_ips',
  114. ]
  115. widgets = {
  116. 'expires': DateTimePicker(),
  117. }
  118. def __init__(self, *args, **kwargs):
  119. super().__init__(*args, **kwargs)
  120. # Omit the key field if token retrieval is not permitted
  121. if self.instance.pk and not settings.ALLOW_TOKEN_RETRIEVAL:
  122. del self.fields['key']
  123. # Generate an initial random key if none has been specified
  124. if not self.instance.pk and not self.initial.get('key'):
  125. self.initial['key'] = Token.generate_key()
  126. class TokenForm(UserTokenForm):
  127. user = forms.ModelChoiceField(
  128. queryset=get_user_model().objects.order_by('username'),
  129. label=_('User')
  130. )
  131. class Meta:
  132. model = Token
  133. fields = [
  134. 'user', 'key', 'write_enabled', 'expires', 'description', 'allowed_ips',
  135. ]
  136. widgets = {
  137. 'expires': DateTimePicker(),
  138. }
  139. class UserForm(forms.ModelForm):
  140. password = forms.CharField(
  141. label=_('Password'),
  142. widget=forms.PasswordInput(),
  143. required=True,
  144. )
  145. confirm_password = forms.CharField(
  146. label=_('Confirm password'),
  147. widget=forms.PasswordInput(),
  148. required=True,
  149. help_text=_("Enter the same password as before, for verification."),
  150. )
  151. groups = DynamicModelMultipleChoiceField(
  152. label=_('Groups'),
  153. required=False,
  154. queryset=Group.objects.all()
  155. )
  156. object_permissions = DynamicModelMultipleChoiceField(
  157. required=False,
  158. label=_('Permissions'),
  159. queryset=ObjectPermission.objects.all()
  160. )
  161. fieldsets = (
  162. FieldSet('username', 'password', 'confirm_password', 'first_name', 'last_name', 'email', name=_('User')),
  163. FieldSet('groups', name=_('Groups')),
  164. FieldSet('is_active', 'is_staff', 'is_superuser', name=_('Status')),
  165. FieldSet('object_permissions', name=_('Permissions')),
  166. )
  167. class Meta:
  168. model = User
  169. fields = [
  170. 'username', 'first_name', 'last_name', 'email', 'groups', 'object_permissions',
  171. 'is_active', 'is_staff', 'is_superuser',
  172. ]
  173. def __init__(self, *args, **kwargs):
  174. super().__init__(*args, **kwargs)
  175. if self.instance.pk:
  176. # Password fields are optional for existing Users
  177. self.fields['password'].required = False
  178. self.fields['confirm_password'].required = False
  179. def save(self, *args, **kwargs):
  180. instance = super().save(*args, **kwargs)
  181. # On edit, check if we have to save the password
  182. if self.cleaned_data.get('password'):
  183. instance.set_password(self.cleaned_data.get('password'))
  184. instance.save()
  185. return instance
  186. def clean(self):
  187. # Check that password confirmation matches if password is set
  188. if self.cleaned_data['password'] and self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
  189. raise forms.ValidationError(_("Passwords do not match! Please check your input and try again."))
  190. # Enforce password validation rules (if configured)
  191. if self.cleaned_data['password']:
  192. password_validation.validate_password(self.cleaned_data['password'], self.instance)
  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