Commit 4be5be99 authored by guillecxb's avatar guillecxb
Browse files

remove delete config and add snake case checks

parent 46b211a8
Loading
Loading
Loading
Loading
Loading
+24 −0
Original line number Diff line number Diff line
@@ -167,3 +167,27 @@ def add_new_config_setting():
        return jsonify(message="Missing 'param_path' or 'new_value' in request body"), 400
    
    return helper_operation.add_new_config_setting(param_path, new_value)


@helper_routes.route("/helper/removeConfigParam", methods=["DELETE"])
def remove_config_param():
    """Deletes a specific parameter inside 'settings'."""
    data = request.json
    param_path = data.get("param_path")

    if not param_path:
        return jsonify(message="Missing 'param_path' in request body"), 400

    return helper_operation.remove_config_param(param_path)


@helper_routes.route("/helper/removeConfigCategory", methods=["DELETE"])
def remove_config_category():
    """Deletes an entire category inside 'settings'."""
    data = request.json
    category_name = data.get("category_name")

    if not category_name:
        return jsonify(message="Missing 'category_name' in request body"), 400

    return helper_operation.remove_config_category(category_name)
+42 −7
Original line number Diff line number Diff line
@@ -5,7 +5,7 @@ import requests
from config import Config
from db.db import MongoDatabse
from flask import jsonify, current_app
from utils.utils import to_snake_case, convert_dict_keys_to_snake_case
from utils.utils import to_snake_case, convert_dict_keys_to_snake_case, validate_snake_case_keys


class HelperOperations:
@@ -203,7 +203,7 @@ class HelperOperations:
        return jsonify(message="User entities removed successfully"), 200

    def get_configuration(self):
        """Recupera toda la configuración actual"""
        """Get all current settings."""
        current_app.logger.debug("Retrieving current CAPIF configuration")
        config_col = self.db.get_col_by_name(self.db.capif_configuration)
        config = config_col.find_one({}, {"_id": 0})
@@ -216,14 +216,13 @@ class HelperOperations:

    def update_config_param(self, param_path, new_value):
        """
        Actualiza un único parámetro en la configuración.
        param_path: Ruta del parámetro (ej. settings.acl_policy_settings.allowed_total_invocations)
        Updates a single parameter in the configuration.
        param_path: Path of the parameter (e.g., settings.acl_policy_settings.allowed_total_invocations)
        """
        current_app.logger.debug(f"Updating configuration parameter: {param_path} with value: {new_value}")

        config_col = self.db.get_col_by_name(self.db.capif_configuration)

        # Construir el query dinámico para actualizar un parámetro específico
        update_query = {"$set": {param_path: new_value}}
        result = config_col.update_one({}, update_query)

@@ -235,13 +234,16 @@ class HelperOperations:

    def replace_configuration(self, new_config):
        """
        Reemplaza toda la configuración actual con una nueva.
        Replaces all current settings with a new one.
        """
        current_app.logger.debug("Replacing entire CAPIF configuration")

        error_response = validate_snake_case_keys(new_config)
        if error_response:
            return error_response

        config_col = self.db.get_col_by_name(self.db.capif_configuration)

        # Reemplazar la configuración existente con la nueva
        result = config_col.replace_one({}, new_config, upsert=True)

        if result.matched_count == 0:
@@ -288,4 +290,37 @@ class HelperOperations:
        return jsonify(message=f"Parameter '{param_path_snake}' added successfully"), 200


    def remove_config_param(self, param_path):
        """Removes a specific parameter inside 'settings'."""
        current_app.logger.debug(f"Removing configuration parameter: {param_path}")

        config_col = self.db.get_col_by_name(self.db.capif_configuration)

        param_path_snake = ".".join(to_snake_case(part) for part in param_path.split("."))

        update_query = {"$unset": {f"settings.{param_path_snake}": ""}}

        result = config_col.update_one({}, update_query)

        if result.modified_count == 0:
            return jsonify(message=f"No configuration found or parameter '{param_path_snake}' not removed"), 404

        return jsonify(message=f"Parameter '{param_path_snake}' removed successfully"), 200


    def remove_config_category(self, category_name):
        """Removes an entire category inside 'settings'."""
        current_app.logger.debug(f"Removing configuration category: {category_name}")

        config_col = self.db.get_col_by_name(self.db.capif_configuration)

        category_name_snake = to_snake_case(category_name)

        update_query = {"$unset": {f"settings.{category_name_snake}": ""}}

        result = config_col.update_one({}, update_query)

        if result.modified_count == 0:
            return jsonify(message=f"No configuration found or category '{category_name_snake}' not removed"), 404

        return jsonify(message=f"Category '{category_name_snake}' removed successfully"), 200
