netbox-docker/startup_scripts/015_object_permissions.py

49 lines
1.6 KiB
Python
Raw Normal View History

2021-04-20 23:47:49 +02:00
import sys
from django.contrib.contenttypes.models import ContentType
from startup_script_utils import load_yaml
from users.models import AdminGroup, AdminUser, ObjectPermission
2021-04-20 23:47:49 +02:00
object_permissions = load_yaml("/opt/netbox/initializers/object_permissions.yml")
if object_permissions is None:
sys.exit()
for params in object_permissions:
object_permission, created = ObjectPermission.objects.get_or_create(
2021-04-21 00:05:47 +02:00
name=params["name"],
description=params["description"],
enabled=params["enabled"],
actions=params["actions"],
2021-04-20 23:47:49 +02:00
)
2021-04-21 00:05:47 +02:00
# Need to try to pass a list of model_name and app_label for more than the current ALL
# object_types = ContentType.objects.filter(app_label__in=params.pop("object_types"))
# object_permission.object_types.set(ContentType.objects.filter(app_label__in=params.pop("object_types")))
2021-04-20 23:47:49 +02:00
object_permission.object_types.set(ContentType.objects.all())
object_permission.save()
print("🔓 Created object permission", object_permission.name)
for groupname in params.get("groups", []):
group = AdminGroup.objects.get(name=groupname)
if group:
object_permission.groups.add(group)
2021-04-21 00:05:47 +02:00
print(
" 👥 Assigned group %s object permission of %s" % (groupname, object_permission.name)
)
2021-04-20 23:47:49 +02:00
for username in params.get("users", []):
user = AdminUser.objects.get(username=username)
if user:
object_permission.users.add(user)
2021-04-21 00:05:47 +02:00
print(
" 👤 Assigned user %s object permission of %s" % (username, object_permission.name)
)
2021-04-20 23:47:49 +02:00
object_permission.save()