netbox-docker/startup_scripts/020_object_permissions.py

69 lines
2.4 KiB
Python
Raw Normal View History

2021-04-20 16:47:49 -05: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 16:47:49 -05:00
object_permissions = load_yaml("/opt/netbox/initializers/object_permissions.yml")
if object_permissions is None:
sys.exit()
2021-04-25 10:15:46 -05:00
for permission_name, permission_details in object_permissions.items():
2021-04-20 16:47:49 -05:00
object_permission, created = ObjectPermission.objects.get_or_create(
2021-04-25 10:15:46 -05:00
name=permission_name,
2022-04-05 01:34:08 -05:00
defaults={
"description": permission_details["description"],
"enabled": permission_details["enabled"],
"actions": permission_details["actions"],
},
2021-04-20 16:47:49 -05:00
)
2021-04-25 15:31:50 -05: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 16:47:49 -05:00
print("🔓 Created object permission", object_permission.name)
2021-04-25 10:15:46 -05:00
if permission_details.get("groups", 0):
for groupname in permission_details["groups"]:
group = AdminGroup.objects.filter(name=groupname).first()
2021-04-25 10:15:46 -05:00
if group:
object_permission.groups.add(group)
print(
" 👥 Assigned group %s object permission of %s"
% (groupname, object_permission.name)
)
2021-04-25 10:15:46 -05:00
if permission_details.get("users", 0):
for username in permission_details["users"]:
user = AdminUser.objects.filter(username=username).first()
2021-04-25 10:15:46 -05:00
if user:
object_permission.users.add(user)
print(
" 👤 Assigned user %s object permission of %s"
% (username, object_permission.name)
)
2021-04-20 16:47:49 -05:00
object_permission.save()