+ records = self.backend.get_role_list()
+
+ # Loading permissions to AUTH. At lease system_admin must be present.
+ if not records or not next(
+ (r for r in records if r["name"] == "system_admin"), None
+ ):
+ with open(self.roles_to_operations_file, "r") as stream:
+ roles_to_operations_yaml = yaml.safe_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 check 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,
+ }
+
+ # self.db.create(self.roles_to_operations_table, role_with_operations)
+ try:
+ self.backend.create_role(role_with_operations)
+ self.logger.info(
+ "Role '{}' created".format(role_with_operations["name"])
+ )
+ except (AuthException, AuthconnException) as e:
+ if role_with_operations["name"] == "system_admin":
+ raise
+ self.logger.error(
+ "Role '{}' cannot be created: {}".format(
+ role_with_operations["name"], e
+ )
+ )
+
+ # Create admin project&user if required
+ pid = self.create_admin_project()
+ user_id = self.create_admin_user(pid)
+
+ # try to assign system_admin role to user admin if not any user has this role
+ if not user_id:
+ try:
+ users = self.backend.get_user_list()
+ roles = self.backend.get_role_list({"name": "system_admin"})
+ role_id = roles[0]["_id"]
+ user_with_system_admin = False
+ user_admin_id = None
+ for user in users:
+ if not user_admin_id:
+ user_admin_id = user["_id"]
+ if user["username"] == "admin":
+ user_admin_id = user["_id"]
+ for prm in user.get("project_role_mappings", ()):
+ if prm["role"] == role_id:
+ user_with_system_admin = True
+ break
+ if user_with_system_admin:
+ break
+ if not user_with_system_admin:
+ self.backend.update_user(
+ {
+ "_id": user_admin_id,
+ "add_project_role_mappings": [
+ {"project": pid, "role": role_id}
+ ],
+ }
+ )
+ self.logger.info(
+ "Added role system admin to user='{}' project=admin".format(
+ user_admin_id
+ )
+ )
+ except Exception as e:
+ self.logger.error(
+ "Error in Authorization DataBase initialization: {}: {}".format(
+ type(e).__name__, e
+ )
+ )
+
+ 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.role_permissions
+ 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.role_permissions}
+ # records = self.db.get_list(self.roles_to_operations_table)
+ records = self.backend.get_role_list()
+
+ ignore_fields = ["_id", "_admin", "name", "default"]
+ for record in records:
+ if not record.get("permissions"):
+ continue
+ record_permissions = {
+ oper: record["permissions"].get("default", False)
+ for oper in self.role_permissions
+ }
+ 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
+
+ def authorize(
+ self, role_permission=None, query_string_operations=None, item_id=None
+ ):