+20 −0
Original line number Diff line number Diff line
import re
from flask import jsonify

def to_snake_case(text):
    """
@@ -13,3 +14,22 @@ def convert_dict_keys_to_snake_case(data):
    if isinstance(data, dict):
        return {to_snake_case(k): convert_dict_keys_to_snake_case(v) for k, v in data.items()}
    return data


def is_snake_case(value):
    """
    Checks if a key is in snake_case.
    """
    return bool(re.match(r'^[a-z0-9_]+$', value))

def validate_snake_case_keys(obj, path="root"):
    """
    Iterates through the JSON validating that all keys are in snake_case.
    """
    for key, value in obj.items():
        if not is_snake_case(key):
            return jsonify({"error": f"The key '{path}.{key}' is not in snake_case"}), 400
        if isinstance(value, dict):
            error_response = validate_snake_case_keys(value, f"{path}.{key}")
            if error_response:
                return error_response
+29 −0
Original line number Diff line number Diff line
@@ -217,3 +217,32 @@ def add_new_config_setting():
        return jsonify(message="Missing 'param_path' or 'new_value' in request body"), 400
    
    return register_operation.add_new_config_setting(param_path, new_value)


@register_routes.route("/configuration/removeConfigParam", methods=["DELETE"])
@admin_required()
def remove_register_config_param(username):
    """Remove a specific parameter in the register configuration"""
    data = request.json
    param_path = data.get("param_path")

    if not param_path:
        return jsonify(message="Missing 'param_path' in request body"), 400

    current_app.logger.debug(f"Admin {username} is removing parameter {param_path}")
    return register_operation.remove_register_config_param(param_path)


@register_routes.route("/configuration/removeConfigCategory", methods=["DELETE"])
@admin_required()
def remove_register_config_category(username):
    """Remove an entire category in the register configuration"""
    data = request.json
    category_name = data.get("category_name")

    if not category_name:
        return jsonify(message="Missing 'category_name' in request body"), 400

    current_app.logger.debug(f"Admin {username} is removing category {category_name}")
    return register_operation.remove_register_config_category(category_name)
+46 −1
Original line number Diff line number Diff line
@@ -7,7 +7,7 @@ from config import Config
from db.db import MongoDatabse
from flask import jsonify, current_app
from flask_jwt_extended import create_access_token
from utils.utils import to_snake_case, convert_dict_keys_to_snake_case
from utils.utils import to_snake_case, convert_dict_keys_to_snake_case, validate_snake_case_keys


class RegisterOperations:
@@ -123,6 +123,11 @@ class RegisterOperations:
    def replace_register_configuration(self, new_config):
        """Replace the entire register configuration"""
        current_app.logger.debug("Replacing entire register configuration")

        error_response = validate_snake_case_keys(new_config)
        if error_response:
            return error_response

        config_col = self.db.get_col_by_name(self.db.capif_configuration)

        result = config_col.replace_one({}, new_config, upsert=True)
@@ -163,3 +168,43 @@ class RegisterOperations:
            return jsonify(message=f"No configuration found or parameter '{param_path_snake}' not updated"), 404

        return jsonify(message=f"Parameter '{param_path_snake}' added successfully"), 200
    

    def remove_register_config_param(self, param_path):
        """
        Removes a specific parameter in the registry settings.
        """
        current_app.logger.debug(f"Removing configuration parameter: {param_path}")
        
        config_col = self.db.get_col_by_name(self.db.capif_configuration)
        
        param_path_snake = ".".join(to_snake_case(part) for part in param_path.split("."))
        update_query = {"$unset": {f"settings.{param_path_snake}": ""}}

        result = config_col.update_one({}, update_query)

        if result.modified_count == 0:
            return jsonify(message=f"No configuration found or parameter '{param_path_snake}' not removed"), 404

        return jsonify(message=f"Parameter '{param_path_snake}' removed successfully"), 200
    

    def remove_register_config_category(self, category_name):
        """
        Deletes an entire category within 'settings'.
        """
        current_app.logger.debug(f"Removing configuration category: {category_name}")

        config_col = self.db.get_col_by_name(self.db.capif_configuration)

        category_name_snake = to_snake_case(category_name)
        update_query = {"$unset": {f"settings.{category_name_snake}": ""}}

        result = config_col.update_one({}, update_query)

        if result.modified_count == 0:
            return jsonify(message=f"No configuration found or category '{category_name_snake}' not removed"), 404

        return jsonify(message=f"Category '{category_name_snake}' removed successfully"), 200

Loading