+ # Always reads operation to resource mapping from file (this is static, no need to store it in MongoDB)
+ # Operations encoding: "<METHOD> <URL>"
+ # Note: it is faster to rewrite the value than to check if it is already there or not
+ if self.config["authentication"]["backend"] == "internal":
+ return
+
+ with open(self.resources_to_operations_file, "r") as stream:
+ resources_to_operations_yaml = yaml.load(stream)
+
+ for resource, operation in resources_to_operations_yaml["resources_to_operations"].items():
+ if operation not in self.operations:
+ self.operations.append(operation)
+ self.resources_to_operations_mapping[resource] = operation
+
+ records = self.db.get_list("roles_operations")
+
+ # Loading permissions to MongoDB if there is not any permission.
+ if not records:
+ with open(self.roles_to_operations_file, "r") as stream:
+ roles_to_operations_yaml = yaml.load(stream)
+
+ role_names = []
+ for role_with_operations in roles_to_operations_yaml["roles"]:
+ # Verifying if role already exists. If it does, raise exception
+ if role_with_operations["name"] not in role_names:
+ role_names.append(role_with_operations["name"])
+ else:
+ raise AuthException("Duplicated role name '{}' at file '{}''"
+ .format(role_with_operations["name"], self.roles_to_operations_file))
+
+ if not role_with_operations["permissions"]:
+ continue
+
+ for permission, is_allowed in role_with_operations["permissions"].items():
+ if not isinstance(is_allowed, bool):
+ raise AuthException("Invalid value for permission '{}' at role '{}'; at file '{}'"
+ .format(permission, role_with_operations["name"],
+ self.roles_to_operations_file))
+
+ # TODO chek permission is ok
+ if permission[-1] == ":":
+ raise AuthException("Invalid permission '{}' terminated in ':' for role '{}'; at file {}"
+ .format(permission, role_with_operations["name"],
+ self.roles_to_operations_file))
+
+ if "default" not in role_with_operations["permissions"]:
+ role_with_operations["permissions"]["default"] = False
+ if "admin" not in role_with_operations["permissions"]:
+ role_with_operations["permissions"]["admin"] = False
+
+ now = time()
+ role_with_operations["_admin"] = {
+ "created": now,
+ "modified": now,
+ }
+
+ if self.config["authentication"]["backend"] != "internal" and \
+ role_with_operations["name"] != "anonymous":
+
+ backend_roles = self.backend.get_role_list(filter_q={"name": role_with_operations["name"]})
+
+ if backend_roles:
+ backend_id = backend_roles[0]["_id"]
+ else:
+ backend_id = self.backend.create_role(role_with_operations["name"])
+ role_with_operations["_id"] = backend_id
+
+ self.db.create("roles_operations", role_with_operations)
+
+ if self.config["authentication"]["backend"] != "internal":
+ self.backend.assign_role_to_user("admin", "admin", "system_admin")
+
+ self.load_operation_to_allowed_roles()
+
+ def load_operation_to_allowed_roles(self):
+ """
+ Fills the internal self.operation_to_allowed_roles based on database role content and self.operations
+ It works in a shadow copy and replace at the end to allow other threads working with the old copy
+ :return: None
+ """
+
+ permissions = {oper: [] for oper in self.operations}
+ records = self.db.get_list("roles_operations")
+
+ ignore_fields = ["_id", "_admin", "name", "default"]
+ for record in records:
+ record_permissions = {oper: record["permissions"].get("default", False) for oper in self.operations}
+ operations_joined = [(oper, value) for oper, value in record["permissions"].items()
+ if oper not in ignore_fields]
+ operations_joined.sort(key=lambda x: x[0].count(":"))
+
+ for oper in operations_joined:
+ match = list(filter(lambda x: x.find(oper[0]) == 0, record_permissions.keys()))
+
+ for m in match:
+ record_permissions[m] = oper[1]
+
+ allowed_operations = [k for k, v in record_permissions.items() if v is True]
+
+ for allowed_op in allowed_operations:
+ permissions[allowed_op].append(record["name"])
+
+ self.operation_to_allowed_roles = permissions