netbox-docker/startup_scripts/015_object_permissions.py

61 lines
2.2 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()
2021-04-25 17:15:46 +02:00
for permission_name, permission_details in object_permissions.items():
2021-04-20 23:47:49 +02:00
object_permission, created = ObjectPermission.objects.get_or_create(
2021-04-25 17:15:46 +02:00
name=permission_name,
description=permission_details["description"],
2021-04-25 17:15:46 +02:00
enabled=permission_details["enabled"],
actions=permission_details["actions"],
2021-04-20 23:47:49 +02:00
)
2021-04-25 22:31:50 +02:00
if permission_details.get("object_types", 0):
object_types = permission_details["object_types"]
if object_types == "all":
object_permission.object_types.set(ContentType.objects.all())
else:
for app_label, models in object_types.items():
if models == "all":
app_models = ContentType.objects.filter(app_label=app_label)
for app_model in app_models:
object_permission.object_types.add(app_model.id)
else:
# There is
for model in models:
object_permission.object_types.add(
ContentType.objects.get(app_label=app_label, model=model)
)
2021-04-20 23:47:49 +02:00
print("🔓 Created object permission", object_permission.name)
2021-04-25 17:15:46 +02:00
if permission_details.get("groups", 0):
for groupname in permission_details["groups"]:
group = AdminGroup.objects.filter(name=groupname).first()
2021-04-25 17:15:46 +02:00
if group:
object_permission.groups.add(group)
print(" 👥 Assigned group %s object permission of %s" % (groupname, groupname))
2021-04-25 17:15:46 +02:00
if permission_details.get("users", 0):
for username in permission_details["users"]:
user = AdminUser.objects.filter(username=username).first()
2021-04-25 17:15:46 +02:00
if user:
object_permission.users.add(user)
print(" 👤 Assigned user %s object permission of %s" % (username, groupname))
2021-04-20 23:47:49 +02:00
object_permission.save()