From 41cc5e46af06291f7491155668230c04e7c76969 Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Tue, 17 Oct 2023 15:17:12 -0400 Subject: [PATCH] Merge actions and action_perms into a single mapping --- netbox/netbox/views/generic/mixins.py | 39 +++++++++++++++++++++------ 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/netbox/netbox/views/generic/mixins.py b/netbox/netbox/views/generic/mixins.py index a55f01509..d072843d9 100644 --- a/netbox/netbox/views/generic/mixins.py +++ b/netbox/netbox/views/generic/mixins.py @@ -9,13 +9,13 @@ __all__ = ( class ActionsMixin: - actions = ('add', 'import', 'export', 'bulk_edit', 'bulk_delete') - action_perms = defaultdict(set, **{ + actions = { 'add': {'add'}, 'import': {'add'}, + 'export': set(), 'bulk_edit': {'change'}, 'bulk_delete': {'delete'}, - }) + } def get_permitted_actions(self, user, model=None): """ @@ -23,11 +23,34 @@ class ActionsMixin: """ model = model or self.queryset.model - return [ - action for action in self.actions if user.has_perms([ - get_permission_for_model(model, name) for name in self.action_perms[action] - ]) - ] + # TODO: Remove backward compatibility in Netbox v4.0 + # Determine how permissions are being mapped to actions for the view + if type(self.actions) is dict: + # New actions format (3.7+) + permissions_map = self.actions + elif hasattr(self, 'action_perms'): + # Backward compatibility for <3.7 + permissions_map = self.action_perms + else: + # actions is still defined as a list or tuple (<3.7) but no custom mapping is defined; use the old + # default mapping + permissions_map = { + 'add': {'add'}, + 'import': {'add'}, + 'bulk_edit': {'change'}, + 'bulk_delete': {'delete'}, + } + + # Resolve required permissions for each action + permitted_actions = [] + for action in self.actions: + required_permissions = [ + get_permission_for_model(model, name) for name in permissions_map.get(action, set()) + ] + if not required_permissions or user.has_perms(required_permissions): + permitted_actions.append(action) + + return permitted_actions class TableMixin: