Răsfoiți Sursa

Add new services and update admin routes after merge from main

Manuel 9 luni în urmă
părinte
comite
be3a7ebf1e

+ 199 - 414
routes/admin_routes.py

@@ -1,5 +1,3 @@
-import os
-
 from flask import (
     Blueprint,
     current_app,
@@ -10,75 +8,83 @@ from flask import (
     request,
     url_for,
 )
-from sqlalchemy import MetaData, Table, func, inspect, select, text
+from loguru import logger
 
-from config import Config, logger
-from database.database import get_engine, get_session
+from config import Config
 from services.auth_service import AuthService, admin_required, api_auth_required
+from services.config_service import save_config as service_save_config
+from services.db_admin_service import delete_table_data as service_delete_table_data
+from services.db_info_service import get_tables_info as service_get_tables_info
+from services.logs_service import read_logs as service_read_logs
+from services.split_config_service import (
+    get_split_files_info as service_get_split_files_info,
+)
+from services.split_config_service import (
+    get_split_view_data as service_get_split_view_data,
+)
+from services.split_config_service import (
+    split_config as service_split_config,
+)
 from services.squid_config_splitter import SquidConfigSplitter
+from services.system_service import (
+    reload_squid as service_reload_squid,
+)
+from services.system_service import (
+    restart_squid as service_restart_squid,
+)
+from services.user_service import (
+    create_user as service_create_user,
+)
+from services.user_service import (
+    delete_user as service_delete_user,
+)
+from services.user_service import (
+    get_all_users as service_get_all_users,
+)
+from services.user_service import (
+    update_user as service_update_user,
+)
 from utils.admin import SquidConfigManager
 
 admin_bp = Blueprint("admin", __name__)
 
 # Global manager instance
 config_manager = SquidConfigManager()
-
-
-def load_env_vars():
-    env_vars = {}
-    env_file = os.path.join(os.getcwd(), ".env")
-    if os.path.exists(env_file):
-        with open(env_file) as f:
-            for line in f:
-                line = line.strip()
-                if line and "=" in line:
-                    key, value = line.split("=", 1)
-                    env_vars[key] = value.strip('"')
-    return env_vars
-
-
-def save_env_vars(env_vars):
-    env_file = os.path.join(os.getcwd(), ".env")
-    with open(env_file, "w") as f:
-        for key, value in env_vars.items():
-            f.write(f'{key}="{value}"\n')
-
-
-def get_table_row_count(session, engine, table_name):
-    metadata = MetaData()
-    table = Table(table_name, metadata, autoload_with=engine)
-
-    return session.execute(select(func.count()).select_from(table)).scalar_one()
-
-
-def get_table_size(session, db_type, table_name):
-    if db_type == "SQLITE":
-        result = session.execute(
-            text("SELECT SUM(pgsize) FROM dbstat WHERE name = :name"),
-            {"name": table_name},
-        )
-        return result.scalar() or 0
-
-    if db_type in ("MYSQL", "MARIADB"):
-        result = session.execute(
-            text("""
-                SELECT data_length + index_length
-                FROM information_schema.tables
-                WHERE table_name = :name
-                AND table_schema = DATABASE()
-            """),
-            {"name": table_name},
-        )
-        return result.scalar() or 0
-
-    if db_type in ("POSTGRES", "POSTGRESQL"):
-        result = session.execute(
-            text("SELECT pg_total_relation_size(:name)"),
-            {"name": table_name},
-        )
-        return result.scalar() or 0
-
-    return 0
+from services.acls_service import add_acl as service_add_acl
+from services.acls_service import delete_acl as service_delete_acl
+from services.acls_service import edit_acl as service_edit_acl
+from services.admin_helpers import (
+    load_env_vars,
+    save_env_vars,
+)
+from services.blacklist_service import (
+    import_domains_from_file,
+    import_domains_from_url,
+    merge_and_save_blacklist,
+    save_custom_list,
+    test_pihole_connection,
+)
+from services.delay_pools_service import (
+    add_delay_pool as service_add_delay_pool,
+)
+from services.delay_pools_service import (
+    delete_delay_pool as service_delete_delay_pool,
+)
+from services.delay_pools_service import (
+    edit_delay_pool as service_edit_delay_pool,
+)
+from services.http_access_service import (
+    add_http_access as service_add_http_access,
+)
+from services.http_access_service import (
+    delete_http_access as service_delete_http_access,
+)
+from services.http_access_service import (
+    edit_http_access as service_edit_http_access,
+)
+from services.http_access_service import (
+    move_http_access as service_move_http_access,
+)
 
 
 @admin_bp.route("/")
@@ -173,59 +179,15 @@ def add_acl():
     options = request.form.getlist("options[]")
     comment = request.form.get("comment", "").strip()
 
-    if not name or not acl_type or not values:
-        flash("Debe proporcionar nombre, tipo y al menos un valor para la ACL", "error")
-        return redirect(url_for("admin.manage_acls"))
-
-    # Build ACL line: acl name [options] type values...
-    acl_parts = ["acl", name]
-    if options:
-        acl_parts.extend(options)
-    acl_parts.append(acl_type)
-    acl_parts.extend(values)
-    new_acl = " ".join(acl_parts)
-
-    # Check if using modular configuration
-    if config_manager.is_modular:
-        acl_content = config_manager.read_modular_config("100_acls.conf")
-        if acl_content is not None:
-            lines = acl_content.split("\n")
-
-            # Add comment if provided
-            if comment:
-                lines.append(f"# {comment}")
-
-            # Add the new ACL
-            lines.append(new_acl)
-
-            new_content = "\n".join(lines)
-            if config_manager.save_modular_config("100_acls.conf", new_content):
-                flash(f"ACL '{name}' agregada exitosamente", "success")
-            else:
-                flash("Error al guardar la ACL", "error")
-            return redirect(url_for("admin.manage_acls"))
-
-    # Fallback to main config
-    lines = config_manager.config_content.split("\n")
-    acl_section_end = -1
-    for i, line in enumerate(lines):
-        if line.strip().startswith("acl "):
-            acl_section_end = i
-
-    if acl_section_end != -1:
-        if comment:
-            lines.insert(acl_section_end + 1, f"# {comment}")
-            lines.insert(acl_section_end + 2, new_acl)
-        else:
-            lines.insert(acl_section_end + 1, new_acl)
-    else:
-        if comment:
-            lines.append(f"# {comment}")
-        lines.append(new_acl)
-
-    new_content = "\n".join(lines)
-    config_manager.save_config(new_content)
-    flash(f"ACL '{name}' agregada exitosamente", "success")
+    success, message = service_add_acl(
+        name, acl_type, values, options, comment, config_manager
+    )
+    flash(message, "success" if success else "error")
+    return redirect(url_for("admin.manage_acls"))
+    success, message = service_add_acl(
+        name, acl_type, values, options, comment, config_manager
+    )
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_acls"))
 
 
@@ -303,31 +265,10 @@ def edit_acl():
                         flash("Línea de ACL no encontrada", "error")
                     return redirect(url_for("admin.manage_acls"))
 
-            # Fallback to main config
-            lines = config_manager.config_content.split("\n")
-            if 0 <= target_line < len(lines):
-                lines[target_line] = new_acl_line
-
-                # Handle comment
-                if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
-                    if comment:
-                        lines[target_line - 1] = f"# {comment}"
-                    else:
-                        lines.pop(target_line - 1)
-                else:
-                    if comment:
-                        lines.insert(target_line, f"# {comment}")
-
-                new_content = "\n".join(lines)
-                config_manager.save_config(new_content)
-                flash(f"ACL '{new_name}' actualizada exitosamente", "success")
-            else:
-                flash("Línea de ACL no encontrada", "error")
-        else:
-            flash("ACL no encontrada", "error")
-    except (ValueError, IndexError) as e:
-        flash(f"Error al actualizar la ACL: {str(e)}", "error")
-
+    success, message = service_edit_acl(
+        acl_index, new_name, acl_type, values, options, comment, config_manager
+    )
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_acls"))
 
 
@@ -420,64 +361,119 @@ def manage_http_access():
     return render_template("admin/http_access.html", rules=rules)
 
 
-@admin_bp.route("/http-access/delete", methods=["POST"])
+@admin_bp.route("/blacklist", methods=["GET"])
 @admin_required
-def delete_http_access():
-    index = request.form.get("index")
+def manage_blacklist():
+    """Render the blacklist management UI."""
+    env_vars = load_env_vars()
+    # Provide current blacklist domains to the template
+    blacklist = env_vars.get("BLACKLIST_DOMAINS", "")
+    return render_template(
+        "admin/blacklist.html", env_vars=env_vars, blacklist=blacklist
+    )
+
+
+@admin_bp.route("/blacklist/test-connection", methods=["POST"])
+@admin_required
+def blacklist_test_connection():
+    host = request.form.get("host") or request.form.get("pihole_host")
+    token = request.form.get("token") or request.form.get("api_token")
+    if not host:
+        flash("Host de Pi-hole no proporcionado", "error")
+        return redirect(url_for("admin.manage_blacklist"))
+    success, msg = test_pihole_connection(host, token)
+    flash(msg, "success" if success else "error")
 
+    return redirect(url_for("admin.manage_blacklist"))
+
+
+@admin_bp.route("/blacklist/sync", methods=["POST"])
+@admin_required
+def blacklist_sync():
+    # Placeholder: kick off background sync job in production
+    # For now just flash success and return
+    flash("Sincronización de listas iniciada (en segundo plano)", "success")
+    return redirect(url_for("admin.manage_blacklist"))
+
+
+@admin_bp.route("/blacklist/import", methods=["POST"])
+@admin_required
+def blacklist_import():
+    # Import domains from uploaded file or URL and append to BLACKLIST_DOMAINS
+    env_vars = load_env_vars()
+    domains = set()
+
+    # Handle file upload
+    uploaded = request.files.get("file")
+    if uploaded and uploaded.filename:
+        try:
+            file_domains = import_domains_from_file(uploaded)
+            domains.update(file_domains)
+            flash("Archivo importado correctamente", "success")
+        except Exception as e:
+            logger.exception("Error importando archivo de blacklist")
+            flash(f"Error al procesar el archivo: {str(e)}", "error")
+            return redirect(url_for("admin.manage_blacklist"))
+
+    # Handle URL import
+    url = request.form.get("url")
+    if url:
+        ok, url_domains, err = import_domains_from_url(url)
+        if ok:
+            domains.update(url_domains)
+            flash("Lista importada desde URL correctamente", "success")
+        else:
+            flash(f"Error importando desde URL: {err}", "error")
+
+    # Merge with existing and save
     try:
-        rule_index = int(index)
+        merge_and_save_blacklist(env_vars, domains)
+        flash("Blacklist actualizada exitosamente", "success")
+    except Exception as e:
+        logger.exception("Error guardando BLACKLIST_DOMAINS")
+        flash(f"Error al guardar blacklist: {str(e)}", "error")
 
-        # Check if using modular configuration
-        if config_manager.is_modular:
-            http_content = config_manager.read_modular_config("120_http_access.conf")
-            if http_content is not None:
-                lines = http_content.split("\n")
-                new_lines = []
-                http_count = 0
+    return redirect(url_for("admin.manage_blacklist"))
 
-                for line in lines:
-                    if line.strip().startswith(
-                        "http_access "
-                    ) and not line.strip().startswith("#"):
-                        if http_count == rule_index:
-                            # Skip this line (delete it)
-                            http_count += 1
-                            continue
-                        http_count += 1
-                    new_lines.append(line)
 
-                new_content = "\n".join(new_lines)
-                if config_manager.save_modular_config(
-                    "120_http_access.conf", new_content
-                ):
-                    flash("Regla HTTP Access eliminada exitosamente", "success")
-                else:
-                    flash("Error al eliminar la regla", "error")
-                return redirect(url_for("admin.manage_http_access"))
+@admin_bp.route("/blacklist/save-custom", methods=["POST"])
+@admin_required
+def blacklist_save_custom():
+    custom = request.form.get("custom_list", "")
+    if not custom.strip():
+        flash("Lista personalizada vacía", "error")
+        return redirect(url_for("admin.manage_blacklist"))
+
+    # parse lines and commas
+    items = []
+    for line in custom.splitlines():
+        for part in line.split(","):
+            d = part.strip()
+            if d:
+                items.append(d)
 
-        # Fallback to main config
-        lines = config_manager.config_content.split("\n")
-        new_lines = []
-        http_count = 0
+    try:
+        save_custom_list(items)
+        flash("Lista personalizada guardada en BLACKLIST_DOMAINS", "success")
+    except Exception as e:
+        logger.exception("Error guardando lista personalizada")
+        flash(f"Error al guardar la lista: {str(e)}", "error")
 
-        for line in lines:
-            if line.strip().startswith("http_access ") and not line.strip().startswith(
-                "#"
-            ):
-                if http_count == rule_index:
-                    http_count += 1
-                    continue
-                http_count += 1
-            new_lines.append(line)
+    return redirect(url_for("admin.manage_blacklist"))
 
-        new_content = "\n".join(new_lines)
-        config_manager.save_config(new_content)
-        flash("Regla HTTP Access eliminada exitosamente", "success")
 
-    except (ValueError, IndexError) as e:
-        flash(f"Error al eliminar la regla: {str(e)}", "error")
+@admin_bp.route("/http-access/delete", methods=["POST"])
+@admin_required
+def delete_http_access():
+    index = request.form.get("index")
+    try:
+        rule_index = int(index)
+    except (ValueError, TypeError):
+        flash("Índice de regla inválido", "error")
+        return redirect(url_for("admin.manage_http_access"))
 
+    success, message = service_delete_http_access(rule_index, config_manager)
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_http_access"))
 
 
@@ -498,67 +494,10 @@ def edit_http_access():
             flash("Debe especificar al menos una ACL", "error")
             return redirect(url_for("admin.manage_http_access"))
 
-        new_rule = f"http_access {action} {acl_string}"
-
-        # Check if using modular configuration
-        if config_manager.is_modular:
-            http_content = config_manager.read_modular_config("120_http_access.conf")
-            if http_content is not None:
-                lines = http_content.split("\n")
-                http_count = 0
-
-                for i, line in enumerate(lines):
-                    if line.strip().startswith(
-                        "http_access "
-                    ) and not line.strip().startswith("#"):
-                        if http_count == rule_index:
-                            # Replace the rule, optionally with a comment above
-                            if description:
-                                # Check if there's already a comment above this line
-                                if i > 0 and lines[i - 1].strip().startswith("#"):
-                                    lines[i - 1] = f"# {description}"
-                                else:
-                                    lines.insert(i, f"# {description}")
-                                    i += 1
-                            lines[i] = new_rule
-                            break
-                        http_count += 1
-
-                new_content = "\n".join(lines)
-                if config_manager.save_modular_config(
-                    "120_http_access.conf", new_content
-                ):
-                    flash("Regla HTTP Access actualizada exitosamente", "success")
-                else:
-                    flash("Error al actualizar la regla", "error")
-                return redirect(url_for("admin.manage_http_access"))
-
-        # Fallback to main config
-        lines = config_manager.config_content.split("\n")
-        http_count = 0
-
-        for i, line in enumerate(lines):
-            if line.strip().startswith("http_access ") and not line.strip().startswith(
-                "#"
-            ):
-                if http_count == rule_index:
-                    if description:
-                        if i > 0 and lines[i - 1].strip().startswith("#"):
-                            lines[i - 1] = f"# {description}"
-                        else:
-                            lines.insert(i, f"# {description}")
-                            i += 1
-                    lines[i] = new_rule
-                    break
-                http_count += 1
-
-        new_content = "\n".join(lines)
-        config_manager.save_config(new_content)
-        flash("Regla HTTP Access actualizada exitosamente", "success")
-
-    except (ValueError, IndexError) as e:
-        flash(f"Error al actualizar la regla: {str(e)}", "error")
-
+    success, message = service_edit_http_access(
+        rule_index, action, acls, description, config_manager
+    )
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_http_access"))
 
 
@@ -570,48 +509,10 @@ def add_http_access():
     acls = request.form.getlist("acls[]")
     description = request.form.get("description", "").strip()
 
-    try:
-        acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
-
-        if not acl_string:
-            flash("Debe especificar al menos una ACL", "error")
-            return redirect(url_for("admin.manage_http_access"))
-
-        new_rule = f"http_access {action} {acl_string}"
-        lines_to_add = []
-
-        if description:
-            lines_to_add.append(f"# {description}")
-        lines_to_add.append(new_rule)
-
-        # Check if using modular configuration
-        if config_manager.is_modular:
-            http_content = config_manager.read_modular_config("120_http_access.conf")
-            if http_content is not None:
-                lines = http_content.split("\n")
-                # Add at the end (before final "deny all" if it exists)
-                lines.extend(lines_to_add)
-
-                new_content = "\n".join(lines)
-                if config_manager.save_modular_config(
-                    "120_http_access.conf", new_content
-                ):
-                    flash("Regla HTTP Access agregada exitosamente", "success")
-                else:
-                    flash("Error al agregar la regla", "error")
-                return redirect(url_for("admin.manage_http_access"))
-
-        # Fallback to main config
-        lines = config_manager.config_content.split("\n")
-        lines.extend(lines_to_add)
-
-        new_content = "\n".join(lines)
-        config_manager.save_config(new_content)
-        flash("Regla HTTP Access agregada exitosamente", "success")
-
-    except Exception as e:
-        flash(f"Error al agregar la regla: {str(e)}", "error")
-
+    success, message = service_add_http_access(
+        action, acls, description, config_manager
+    )
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_http_access"))
 
 
@@ -785,91 +686,10 @@ def edit_delay_pool():
     access_actions = request.form.getlist("access_action[]")
     access_acls = request.form.getlist("access_acl[]")
 
-    try:
-        # Build new directives
-        new_directives = []
-        new_directives.append(f"delay_class {pool_number} {pool_class}")
-        new_directives.append(f"delay_parameters {pool_number} {parameters}")
-
-        # Add access rules
-        for action, acl in zip(access_actions, access_acls, strict=True):
-            if acl.strip():
-                new_directives.append(f"delay_access {pool_number} {action} {acl}")
-
-        # Check if using modular configuration
-        if config_manager.is_modular:
-            delay_content = config_manager.read_modular_config("110_delay_pools.conf")
-            if delay_content is not None:
-                lines = delay_content.split("\n")
-                new_lines = []
-                pool_found = False
-                insert_index = -1
-
-                # Remove old directives and find insertion point
-                for _i, line in enumerate(lines):
-                    stripped = line.strip()
-                    if (
-                        stripped.startswith(f"delay_class {pool_number} ")
-                        or stripped.startswith(f"delay_parameters {pool_number} ")
-                        or stripped.startswith(f"delay_access {pool_number} ")
-                    ):
-                        if not pool_found:
-                            insert_index = len(new_lines)
-                            pool_found = True
-                        continue
-                    new_lines.append(line)
-
-                # Insert new directives at the same location
-                if insert_index >= 0:
-                    for directive in reversed(new_directives):
-                        new_lines.insert(insert_index, directive)
-                else:
-                    # If not found, append at the end
-                    new_lines.extend(new_directives)
-
-                new_content = "\n".join(new_lines)
-                if config_manager.save_modular_config(
-                    "110_delay_pools.conf", new_content
-                ):
-                    flash(
-                        f"Delay Pool #{pool_number} actualizado exitosamente", "success"
-                    )
-                else:
-                    flash("Error al actualizar el delay pool", "error")
-                return redirect(url_for("admin.manage_delay_pools"))
-
-        # Fallback to main config
-        lines = config_manager.config_content.split("\n")
-        new_lines = []
-        pool_found = False
-        insert_index = -1
-
-        for _i, line in enumerate(lines):
-            stripped = line.strip()
-            if (
-                stripped.startswith(f"delay_class {pool_number} ")
-                or stripped.startswith(f"delay_parameters {pool_number} ")
-                or stripped.startswith(f"delay_access {pool_number} ")
-            ):
-                if not pool_found:
-                    insert_index = len(new_lines)
-                    pool_found = True
-                continue
-            new_lines.append(line)
-
-        if insert_index >= 0:
-            for directive in reversed(new_directives):
-                new_lines.insert(insert_index, directive)
-        else:
-            new_lines.extend(new_directives)
-
-        new_content = "\n".join(new_lines)
-        config_manager.save_config(new_content)
-        flash(f"Delay Pool #{pool_number} actualizado exitosamente", "success")
-
-    except Exception as e:
-        flash(f"Error al actualizar el delay pool: {str(e)}", "error")
-
+    success, message = service_edit_delay_pool(
+        pool_number, pool_class, parameters, access_actions, access_acls, config_manager
+    )
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_delay_pools"))
 
 
@@ -883,45 +703,10 @@ def add_delay_pool():
     access_actions = request.form.getlist("access_action[]")
     access_acls = request.form.getlist("access_acl[]")
 
-    try:
-        # Build new directives
-        new_directives = []
-        new_directives.append(f"delay_class {pool_number} {pool_class}")
-        new_directives.append(f"delay_parameters {pool_number} {parameters}")
-
-        # Add access rules
-        for action, acl in zip(access_actions, access_acls, strict=True):
-            if acl.strip():
-                new_directives.append(f"delay_access {pool_number} {action} {acl}")
-
-        # Check if using modular configuration
-        if config_manager.is_modular:
-            delay_content = config_manager.read_modular_config("110_delay_pools.conf")
-            if delay_content is not None:
-                # Append new directives at the end
-                lines = delay_content.split("\n")
-                lines.extend(new_directives)
-
-                new_content = "\n".join(lines)
-                if config_manager.save_modular_config(
-                    "110_delay_pools.conf", new_content
-                ):
-                    flash(f"Delay Pool #{pool_number} creado exitosamente", "success")
-                else:
-                    flash("Error al crear el delay pool", "error")
-                return redirect(url_for("admin.manage_delay_pools"))
-
-        # Fallback to main config
-        lines = config_manager.config_content.split("\n")
-        lines.extend(new_directives)
-
-        new_content = "\n".join(lines)
-        config_manager.save_config(new_content)
-        flash(f"Delay Pool #{pool_number} creado exitosamente", "success")
-
-    except Exception as e:
-        flash(f"Error al crear el delay pool: {str(e)}", "error")
-
+    success, message = service_add_delay_pool(
+        pool_number, pool_class, parameters, access_actions, access_acls, config_manager
+    )
+    flash(message, "success" if success else "error")
     return redirect(url_for("admin.manage_delay_pools"))
 
 

+ 170 - 0
services/acls_service.py

@@ -0,0 +1,170 @@
+from loguru import logger
+
+
+def add_acl(
+    name: str, acl_type: str, values: list, options: list, comment: str, config_manager
+) -> tuple[bool, str]:
+    if not name or not acl_type or not values:
+        return False, "Debe proporcionar nombre, tipo y al menos un valor para la ACL"
+
+    acl_parts = ["acl", name]
+    if options:
+        acl_parts.extend(options)
+    acl_parts.append(acl_type)
+    acl_parts.extend(values)
+    new_acl = " ".join(acl_parts)
+
+    try:
+        if config_manager.is_modular:
+            acl_content = config_manager.read_modular_config("100_acls.conf")
+            if acl_content is not None:
+                lines = acl_content.split("\n")
+                if comment:
+                    lines.append(f"# {comment}")
+                lines.append(new_acl)
+                new_content = "\n".join(lines)
+                if config_manager.save_modular_config("100_acls.conf", new_content):
+                    return True, f"ACL '{name}' agregada exitosamente"
+                else:
+                    return False, "Error al guardar la ACL en modular"
+
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        acl_section_end = -1
+        for i, line in enumerate(lines):
+            if line.strip().startswith("acl "):
+                acl_section_end = i
+
+        if acl_section_end != -1:
+            if comment:
+                lines.insert(acl_section_end + 1, f"# {comment}")
+                lines.insert(acl_section_end + 2, new_acl)
+            else:
+                lines.insert(acl_section_end + 1, new_acl)
+        else:
+            if comment:
+                lines.append(f"# {comment}")
+            lines.append(new_acl)
+
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        return True, f"ACL '{name}' agregada exitosamente"
+    except Exception as e:
+        logger.exception("Error agregando ACL")
+        return False, str(e)
+
+
+def edit_acl(
+    acl_index: int,
+    new_name: str,
+    acl_type: str,
+    values: list,
+    options: list,
+    comment: str,
+    config_manager,
+) -> tuple[bool, str]:
+    try:
+        acls = config_manager.get_acls()
+        if not (0 <= acl_index < len(acls)):
+            return False, "ACL no encontrada"
+
+        target_acl = acls[acl_index]
+        target_line = target_acl["line_number"] - 1
+
+        acl_parts = ["acl", new_name]
+        if options:
+            acl_parts.extend(options)
+        acl_parts.append(acl_type)
+        acl_parts.extend(values)
+        new_acl_line = " ".join(acl_parts)
+
+        if config_manager.is_modular:
+            acl_content = config_manager.read_modular_config("100_acls.conf")
+            if acl_content is not None:
+                lines = acl_content.split("\n")
+                if 0 <= target_line < len(lines):
+                    has_comment = target_line > 0 and lines[
+                        target_line - 1
+                    ].strip().startswith("#")
+                    lines[target_line] = new_acl_line
+                    if has_comment:
+                        if comment:
+                            lines[target_line - 1] = f"# {comment}"
+                        else:
+                            lines.pop(target_line - 1)
+                    else:
+                        if comment:
+                            lines.insert(target_line, f"# {comment}")
+                    new_content = "\n".join(lines)
+                    if config_manager.save_modular_config("100_acls.conf", new_content):
+                        return True, f"ACL '{new_name}' actualizada exitosamente"
+                    else:
+                        return False, "Error guardando ACL modular"
+
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        if 0 <= target_line < len(lines):
+            lines[target_line] = new_acl_line
+            if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
+                if comment:
+                    lines[target_line - 1] = f"# {comment}"
+                else:
+                    lines.pop(target_line - 1)
+            else:
+                if comment:
+                    lines.insert(target_line, f"# {comment}")
+            new_content = "\n".join(lines)
+            config_manager.save_config(new_content)
+            return True, f"ACL '{new_name}' actualizada exitosamente"
+        return False, "Línea de ACL no encontrada"
+    except Exception as e:
+        logger.exception("Error editando ACL")
+        return False, str(e)
+
+
+def delete_acl(acl_index: int, config_manager) -> tuple[bool, str]:
+    try:
+        acls = config_manager.get_acls()
+        if not (0 <= acl_index < len(acls)):
+            return False, "ACL no encontrada"
+
+        acl_to_delete = acls[acl_index]
+        target_line = acl_to_delete["line_number"] - 1
+
+        if config_manager.is_modular:
+            acl_content = config_manager.read_modular_config("100_acls.conf")
+            if acl_content is not None:
+                lines = acl_content.split("\n")
+                comment_to_remove = None
+                if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
+                    comment_to_remove = target_line - 1
+                new_lines = []
+                for i, line in enumerate(lines):
+                    if i == target_line:
+                        continue
+                    if comment_to_remove is not None and i == comment_to_remove:
+                        continue
+                    new_lines.append(line)
+                new_content = "\n".join(new_lines)
+                if config_manager.save_modular_config("100_acls.conf", new_content):
+                    return True, f"ACL '{acl_to_delete['name']}' eliminada exitosamente"
+                else:
+                    return False, "Error al eliminar ACL modular"
+
+        lines = config_manager.config_content.split("\n")
+        comment_to_remove = None
+        if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
+            comment_to_remove = target_line - 1
+        new_lines = []
+        for i, line in enumerate(lines):
+            if i == target_line:
+                continue
+            if comment_to_remove is not None and i == comment_to_remove:
+                continue
+            new_lines.append(line)
+        new_content = "\n".join(new_lines)
+        config_manager.save_config(new_content)
+        return True, f"ACL '{acl_to_delete['name']}' eliminada exitosamente"
+    except Exception as e:
+        logger.exception("Error eliminando ACL")
+        return False, str(e)

+ 60 - 0
services/admin_helpers.py

@@ -0,0 +1,60 @@
+import os
+
+from sqlalchemy import MetaData, Table, func, select, text
+
+
+def load_env_vars():
+    env_vars = {}
+    env_file = os.path.join(os.getcwd(), ".env")
+    if os.path.exists(env_file):
+        with open(env_file) as f:
+            for line in f:
+                line = line.strip()
+                if line and "=" in line:
+                    key, value = line.split("=", 1)
+                    env_vars[key] = value.strip('"')
+    return env_vars
+
+
+def save_env_vars(env_vars):
+    env_file = os.path.join(os.getcwd(), ".env")
+    with open(env_file, "w") as f:
+        for key, value in env_vars.items():
+            f.write(f'{key}="{value}"\n')
+
+
+def get_table_row_count(session, engine, table_name):
+    metadata = MetaData()
+    table = Table(table_name, metadata, autoload_with=engine)
+
+    return session.execute(select(func.count()).select_from(table)).scalar_one()
+
+
+def get_table_size(session, db_type, table_name):
+    if db_type == "SQLITE":
+        result = session.execute(
+            text("SELECT SUM(pgsize) FROM dbstat WHERE name = :name"),
+            {"name": table_name},
+        )
+        return result.scalar() or 0
+
+    if db_type in ("MYSQL", "MARIADB"):
+        result = session.execute(
+            text("""
+                SELECT data_length + index_length
+                FROM information_schema.tables
+                WHERE table_name = :name
+                AND table_schema = DATABASE()
+            """),
+            {"name": table_name},
+        )
+        return result.scalar() or 0
+
+    if db_type in ("POSTGRES", "POSTGRESQL"):
+        result = session.execute(
+            text("SELECT pg_total_relation_size(:name)"),
+            {"name": table_name},
+        )
+        return result.scalar() or 0
+
+    return 0

+ 90 - 0
services/blacklist_service.py

@@ -0,0 +1,90 @@
+import requests
+from loguru import logger
+
+from services.admin_helpers import load_env_vars, save_env_vars
+
+
+def test_pihole_connection(host: str, token: str | None = None) -> tuple[bool, str]:
+    if not host:
+        return False, "Host no proporcionado"
+
+    url = host
+    if not url.startswith("http://") and not url.startswith("https://"):
+        url = f"http://{url}"
+
+    params = {}
+    headers = {}
+    if token:
+        headers["Authorization"] = token
+        params["auth"] = token
+
+    try:
+        resp = requests.get(
+            f"{url}/admin/api.php", params=params, headers=headers, timeout=6
+        )
+        if resp.status_code == 200:
+            return True, "Conexión a Pi-hole exitosa"
+        return False, f"Respuesta inesperada de Pi-hole: {resp.status_code}"
+    except Exception as e:
+        logger.exception("Error probando conexión Pi-hole")
+        return False, f"Error al conectar con Pi-hole: {str(e)}"
+
+
+def import_domains_from_file(file_storage) -> set:
+    domains = set()
+    if not file_storage:
+        return domains
+
+    content = file_storage.read().decode("utf-8", errors="ignore")
+    for line in content.splitlines():
+        line = line.strip()
+        if not line or line.startswith("#"):
+            continue
+        if " " in line:
+            parts = line.split()
+            domain = parts[-1]
+        else:
+            domain = line
+        domains.add(domain)
+    return domains
+
+
+def import_domains_from_url(url: str) -> tuple[bool, set, str]:
+    domains = set()
+    try:
+        resp = requests.get(url, timeout=8)
+        if resp.status_code != 200:
+            return False, domains, f"Error al descargar la lista: {resp.status_code}"
+
+        for line in resp.text.splitlines():
+            line = line.strip()
+            if not line or line.startswith("#"):
+                continue
+            if " " in line:
+                parts = line.split()
+                domain = parts[-1]
+            else:
+                domain = line
+            domains.add(domain)
+        return True, domains, ""
+    except Exception as e:
+        logger.exception("Error descargando lista desde URL")
+        return False, domains, str(e)
+
+
+def merge_and_save_blacklist(existing_env: dict, new_domains: set) -> None:
+    existing = [
+        d.strip()
+        for d in existing_env.get("BLACKLIST_DOMAINS", "").split(",")
+        if d.strip()
+    ]
+    merged = set(existing)
+    merged.update(new_domains)
+    existing_env["BLACKLIST_DOMAINS"] = ",".join(sorted(merged))
+    save_env_vars(existing_env)
+
+
+def save_custom_list(items: list) -> None:
+    env_vars = load_env_vars()
+    env_vars["BLACKLIST_DOMAINS"] = ",".join(sorted(set(items)))
+    save_env_vars(env_vars)

+ 50 - 0
services/db_admin_service.py

@@ -0,0 +1,50 @@
+import re
+
+from loguru import logger
+from sqlalchemy import MetaData, Table, inspect
+
+from database.database import get_engine
+
+
+def delete_table_data(table_name: str):
+    """Delete all rows from `table_name` after validation.
+
+    Returns tuple `(response_dict, status_code)` ready to jsonify/return.
+    """
+    if not table_name:
+        return {"status": "error", "message": "Nombre de tabla no proporcionado"}, 400
+
+    if not re.match(r"^[a-zA-Z0-9_]+$", table_name):
+        return {"status": "error", "message": "Nombre de tabla inválido"}, 400
+
+    if table_name in ("admin_users", "alembic_version"):
+        return {
+            "status": "error",
+            "message": "No se puede eliminar estas tablas críticas",
+        }, 400
+
+    try:
+        engine = get_engine()
+        inspector = inspect(engine)
+
+        if table_name not in inspector.get_table_names():
+            return {"status": "error", "message": "La tabla no existe"}, 404
+
+        metadata = MetaData()
+        table = Table(table_name, metadata, autoload_with=engine)
+        with engine.connect() as conn:
+            conn.execute(table.delete())
+            conn.commit()
+
+        return {
+            "status": "success",
+            "message": f"Datos de la tabla '{table_name}' eliminados correctamente",
+        }, 200
+
+    except Exception as e:
+        logger.exception("Error deleting data from table %s", table_name)
+        return {
+            "status": "error",
+            "message": "Error interno del servidor",
+            "details": str(e),
+        }, 500

+ 49 - 0
services/db_info_service.py

@@ -0,0 +1,49 @@
+from loguru import logger
+from sqlalchemy import inspect
+
+from config import Config
+from database.database import get_engine, get_session
+from services.admin_helpers import get_table_row_count, get_table_size
+
+
+def get_tables_info():
+    session = None
+    try:
+        engine = get_engine()
+        inspector = inspect(engine)
+        session = get_session()
+        db_type = Config.DATABASE_TYPE
+
+        tables = inspector.get_table_names()
+        table_info = []
+
+        for table_name in tables:
+            try:
+                rows = get_table_row_count(session, engine, table_name)
+                size = get_table_size(session, db_type, table_name)
+
+                table_info.append(
+                    {
+                        "name": table_name,
+                        "rows": rows,
+                        "size": size,
+                        "has_data": rows > 0,
+                    }
+                )
+
+            except Exception as e:
+                logger.warning(f"Error processing table {table_name}: {e}")
+                table_info.append(
+                    {"name": table_name, "rows": 0, "size": 0, "has_data": False}
+                )
+
+        return {"status": "success", "tables": table_info}, 200
+
+    except Exception:
+        logger.exception("Error getting database tables")
+        resp = {"status": "error", "message": "Error interno del servidor"}
+        return resp, 500
+
+    finally:
+        if session:
+            session.close()

+ 163 - 0
services/delay_pools_service.py

@@ -0,0 +1,163 @@
+from loguru import logger
+
+
+def delete_delay_pool(pool_number: str, config_manager) -> tuple[bool, str]:
+    try:
+        if config_manager.is_modular:
+            delay_content = config_manager.read_modular_config("110_delay_pools.conf")
+            if delay_content is not None:
+                lines = delay_content.split("\n")
+                new_lines = []
+                for line in lines:
+                    stripped = line.strip()
+                    if (
+                        stripped.startswith(f"delay_class {pool_number} ")
+                        or stripped.startswith(f"delay_parameters {pool_number} ")
+                        or stripped.startswith(f"delay_access {pool_number} ")
+                    ):
+                        continue
+                    new_lines.append(line)
+                new_content = "\n".join(new_lines)
+                if config_manager.save_modular_config(
+                    "110_delay_pools.conf", new_content
+                ):
+                    return True, f"Delay Pool #{pool_number} eliminado exitosamente"
+                else:
+                    return False, "Error al eliminar delay pool modular"
+
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        new_lines = []
+        for line in lines:
+            stripped = line.strip()
+            if (
+                stripped.startswith(f"delay_class {pool_number} ")
+                or stripped.startswith(f"delay_parameters {pool_number} ")
+                or stripped.startswith(f"delay_access {pool_number} ")
+            ):
+                continue
+            new_lines.append(line)
+        new_content = "\n".join(new_lines)
+        config_manager.save_config(new_content)
+        return True, f"Delay Pool #{pool_number} eliminado exitosamente"
+    except Exception as e:
+        logger.exception("Error eliminando delay pool")
+        return False, str(e)
+
+
+def edit_delay_pool(
+    pool_number: str,
+    pool_class: str,
+    parameters: str,
+    access_actions: list,
+    access_acls: list,
+    config_manager,
+) -> tuple[bool, str]:
+    try:
+        new_directives = []
+        new_directives.append(f"delay_class {pool_number} {pool_class}")
+        new_directives.append(f"delay_parameters {pool_number} {parameters}")
+        for action, acl in zip(access_actions, access_acls):
+            if acl.strip():
+                new_directives.append(f"delay_access {pool_number} {action} {acl}")
+
+        if config_manager.is_modular:
+            delay_content = config_manager.read_modular_config("110_delay_pools.conf")
+            if delay_content is not None:
+                lines = delay_content.split("\n")
+                new_lines = []
+                pool_found = False
+                insert_index = -1
+                for i, line in enumerate(lines):
+                    if line.strip().startswith(f"delay_class {pool_number} "):
+                        pool_found = True
+                        insert_index = i
+                        # skip existing block (we will rebuild)
+                        continue
+                    if pool_found and (
+                        line.strip().startswith("delay_class ") or line.strip() == ""
+                    ):
+                        pool_found = False
+                    if not pool_found:
+                        new_lines.append(line)
+
+                if insert_index >= 0:
+                    # insert our directives at the insertion point
+                    new_lines[insert_index:insert_index] = new_directives
+                else:
+                    new_lines.extend(new_directives)
+                new_content = "\n".join(new_lines)
+                if config_manager.save_modular_config(
+                    "110_delay_pools.conf", new_content
+                ):
+                    return True, f"Delay Pool #{pool_number} actualizado exitosamente"
+                else:
+                    return False, "Error al guardar delay pool modular"
+
+        # Fallback to main config: naive append/update
+        lines = config_manager.config_content.split("\n")
+        # Try to find existing pool and replace, else append
+        pool_found = False
+        insert_index = -1
+        for i, line in enumerate(lines):
+            if line.strip().startswith(f"delay_class {pool_number} "):
+                pool_found = True
+                insert_index = i
+                break
+
+        if insert_index >= 0:
+            # remove existing block lines starting at insert_index until next blank or next delay_class
+            j = insert_index
+            while j < len(lines) and not (
+                lines[j].strip().startswith("delay_class ") and j != insert_index
+            ):
+                j += 1
+            new_lines = lines[:insert_index] + new_directives + lines[j:]
+        else:
+            new_lines = lines + new_directives
+
+        new_content = "\n".join(new_lines)
+        config_manager.save_config(new_content)
+        return True, f"Delay Pool #{pool_number} actualizado exitosamente"
+    except Exception as e:
+        logger.exception("Error actualizando delay pool")
+        return False, str(e)
+
+
+def add_delay_pool(
+    pool_number: str,
+    pool_class: str,
+    parameters: str,
+    access_actions: list,
+    access_acls: list,
+    config_manager,
+) -> tuple[bool, str]:
+    try:
+        new_directives = []
+        new_directives.append(f"delay_class {pool_number} {pool_class}")
+        new_directives.append(f"delay_parameters {pool_number} {parameters}")
+        for action, acl in zip(access_actions, access_acls):
+            if acl.strip():
+                new_directives.append(f"delay_access {pool_number} {action} {acl}")
+
+        if config_manager.is_modular:
+            delay_content = config_manager.read_modular_config("110_delay_pools.conf")
+            if delay_content is not None:
+                lines = delay_content.split("\n")
+                lines.extend(new_directives)
+                new_content = "\n".join(lines)
+                if config_manager.save_modular_config(
+                    "110_delay_pools.conf", new_content
+                ):
+                    return True, f"Delay Pool #{pool_number} creado exitosamente"
+                else:
+                    return False, "Error al crear delay pool modular"
+
+        lines = config_manager.config_content.split("\n")
+        lines.extend(new_directives)
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        return True, f"Delay Pool #{pool_number} creado exitosamente"
+    except Exception as e:
+        logger.exception("Error creando delay pool")
+        return False, str(e)

+ 173 - 0
services/http_access_service.py

@@ -0,0 +1,173 @@
+from loguru import logger
+
+
+def _find_http_lines(lines):
+    return [
+        i
+        for i, line in enumerate(lines)
+        if line.strip().startswith("http_access ") and not line.strip().startswith("#")
+    ]
+
+
+def delete_http_access(rule_index: int, config_manager) -> tuple[bool, str]:
+    try:
+        if config_manager.is_modular:
+            http_content = config_manager.read_modular_config("120_http_access.conf")
+            if http_content is not None:
+                lines = http_content.split("\n")
+                http_lines_indices = _find_http_lines(lines)
+                if rule_index >= len(http_lines_indices):
+                    return False, "Índice de regla inválido"
+                # remove the line
+                del lines[http_lines_indices[rule_index]]
+                new_content = "\n".join(lines)
+                if config_manager.save_modular_config(
+                    "120_http_access.conf", new_content
+                ):
+                    return True, "Regla HTTP Access eliminada exitosamente"
+                else:
+                    return False, "Error al eliminar la regla modular"
+
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        http_lines_indices = _find_http_lines(lines)
+        if rule_index >= len(http_lines_indices):
+            return False, "Índice de regla inválido"
+        del lines[http_lines_indices[rule_index]]
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        return True, "Regla HTTP Access eliminada exitosamente"
+    except Exception as e:
+        logger.exception("Error eliminando http_access")
+        return False, str(e)
+
+
+def edit_http_access(
+    rule_index: int, action: str, acls: list, description: str, config_manager
+) -> tuple[bool, str]:
+    try:
+        acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
+        if not acl_string:
+            return False, "Debe especificar al menos una ACL"
+
+        new_rule = f"http_access {action} {acl_string}"
+
+        if config_manager.is_modular:
+            http_content = config_manager.read_modular_config("120_http_access.conf")
+            if http_content is not None:
+                lines = http_content.split("\n")
+                http_lines_indices = _find_http_lines(lines)
+                if rule_index >= len(http_lines_indices):
+                    return False, "Índice de regla inválido"
+                i = http_lines_indices[rule_index]
+                if description:
+                    if i > 0 and lines[i - 1].strip().startswith("#"):
+                        lines[i - 1] = f"# {description}"
+                    else:
+                        lines.insert(i, f"# {description}")
+                        i += 1
+                lines[i] = new_rule
+                new_content = "\n".join(lines)
+                if config_manager.save_modular_config(
+                    "120_http_access.conf", new_content
+                ):
+                    return True, "Regla HTTP Access actualizada exitosamente"
+                else:
+                    return False, "Error al guardar regla modular"
+
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        http_lines_indices = _find_http_lines(lines)
+        if rule_index >= len(http_lines_indices):
+            return False, "Índice de regla inválido"
+        i = http_lines_indices[rule_index]
+        if description:
+            if i > 0 and lines[i - 1].strip().startswith("#"):
+                lines[i - 1] = f"# {description}"
+            else:
+                lines.insert(i, f"# {description}")
+                i += 1
+        lines[i] = new_rule
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        return True, "Regla HTTP Access actualizada exitosamente"
+    except Exception as e:
+        logger.exception("Error actualizando http_access")
+        return False, str(e)
+
+
+def add_http_access(
+    action: str, acls: list, description: str, config_manager
+) -> tuple[bool, str]:
+    try:
+        acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
+        if not acl_string:
+            return False, "Debe especificar al menos una ACL"
+        new_rule = f"http_access {action} {acl_string}"
+        lines_to_add = []
+        if description:
+            lines_to_add.append(f"# {description}")
+        lines_to_add.append(new_rule)
+
+        if config_manager.is_modular:
+            http_content = config_manager.read_modular_config("120_http_access.conf")
+            if http_content is not None:
+                lines = http_content.split("\n")
+                lines.extend(lines_to_add)
+                new_content = "\n".join(lines)
+                if config_manager.save_modular_config(
+                    "120_http_access.conf", new_content
+                ):
+                    return True, "Regla HTTP Access agregada exitosamente"
+                else:
+                    return False, "Error al guardar regla modular"
+
+        lines = config_manager.config_content.split("\n")
+        lines.extend(lines_to_add)
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        return True, "Regla HTTP Access agregada exitosamente"
+    except Exception as e:
+        logger.exception("Error agregando http_access")
+        return False, str(e)
+
+
+def move_http_access(
+    rule_index: int, direction: str, config_manager
+) -> tuple[bool, str]:
+    try:
+        if config_manager.is_modular:
+            http_content = config_manager.read_modular_config("120_http_access.conf")
+            if http_content is not None:
+                lines = http_content.split("\n")
+                http_lines_indices = _find_http_lines(lines)
+                if rule_index >= len(http_lines_indices):
+                    return False, "Índice de regla inválido"
+                current = http_lines_indices[rule_index]
+                if direction == "up" and rule_index > 0:
+                    target = http_lines_indices[rule_index - 1]
+                    lines[current], lines[target] = lines[target], lines[current]
+                elif direction == "down" and rule_index < len(http_lines_indices) - 1:
+                    target = http_lines_indices[rule_index + 1]
+                    lines[current], lines[target] = lines[target], lines[current]
+                new_content = "\n".join(lines)
+                config_manager.save_modular_config("120_http_access.conf", new_content)
+                return True, "Regla movida exitosamente"
+
+        lines = config_manager.config_content.split("\n")
+        http_lines_indices = _find_http_lines(lines)
+        if rule_index >= len(http_lines_indices):
+            return False, "Índice de regla inválido"
+        current = http_lines_indices[rule_index]
+        if direction == "up" and rule_index > 0:
+            target = http_lines_indices[rule_index - 1]
+            lines[current], lines[target] = lines[target], lines[current]
+        elif direction == "down" and rule_index < len(http_lines_indices) - 1:
+            target = http_lines_indices[rule_index + 1]
+            lines[current], lines[target] = lines[target], lines[current]
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        return True, "Regla movida exitosamente"
+    except Exception as e:
+        logger.exception("Error moviendo http_access")
+        return False, str(e)

+ 26 - 0
services/logs_service.py

@@ -0,0 +1,26 @@
+import os
+
+from loguru import logger
+
+
+def read_logs(log_files, max_lines, debug=False):
+    """Read last `max_lines` from each file in `log_files`.
+
+    Returns a dict mapping basename -> list-of-lines.
+    """
+    logs = {}
+    for log_file in log_files:
+        try:
+            with open(log_file) as f:
+                lines = f.readlines()
+                logs[os.path.basename(log_file)] = lines[-max_lines:]
+        except FileNotFoundError:
+            logs[os.path.basename(log_file)] = ["Log file not found"]
+        except Exception as e:
+            logger.exception("Error reading log file %s", log_file)
+            if debug:
+                logs[os.path.basename(log_file)] = [f"Error reading log: {str(e)}"]
+            else:
+                logs[os.path.basename(log_file)] = ["Error reading log"]
+
+    return logs

+ 64 - 0
services/split_config_service.py

@@ -0,0 +1,64 @@
+import os
+
+from loguru import logger
+
+from services.squid_config_splitter import SquidConfigSplitter
+
+
+def get_split_view_data():
+    splitter = SquidConfigSplitter()
+    return {
+        "split_info": splitter.get_split_info(),
+        "output_exists": splitter.check_output_dir_exists(),
+        "files_count": splitter.count_files_in_output_dir(),
+        "output_dir": splitter.output_dir,
+        "input_file": splitter.input_file,
+    }
+
+
+def split_config(strict=False):
+    splitter = SquidConfigSplitter(strict=strict)
+
+    if not os.path.exists(splitter.input_file):
+        return {
+            "status": "error",
+            "message": f"Archivo squid.conf no encontrado en: {splitter.input_file}",
+        }, 404
+
+    try:
+        results = splitter.split_config()
+        return {
+            "status": "success",
+            "message": f"Configuración dividida exitosamente en {len(results)} archivos",
+            "data": {
+                "output_dir": splitter.output_dir,
+                "files": results,
+                "total_files": len(results),
+            },
+        }, 200
+    except FileNotFoundError as e:
+        logger.error("Archivo no encontrado: %s", e)
+        return {"status": "error", "message": "Archivo requerido no encontrado."}, 404
+    except PermissionError as e:
+        logger.error("Error de permisos: %s", e)
+        return {
+            "status": "error",
+            "message": "No se tienen permisos suficientes para crear los archivos",
+        }, 403
+    except RuntimeError as e:
+        logger.error("Error de validación: %s", e)
+        return {
+            "status": "error",
+            "message": "Error de validación de la configuración",
+        }, 400
+    except Exception as e:
+        logger.exception("Error al dividir el archivo de configuración")
+        return {
+            "status": "error",
+            "message": "Error interno al dividir la configuración",
+            "details": str(e),
+        }, 500
+
+
+def get_split_files_info(output_dir: str):
+    return SquidConfigSplitter.get_split_files_info(output_dir)

+ 21 - 0
services/system_service.py

@@ -0,0 +1,21 @@
+import subprocess
+
+from loguru import logger
+
+
+def restart_squid() -> tuple[bool, str, str]:
+    try:
+        subprocess.run(["systemctl", "restart", "squid"], check=True)
+        return True, "Squid restarted successfully", None
+    except Exception as e:
+        logger.exception("Error restarting squid")
+        return False, "Internal server error", str(e)
+
+
+def reload_squid() -> tuple[bool, str, str]:
+    try:
+        subprocess.run(["systemctl", "reload", "squid"], check=True)
+        return True, "Configuration reloaded successfully", None
+    except Exception as e:
+        logger.exception("Error reloading squid configuration")
+        return False, "Internal server error", str(e)

+ 61 - 0
services/user_service.py

@@ -0,0 +1,61 @@
+from loguru import logger
+
+from services.auth_service import AuthService
+
+
+def get_all_users():
+    try:
+        return AuthService.get_all_users()
+    except Exception:
+        logger.exception("Error getting users")
+        return []
+
+
+def create_user(username: str, password: str, role: str = "admin") -> tuple[bool, str]:
+    if not username or not password:
+        return False, "El nombre de usuario y la contraseña son obligatorios"
+    if len(password) < 8:
+        return False, "La contraseña debe tener al menos 8 caracteres"
+
+    try:
+        ok = AuthService.create_user(username, password, role)
+        if ok:
+            return True, "Usuario creado exitosamente"
+        return False, "Error al crear usuario. El nombre de usuario puede existir."
+    except Exception as e:
+        logger.exception("Error creating user")
+        return False, str(e)
+
+
+def update_user(
+    user_id: int, username: str, password: str, role: str, is_active: int
+) -> tuple[bool, str]:
+    if password and len(password) < 8:
+        return False, "La contraseña debe tener al menos 8 caracteres"
+
+    update_data = {"username": username, "role": role, "is_active": is_active}
+    if password:
+        update_data["password"] = password
+
+    try:
+        ok = AuthService.update_user(user_id, **update_data)
+        if ok:
+            return True, "Usuario actualizado exitosamente"
+        return False, "Error al actualizar usuario"
+    except Exception as e:
+        logger.exception("Error updating user")
+        return False, str(e)
+
+
+def delete_user(user_id: int) -> tuple[bool, str]:
+    try:
+        ok = AuthService.delete_user(user_id)
+        if ok:
+            return True, "Usuario eliminado exitosamente"
+        return (
+            False,
+            "Error al eliminar usuario. No se puede eliminar el usuario admin.",
+        )
+    except Exception as e:
+        logger.exception("Error deleting user")
+        return False, str(e)