|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import grp |
| 3 | +import os |
| 4 | +import pwd |
| 5 | +import sys |
| 6 | +import json |
| 7 | + |
| 8 | +DIR = os.getenv('HOME') |
| 9 | +RESOURCE_ATTR_NAME = "urn:perun:resource:attribute-def:def:authorizationResourceId" |
| 10 | + |
| 11 | +def update_json(data): |
| 12 | + for user_uuid, user_data in data["users"].items(): |
| 13 | + allowed_resources_uuids = list(user_data.get("allowed_resources", {}).keys()) |
| 14 | + for resource_uuid in allowed_resources_uuids: |
| 15 | + if resource_uuid in data["resources"]: |
| 16 | + data["resources"].setdefault(resource_uuid, {}).setdefault("members", {}) |
| 17 | + data["resources"][resource_uuid]["members"][user_uuid] = user_data["attributes"] |
| 18 | + data["users"][user_uuid].pop("allowed_resources", None) |
| 19 | + return data |
| 20 | + |
| 21 | + |
| 22 | +def remove_unmatched_files(data): |
| 23 | + all_resources_names = [] |
| 24 | + for resource_uuid, resource_data in data["resources"].items(): |
| 25 | + all_resources_names.append(resource_data["attributes"][RESOURCE_ATTR_NAME]) |
| 26 | + |
| 27 | + for filename in os.listdir(DIR): |
| 28 | + if filename.endswith(".json") and filename.split(".json")[0] not in all_resources_names: |
| 29 | + filepath = os.path.join(DIR, filename) |
| 30 | + os.remove(filepath) |
| 31 | + |
| 32 | + |
| 33 | +def replace_files(data): |
| 34 | + for resource_uuid, resource_data in data["resources"].items(): |
| 35 | + resource_name = resource_data["attributes"][RESOURCE_ATTR_NAME] |
| 36 | + filepath = os.path.join(DIR, resource_name) |
| 37 | + with open(f"{filepath}.tmp", "w") as tmp_file: |
| 38 | + json.dump(resource_data, tmp_file, indent=4) |
| 39 | + tmp_file.flush() |
| 40 | + os.fsync(tmp_file.fileno()) |
| 41 | + # uid = pwd.getpwnam("perunrpc").pw_uid |
| 42 | + # gid = grp.getgrnam("perunrpc").gr_gid |
| 43 | + # os.chown(f"{filepath}.tmp", uid, gid) |
| 44 | + os.replace(f"{filepath}.tmp", f"{filepath}.json") |
| 45 | + |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + if len(sys.argv) != 2: |
| 49 | + print("Usage: python script.py <file_path>") |
| 50 | + sys.exit(1) |
| 51 | + |
| 52 | + # Load JSON from file |
| 53 | + file_path = sys.argv[1] |
| 54 | + |
| 55 | + with open(file_path, "r") as f: |
| 56 | + data = json.load(f) |
| 57 | + |
| 58 | + data = update_json(data) |
| 59 | + remove_unmatched_files(data) |
| 60 | + replace_files(data) |
0 commit comments