Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added functionality to specify roles in policies.json #310

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions backend/src/zango/api/platform/tenancy/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.conf import settings
from django.utils.decorators import method_decorator
from django.db.models import Q
from django.db import connection

from zango.core.api import (
get_api_response,
Expand All @@ -19,6 +20,7 @@
from zango.core.api.utils import ZangoAPIPagination
from zango.core.permissions import IsPlatformUserAllowedApp
from zango.core.utils import get_search_columns
from zango.apps.dynamic_models.workspace.base import Workspace

from .serializers import (
TenantSerializerModel,
Expand Down Expand Up @@ -261,6 +263,12 @@ def post(self, request, *args, **kwargs):
role.is_active = True
role.save()
result = {"message": "User Role Created Successfully", "role_id": role.id}
if role_serializer.data.get("policies", False):
tenant = TenantModel.objects.get(uuid=kwargs.get("app_uuid"))
connection.set_tenant(tenant)
with connection.cursor() as c:
ws = Workspace(connection.tenant, request=None, as_systemuser=True)
ws.sync_role_with_policies()
else:
success = False
status_code = 400
Expand Down Expand Up @@ -316,6 +324,11 @@ def put(self, request, *args, **kwargs):
"message": "User Role Updated Successfully",
"role_id": obj.id,
}
tenant = TenantModel.objects.get(uuid=kwargs.get("app_uuid"))
connection.set_tenant(tenant)
with connection.cursor() as c:
ws = Workspace(connection.tenant, request=None, as_systemuser=True)
ws.sync_role_with_policies()
else:
success = False
status_code = 400
Expand Down
59 changes: 59 additions & 0 deletions backend/src/zango/apps/dynamic_models/workspace/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

from django.conf import settings
from django.db import connection
from django.db.models import OuterRef, Subquery
from django.contrib.postgres.aggregates import ArrayAgg

from zango.apps.permissions.models import PolicyModel
from zango.apps.appauth.models import UserRoleModel
Expand Down Expand Up @@ -427,6 +429,7 @@ def sync_policies(self):
existing_policies = list(
PolicyModel.objects.filter(type="user").values_list("id", flat=True)
)
role_with_policies = {}
modules = self.get_all_module_paths()
for module in modules:
policy_file = f"{module}/policies.json"
Expand All @@ -444,6 +447,10 @@ def sync_policies(self):
policy = json.load(f)
except json.decoder.JSONDecodeError as e:
raise Exception(f"Error parsing {policy_file}: {e}")
for policy_dict in policy["policies"]:
roles = policy_dict.get("roles", [])
for role in roles:
role_with_policies[role] = []
for policy_details in policy["policies"]:
if type(policy_details["statement"]) is not dict:
raise Exception(
Expand All @@ -465,10 +472,62 @@ def sync_policies(self):
if policy.id not in existing_policies:
raise Exception(f"Policy name already exists")
existing_policies.remove(policy.id)
roles = policy_details.get("roles", [])
for role in roles:
role_with_policies[role].append(policy.id)
except Exception as e:
raise Exception(
f"Error creating policy {policy_details['name']} in {policy_path}: {e}"
)

for policy_id in existing_policies:
PolicyModel.objects.get(id=policy_id).delete()
self.sync_policies_with_roles(role_with_policies)

def sync_policies_with_roles(self, role_with_policies):
"""
mapping roles from policies.json to UserRoleModel
"""
existing_roles = list(UserRoleModel.objects.filter(is_default=False).values_list("id", flat=True))
for role, policies in role_with_policies.items():
user_role, created = UserRoleModel.objects.update_or_create(
name=role,
defaults={
"name": role
}
)
user_role.policies.set(policies)
if not created:
existing_roles.remove(user_role.id)

UserRoleModel.objects.filter(id__in=existing_roles).delete()

def sync_role_with_policies(self):
"""
mapping roles from UserRoleModel to policies.json
"""
all_policies={}
policies_without_roles = list(
PolicyModel.objects.filter(type="user", role_policies__isnull=True)
.values("name", "description", "statement")
)
policies_with_roles = list(
PolicyModel.objects.filter(type="user", role_policies__isnull=False)
.values("name", "description", "statement")
.annotate(
roles=ArrayAgg(
'role_policies__name', distinct=True
)
)
)
all_policies["policies"]=policies_without_roles+policies_with_roles
modules = self.get_all_module_paths()
for module in modules:
policy_file = f"{module}/policies.json"
if os.path.isfile(policy_file):
model_module = (
module.replace(str(settings.BASE_DIR) + "/", "") + "/policies"
)
model_module = model_module.lstrip("/").replace("/", ".")
with open(policy_file, 'w') as f:
f.write(json.dumps(all_policies,indent=4))