misc-fred/authentic/import-roles.py

65 lines
2.1 KiB
Python

import json
import sys
from django_rbac.utils import get_role_model, get_ou_model, get_role_parenting_model, get_permission_model
from authentic2.a2_rbac.models import RoleAttribute
Role = get_role_model()
RoleParenting = get_role_parenting_model()
Permission = get_permission_model()
Ou = get_ou_model()
export = json.load(open(sys.argv[1]))
def get_role(role_dict):
kwargs = {'slug': role_dict['slug']}
if role_dict['is_service']:
kwargs['service__slug'] = role_dict['service_slug']
else:
kwargs['service__isnull'] = True
if role_dict['ou__slug']:
kwargs['ou__slug'] = role_dict['ou__slug']
else:
kwargs['ou__isnull'] = True
return Role.objects.get(**kwargs)
# first pass, create non technical roles
for role_dict in export['roles']:
if role_dict['slug'].startswith('_'):
continue
assert not role_dict['is_service']
ou = Ou.objects.get(slug=role_dict['ou__slug'])
role, created = Role.objects.get_or_create(slug=role_dict['slug'], ou=ou)
role.name = role_dict['name']
role.description = role_dict['description']
role.uuid = role_dict['uuid']
role.save()
for attribute in role_dict['attributes']:
RoleAttribute.objects.update_or_create(
role=role, name=attribute,
defaults=role_dict['attributes'][attribute])
# second pass, create hierarchy
for role_dict in export['roles']:
if not role_dict['parents']:
continue
assert not role_dict['is_service']
kwargs = {}
if role_dict['ou__slug']:
kwargs['ou'] = Ou.objects.get(slug=role_dict['ou__slug'])
else:
kwargs['ou__isnull'] = True
try:
role = Role.objects.get(slug=role_dict['slug'], **kwargs)
except Role.DoesNotExist:
print 'missing role', role
continue
for parent in role_dict['parents']:
try:
parent_role = get_role(parent)
except Role.DoesNotExist:
print 'could not role', parent
continue
RoleParenting.objects.get_or_create(child=role, direct=True, parent=parent_role)