2021-04-20 23:47:49 +02:00
|
|
|
import sys
|
|
|
|
|
|
|
|
from django.contrib.contenttypes.models import ContentType
|
2021-04-21 14:27:20 +02:00
|
|
|
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,
|
2022-04-05 08:34:08 +02:00
|
|
|
defaults={
|
|
|
|
"description": permission_details["description"],
|
|
|
|
"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:59:13 +02:00
|
|
|
|
2021-04-25 17:15:46 +02:00
|
|
|
if permission_details.get("groups", 0):
|
|
|
|
for groupname in permission_details["groups"]:
|
2021-04-26 15:17:25 +02:00
|
|
|
group = AdminGroup.objects.filter(name=groupname).first()
|
2021-04-25 17:15:46 +02:00
|
|
|
|
|
|
|
if group:
|
|
|
|
object_permission.groups.add(group)
|
2021-10-21 15:41:28 +02:00
|
|
|
print(
|
|
|
|
" 👥 Assigned group %s object permission of %s"
|
|
|
|
% (groupname, object_permission.name)
|
|
|
|
)
|
2021-04-25 17:15:46 +02:00
|
|
|
|
|
|
|
if permission_details.get("users", 0):
|
|
|
|
for username in permission_details["users"]:
|
2021-04-26 15:17:25 +02:00
|
|
|
user = AdminUser.objects.filter(username=username).first()
|
2021-04-25 17:15:46 +02:00
|
|
|
|
|
|
|
if user:
|
|
|
|
object_permission.users.add(user)
|
2021-10-21 15:41:28 +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()
|