4
0
Эх сурвалжийг харах

feat: Implement admin dashboard and configuration management for Squid, including ACLs and delay pools

Manuel 1 жил өмнө
parent
commit
55a87bd6f5

+ 126 - 18
app.py

@@ -6,7 +6,16 @@ from datetime import date, datetime
 from threading import Lock  # Importamos Lock para sincronización de hilos
 
 from dotenv import load_dotenv
-from flask import Blueprint, Flask, jsonify, redirect, render_template, request
+from flask import (
+    Blueprint,
+    Flask,
+    flash,
+    jsonify,
+    redirect,
+    render_template,
+    request,
+    url_for,
+)
 from flask_apscheduler import APScheduler
 from flask_socketio import SocketIO
 
@@ -41,8 +50,10 @@ from services.system_info import (
     get_timezone,
     get_uptime,
 )
+from utils.admin import SquidConfigManager
 from utils.colors import color_map
 from utils.filters import register_filters
+from utils.size import size_to_bytes
 from utils.updateSquid import update_squid
 from utils.updateSquidStats import updateSquidStats
 
@@ -51,6 +62,10 @@ class Config:
     SCHEDULER_API_ENABLED = True
 
 
+# Instancia global del manager
+config_manager = SquidConfigManager()
+
+
 load_dotenv()
 
 logging.basicConfig(
@@ -403,23 +418,6 @@ def realtime_data_thread():
                 swap_info = get_swap_info()
                 cpu_info = get_cpu_info()
 
-                # Convertir información de RAM y SWAP a bytes para guardar en BD
-                def size_to_bytes(size_str):
-                    if not size_str:
-                        return 0
-                    parts = size_str.strip().split()
-                    if len(parts) != 2:
-                        return 0
-                    value, unit = float(parts[0]), parts[1].upper()
-                    multipliers = {
-                        "B": 1,
-                        "KB": 1024,
-                        "MB": 1024**2,
-                        "GB": 1024**3,
-                        "TB": 1024**4,
-                    }
-                    return int(value * multipliers.get(unit, 1))
-
                 ram_bytes = size_to_bytes(ram_info.get("used", "0 B"))
                 swap_bytes = size_to_bytes(swap_info.get("used", "0 B"))
 
@@ -622,6 +620,116 @@ def api_run_audit():
     finally:
         db.close()
 
+@app.route('/admin')
+def admin_dashboard():
+    """Página principal con resumen de la configuración"""
+    acls = config_manager.get_acls()
+    delay_pools = config_manager.get_delay_pools()
+    http_access_rules = config_manager.get_http_access_rules()
+    stats = {
+        'total_acls': len(acls),
+        'total_delay_pools': len(delay_pools),
+        'total_http_rules': len(http_access_rules)
+    }
+    return render_template('admin/dashboardAdmin.html', stats=stats)
+
+@app.route('/config')
+def view_config():
+    """Ver configuración completa"""
+    return render_template('admin/config.html', config_content=config_manager.config_content)
+
+@app.route('/admin/config/edit', methods=['GET', 'POST'])
+def edit_config():
+    """Editar configuración completa"""
+    if request.method == 'POST':
+        new_content = request.form['config_content']
+        try:
+            config_manager.save_config(new_content)
+            flash('Configuración guardada exitosamente', 'success')
+            return redirect(url_for('view_config'))
+        except Exception as e:
+            flash(f'Error al guardar la configuración: {str(e)}', 'error')
+    return render_template('edit_config.html', config_content=config_manager.config_content)
+
+@app.route('/admin/acls')
+def manage_acls():
+    """Gestionar ACLs"""
+    acls = config_manager.get_acls()
+    return render_template('admin/acls.html', acls=acls)
+
+@app.route('/admin/acls/add', methods=['POST'])
+def add_acl():
+    """Agregar nueva ACL"""
+    name = request.form['name']
+    acl_type = request.form['type']
+    value = request.form['value']
+    new_acl = f"acl {name} {acl_type} {value}"
+    # Agregar la nueva ACL al final de la sección de ACLs
+    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:
+        lines.insert(acl_section_end + 1, new_acl)
+    else:
+        lines.append(new_acl)
+    new_content = '\n'.join(lines)
+    config_manager.save_config(new_content)
+    flash('ACL agregada exitosamente', 'success')
+    return redirect(url_for('manage_acls'))
+
+@app.route('/admin/delay-pools')
+def manage_delay_pools():
+    """Gestionar Delay Pools"""
+    delay_pools = config_manager.get_delay_pools()
+    return render_template('admin/delay_pools.html', delay_pools=delay_pools)
+
+@app.route('/admin/http-access')
+def manage_http_access():
+    """Gestionar reglas de acceso HTTP"""
+    rules = config_manager.get_http_access_rules()
+    return render_template('admin/http_access.html', rules=rules)
+
+@app.route('/admin/view-logs')
+def view_logs():
+    """Ver logs de Squid"""
+    log_files = [
+        '/var/log/squid/access.log',
+        '/var/log/squid/cache.log'
+    ]
+    logs = {}
+    for log_file in log_files:
+        try:
+            with open(log_file) as f:
+                # Leer las últimas 100 líneas
+                lines = f.readlines()
+                logs[os.path.basename(log_file)] = lines[-100:]
+        except FileNotFoundError:
+            logs[os.path.basename(log_file)] = ['Log file not found']
+        except Exception as e:
+            logs[os.path.basename(log_file)] = [f'Error reading log: {str(e)}']
+
+    return render_template('admin/logs.html', logs=logs)
+
+@app.route('/admin/api/restart-squid', methods=['POST'])
+def restart_squid():
+    """Reiniciar servicio Squid"""
+    try:
+        os.system('systemctl restart squid')
+        return jsonify({'status': 'success', 'message': 'Squid reiniciado exitosamente'})
+    except Exception as e:
+        return jsonify({'status': 'error', 'message': str(e)})
+
+@app.route('/admin/api/reload-squid', methods=['POST'])
+def reload_squid():
+    """Recargar configuración de Squid"""
+    try:
+        os.system('systemctl reload squid')
+        return jsonify({'status': 'success', 'message': 'Configuración recargada exitosamente'})
+    except Exception as e:
+        return jsonify({'status': 'error', 'message': str(e)})
+
 
 # Iniciar el hilo de actualización de datos en tiempo real
 if __name__ == "__main__":

+ 92 - 0
templates/admin/acls.html

@@ -0,0 +1,92 @@
+{% extends "base.html" %}
+
+{% block content %}
+<div class="space-y-6">
+    <div class="bg-white rounded-lg shadow-lg p-6">
+        <div class="flex justify-between items-center mb-6">
+            <h2 class="text-2xl font-bold text-gray-800">Gestión de ACLs</h2>
+            <button onclick="toggleAddForm()" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg transition-colors">
+                <i class="fas fa-plus mr-2"></i>Agregar ACL
+            </button>
+        </div>
+
+        <!-- Add ACL Form -->
+        <div id="addAclForm" class="hidden bg-gray-50 p-6 rounded-lg mb-6">
+            <h3 class="text-lg font-semibold mb-4">Agregar Nueva ACL</h3>
+            <form method="POST" action="/admin/acls/add" class="grid grid-cols-1 md:grid-cols-3 gap-4">
+                <div>
+                    <label class="block text-sm font-medium text-gray-700 mb-2">Nombre:</label>
+                    <input type="text" name="name" required class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
+                </div>
+                <div>
+                    <label class="block text-sm font-medium text-gray-700 mb-2">Tipo:</label>
+                    <select name="type" required class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
+                        <option value="src">src (IP origen)</option>
+                        <option value="dst">dst (IP destino)</option>
+                        <option value="dstdomain">dstdomain (Dominio destino)</option>
+                        <option value="port">port (Puerto)</option>
+                        <option value="time">time (Tiempo)</option>
+                        <option value="method">method (Método HTTP)</option>
+                        <option value="proxy_auth">proxy_auth (Autenticación)</option>
+                        <option value="maxconn">maxconn (Conexiones máximas)</option>
+                    </select>
+                </div>
+                <div>
+                    <label class="block text-sm font-medium text-gray-700 mb-2">Valor:</label>
+                    <input type="text" name="value" required class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
+                </div>
+                <div class="md:col-span-3 flex space-x-4">
+                    <button type="submit" class="bg-green-500 hover:bg-green-600 text-white px-6 py-2 rounded-lg transition-colors">
+                        <i class="fas fa-save mr-2"></i>Guardar ACL
+                    </button>
+                    <button type="button" onclick="toggleAddForm()" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg transition-colors">
+                        <i class="fas fa-times mr-2"></i>Cancelar
+                    </button>
+                </div>
+            </form>
+        </div>
+
+        <!-- ACLs List -->
+        <div class="overflow-x-auto">
+            <table class="w-full table-auto">
+                <thead class="bg-gray-50">
+                    <tr>
+                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nombre</th>
+                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tipo</th>
+                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Valor</th>
+                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Acciones</th>
+                    </tr>
+                </thead>
+                <tbody class="bg-white divide-y divide-gray-200">
+                    {% for acl in acls %}
+                    <tr class="hover:bg-gray-50">
+                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ acl.name }}</td>
+                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
+                            <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">
+                                {{ acl.type }}
+                            </span>
+                        </td>
+                        <td class="px-6 py-4 text-sm text-gray-500 max-w-xs truncate">{{ acl.value }}</td>
+                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
+                            <button class="text-blue-600 hover:text-blue-900 mr-3">
+                                <i class="fas fa-edit"></i>
+                            </button>
+                            <button class="text-red-600 hover:text-red-900">
+                                <i class="fas fa-trash"></i>
+                            </button>
+                        </td>
+                    </tr>
+                    {% endfor %}
+                </tbody>
+            </table>
+        </div>
+    </div>
+</div>
+
+<script>
+function toggleAddForm() {
+    const form = document.getElementById('addAclForm');
+    form.classList.toggle('hidden');
+}
+</script>
+{% endblock %}

+ 132 - 0
templates/admin/base.html

@@ -0,0 +1,132 @@
+<!DOCTYPE html>
+<html lang="es">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>{% block title %}Administrador Squid Proxy{% endblock %}</title>
+    <script src="https://cdn.tailwindcss.com"></script>
+    <script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
+    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
+</head>
+<body class="bg-gray-50 min-h-screen">
+    <!-- Navigation -->
+    <nav class="bg-blue-600 text-white shadow-lg">
+        <div class="max-w-7xl mx-auto px-4">
+            <div class="flex justify-between items-center py-4">
+                <div class="flex items-center space-x-4">
+                    <i class="fas fa-server text-2xl"></i>
+                    <h1 class="text-xl font-bold">Administrador Squid Proxy</h1>
+                </div>
+                <div class="flex space-x-4">
+                    <button onclick="reloadSquid()" class="bg-green-500 hover:bg-green-600 px-4 py-2 rounded-lg transition-colors">
+                        <i class="fas fa-sync-alt mr-2"></i>Recargar
+                    </button>
+                    <button onclick="restartSquid()" class="bg-red-500 hover:bg-red-600 px-4 py-2 rounded-lg transition-colors">
+                        <i class="fas fa-power-off mr-2"></i>Reiniciar
+                    </button>
+                </div>
+            </div>
+        </div>
+    </nav>
+
+    <!-- Sidebar -->
+    <div class="flex">
+        <aside class="w-64 bg-white shadow-lg min-h-screen">
+            <nav class="mt-8">
+                <div class="px-4 space-y-2">
+                    <a href="{{ url_for('index') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <i class="fas fa-home mr-3"></i>Dashboard
+                    </a>
+                    <a href="{{ url_for('view_config') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <i class="fas fa-file-code mr-3"></i>Configuración
+                    </a>
+                    <a href="{{ url_for('manage_acls') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <i class="fas fa-shield-alt mr-3"></i>ACLs
+                    </a>
+                    <a href="{{ url_for('manage_delay_pools') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <i class="fas fa-tachometer-alt mr-3"></i>Delay Pools
+                    </a>
+                    <a href="{{ url_for('manage_http_access') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <i class="fas fa-key mr-3"></i>Acceso HTTP
+                    </a>
+                    <a href="{{ url_for('view_logs') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <i class="fas fa-file-alt mr-3"></i>Logs
+                    </a>
+                </div>
+            </nav>
+        </aside>
+
+        <!-- Main Content -->
+        <main class="flex-1 p-8">
+            <!-- Flash Messages -->
+            {% with messages = get_flashed_messages(with_categories=true) %}
+                {% if messages %}
+                    <div class="mb-6">
+                        {% for category, message in messages %}
+                            <div class="alert alert-{{ 'success' if category == 'success' else 'error' }} p-4 rounded-lg mb-4 {% if category == 'success' %}bg-green-100 text-green-700 border border-green-300{% else %}bg-red-100 text-red-700 border border-red-300{% endif %}">
+                                <i class="fas fa-{% if category == 'success' %}check-circle{% else %}exclamation-triangle{% endif %} mr-2"></i>
+                                {{ message }}
+                            </div>
+                        {% endfor %}
+                    </div>
+                {% endif %}
+            {% endwith %}
+
+            {% block content %}{% endblock %}
+        </main>
+    </div>
+
+    <script>
+        async function reloadSquid() {
+            try {
+                const response = await fetch('/api/reload-squid', { method: 'POST' });
+                const data = await response.json();
+                
+                if (data.status === 'success') {
+                    showNotification(data.message, 'success');
+                } else {
+                    showNotification(data.message, 'error');
+                }
+            } catch (error) {
+                showNotification('Error al recargar Squid', 'error');
+            }
+        }
+
+        async function restartSquid() {
+            if (confirm('¿Está seguro de que desea reiniciar Squid? Esto interrumpirá temporalmente el servicio.')) {
+                try {
+                    const response = await fetch('/api/restart-squid', { method: 'POST' });
+                    const data = await response.json();
+                    
+                    if (data.status === 'success') {
+                        showNotification(data.message, 'success');
+                    } else {
+                        showNotification(data.message, 'error');
+                    }
+                } catch (error) {
+                    showNotification('Error al reiniciar Squid', 'error');
+                }
+            }
+        }
+
+        function showNotification(message, type) {
+            const notification = document.createElement('div');
+            notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
+                type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
+            }`;
+            notification.innerHTML = `
+                <div class="flex items-center">
+                    <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>
+                    ${message}
+                </div>
+            `;
+            
+            document.body.appendChild(notification);
+            
+            setTimeout(() => {
+                notification.remove();
+            }, 5000);
+        }
+    </script>
+</body>
+</html>

+ 16 - 0
templates/admin/config.html

@@ -0,0 +1,16 @@
+{% extends "base.html" %}
+
+{% block content %}
+<div class="bg-white rounded-lg shadow-lg p-6">
+    <div class="flex justify-between items-center mb-6">
+        <h2 class="text-2xl font-bold text-gray-800">Configuración de Squid</h2>
+        <a href="{{ url_for('edit_config') }}" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors">
+            <i class="fas fa-edit mr-2"></i>Editar
+        </a>
+    </div>
+    
+    <div class="bg-gray-900 rounded-lg p-4 overflow-x-auto">
+        <pre class="text-green-400 text-sm font-mono whitespace-pre-wrap">{{ config_content }}</pre>
+    </div>
+</div>
+{% endblock %}

+ 94 - 0
templates/admin/dashboardAdmin.html

@@ -0,0 +1,94 @@
+{% extends "base.html" %}
+
+{% block content %}
+<div class="space-y-6">
+    <div class="bg-white rounded-lg shadow-lg p-6">
+        <h2 class="text-2xl font-bold text-gray-800 mb-6">Dashboard - Resumen del Sistema</h2>
+        
+        <!-- Stats Cards -->
+        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
+            <div class="bg-gradient-to-r from-blue-500 to-blue-600 text-white p-6 rounded-lg">
+                <div class="flex items-center justify-between">
+                    <div>
+                        <p class="text-blue-100">Total ACLs</p>
+                        <p class="text-3xl font-bold">{{ stats.total_acls }}</p>
+                    </div>
+                    <i class="fas fa-shield-alt text-4xl text-blue-200"></i>
+                </div>
+            </div>
+            
+            <div class="bg-gradient-to-r from-green-500 to-green-600 text-white p-6 rounded-lg">
+                <div class="flex items-center justify-between">
+                    <div>
+                        <p class="text-green-100">Delay Pools</p>
+                        <p class="text-3xl font-bold">{{ stats.total_delay_pools }}</p>
+                    </div>
+                    <i class="fas fa-tachometer-alt text-4xl text-green-200"></i>
+                </div>
+            </div>
+            
+            <div class="bg-gradient-to-r from-purple-500 to-purple-600 text-white p-6 rounded-lg">
+                <div class="flex items-center justify-between">
+                    <div>
+                        <p class="text-purple-100">Reglas HTTP</p>
+                        <p class="text-3xl font-bold">{{ stats.total_http_rules }}</p>
+                    </div>
+                    <i class="fas fa-key text-4xl text-purple-200"></i>
+                </div>
+            </div>
+        </div>
+
+        <!-- Quick Actions -->
+        <div class="bg-gray-50 rounded-lg p-6">
+            <h3 class="text-lg font-semibold text-gray-800 mb-4">Acciones Rápidas</h3>
+            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
+                <a href="/admin/config/edit" class="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow border-l-4 border-blue-500">
+                    <i class="fas fa-edit text-blue-500 text-2xl mb-2"></i>
+                    <h4 class="font-semibold text-gray-800">Editar Configuración</h4>
+                    <p class="text-sm text-gray-600">Modificar archivo squid.conf</p>
+                </a>
+                
+                <a href="/admin/acls" class="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow border-l-4 border-green-500">
+                    <i class="fas fa-plus text-green-500 text-2xl mb-2"></i>
+                    <h4 class="font-semibold text-gray-800">Agregar ACL</h4>
+                    <p class="text-sm text-gray-600">Crear nueva regla de acceso</p>
+                </a>
+                
+                <a href="/admin/view-logs" class="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow border-l-4 border-yellow-500">
+                    <i class="fas fa-file-alt text-yellow-500 text-2xl mb-2"></i>
+                    <h4 class="font-semibold text-gray-800">Ver Logs</h4>
+                    <p class="text-sm text-gray-600">Revisar logs del sistema</p>
+                </a>
+                
+                <div class="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow border-l-4 border-red-500 cursor-pointer" onclick="restartSquid()">
+                    <i class="fas fa-power-off text-red-500 text-2xl mb-2"></i>
+                    <h4 class="font-semibold text-gray-800">Reiniciar Squid</h4>
+                    <p class="text-sm text-gray-600">Reiniciar el servicio</p>
+                </div>
+            </div>
+        </div>
+
+        <!-- System Status -->
+        <div class="mt-8 bg-white border rounded-lg p-6">
+            <h3 class="text-lg font-semibold text-gray-800 mb-4">Estado del Sistema</h3>
+            <div class="space-y-3">
+                <div class="flex items-center justify-between p-3 bg-green-50 rounded-lg">
+                    <div class="flex items-center">
+                        <i class="fas fa-circle text-green-500 mr-3"></i>
+                        <span class="font-medium">Servicio Squid</span>
+                    </div>
+                    <span class="text-green-600 font-semibold">Activo</span>
+                </div>
+                
+                <div class="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
+                    <div class="flex items-center">
+                        <i class="fas fa-database text-blue-500 mr-3"></i>
+                        <span class="font-medium">Configuración</span>
+                    </div>
+                    <span class="text-blue-600 font-semibold">Cargada</span>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>
+{% endblock %}

+ 44 - 0
templates/admin/delay_pools.html

@@ -0,0 +1,44 @@
+{% extends "base.html" %}
+
+{% block content %}
+<div class="bg-white rounded-lg shadow-lg p-6">
+    <h2 class="text-2xl font-bold text-gray-800 mb-6">Gestión de Delay Pools</h2>
+    
+    <div class="space-y-6">
+        {% for pool in delay_pools %}
+        <div class="border border-gray-200 rounded-lg p-6">
+            <div class="flex justify-between items-start mb-4">
+                <div>
+                    <h3 class="text-lg font-semibold text-gray-800">Pool {{ pool.id }}</h3>
+                    <p class="text-sm text-gray-600">Clase: {{ pool.class }}</p>
+                </div>
+                <div class="flex space-x-2">
+                    <button class="text-blue-600 hover:text-blue-900">
+                        <i class="fas fa-edit"></i>
+                    </button>
+                    <button class="text-red-600 hover:text-red-900">
+                        <i class="fas fa-trash"></i>
+                    </button>
+                </div>
+            </div>
+            
+            <div class="bg-gray-50 rounded-lg p-4 mb-4">
+                <h4 class="font-medium text-gray-800 mb-2">Parámetros:</h4>
+                <code class="text-sm text-gray-700">{{ pool.parameters }}</code>
+            </div>
+            
+            <div>
+                <h4 class="font-medium text-gray-800 mb-2">Reglas de Acceso:</h4>
+                <div class="space-y-1">
+                    {% for rule in pool.access_rules %}
+                    <div class="text-sm text-gray-600 bg-gray-50 p-2 rounded">
+                        <code>{{ rule }}</code>
+                    </div>
+                    {% endfor %}
+                </div>
+            </div>
+        </div>
+        {% endfor %}
+    </div>
+</div>
+{% endblock %}

+ 23 - 0
templates/admin/edit_config.html

@@ -0,0 +1,23 @@
+{% extends "base.html" %}
+
+{% block content %}
+<div class="bg-white rounded-lg shadow-lg p-6">
+    <h2 class="text-2xl font-bold text-gray-800 mb-6">Editar Configuración de Squid</h2>
+    
+    <form method="POST" class="space-y-4">
+        <div>
+            <label class="block text-sm font-medium text-gray-700 mb-2">Contenido del archivo squid.conf:</label>
+            <textarea name="config_content" rows="30" class="w-full p-4 border border-gray-300 rounded-lg font-mono text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">{{ config_content }}</textarea>
+        </div>
+        
+        <div class="flex space-x-4">
+            <button type="submit" class="bg-green-500 hover:bg-green-600 text-white px-6 py-2 rounded-lg transition-colors">
+                <i class="fas fa-save mr-2"></i>Guardar Cambios
+            </button>
+            <a href="/admin/config" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg transition-colors">
+                <i class="fas fa-times mr-2"></i>Cancelar
+            </a>
+        </div>
+    </form>
+</div>
+{% endblock %}

+ 36 - 0
templates/admin/http_access.html

@@ -0,0 +1,36 @@
+{% extends "base.html" %}
+
+{% block content %}
+<div class="bg-white rounded-lg shadow-lg p-6">
+    <h2 class="text-2xl font-bold text-gray-800 mb-6">Reglas de Acceso HTTP</h2>
+    
+    <div class="space-y-3">
+        {% for rule in rules %}
+        <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
+            <div class="flex items-center space-x-4">
+                <div class="flex-shrink-0">
+                    {% if 'allow' in rule %}
+                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
+                            ALLOW
+                        </span>
+                    {% else %}
+                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">
+                            DENY
+                        </span>
+                    {% endif %}
+                </div>
+                <code class="text-sm text-gray-700">{{ rule }}</code>
+            </div>
+            <div class="flex space-x-2">
+                <button class="text-blue-600 hover:text-blue-900">
+                    <i class="fas fa-edit"></i>
+                </button>
+                <button class="text-red-600 hover:text-red-900">
+                    <i class="fas fa-trash"></i>
+                </button>
+            </div>
+        </div>
+        {% endfor %}
+    </div>
+</div>
+{% endblock %}

+ 15 - 0
templates/admin/logs.html

@@ -0,0 +1,15 @@
+{% extends "base.html" %}
+
+{% block content %}
+<div class="space-y-6">
+    {% for log_name, log_lines in logs.items() %}
+    <div class="bg-white rounded-lg shadow-lg p-6">
+        <h2 class="text-xl font-bold text-gray-800 mb-4">{{ log_name }}</h2>
+        
+        <div class="bg-gray-900 rounded-lg p-4 overflow-x-auto max-h-96 overflow-y-auto">
+            <pre class="text-green-400 text-sm font-mono">{% for line in log_lines %}{{ line }}{% endfor %}</pre>
+        </div>
+    </div>
+    {% endfor %}
+</div>
+{% endblock %}

+ 112 - 0
utils/admin.py

@@ -0,0 +1,112 @@
+import os
+import shutil
+from datetime import datetime
+
+# Configuración para Squid
+SQUID_CONFIG_PATH = '/etc/squid/squid.conf'
+BACKUP_DIR = '/etc/squid/backups'
+ACL_FILES_DIR = '/etc/squid/acls'
+
+
+class SquidConfigManager:
+    def __init__(self, config_path=SQUID_CONFIG_PATH):
+        self.config_path = config_path
+        self.config_content = ""
+        self.load_config()
+    def load_config(self):
+        """Cargar el archivo de configuración"""
+        try:
+            with open(self.config_path, encoding='utf-8') as f:
+                self.config_content = f.read()
+        except FileNotFoundError:
+            self.config_content = ""
+    def save_config(self, content):
+        """Guardar la configuración con backup"""
+        # Crear backup
+        self.create_backup()
+        # Guardar nueva configuración
+        with open(self.config_path, 'w', encoding='utf-8') as f:
+            f.write(content)
+        self.config_content = content
+    def create_backup(self):
+        """Crear backup de la configuración actual"""
+        if not os.path.exists(BACKUP_DIR):
+            os.makedirs(BACKUP_DIR)
+        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
+        backup_path = os.path.join(BACKUP_DIR, f'squid.conf.backup_{timestamp}')
+        shutil.copy2(self.config_path, backup_path)
+
+    def get_acls(self):
+        """Extraer ACLs del archivo de configuración"""
+        acls = []
+        lines = self.config_content.split('\n')
+        for line in lines:
+            line = line.strip()
+            if line.startswith('acl ') and not line.startswith('#'):
+                parts = line.split()
+                if len(parts) >= 3:
+                    acl_name = parts[1]
+                    acl_type = parts[2]
+                    acl_value = ' '.join(parts[3:]) if len(parts) > 3 else ''
+                    acls.append({
+                        'name': acl_name,
+                        'type': acl_type,
+                        'value': acl_value,
+                        'full_line': line
+                    })
+        return acls
+
+    def get_delay_pools(self):
+        """Extraer configuración de delay pools"""
+        delay_pools = []
+        lines = self.config_content.split('\n')
+        for line in lines:
+            line = line.strip()
+            if line.startswith('delay_pools '):
+                parts = line.split()
+                if len(parts) >= 2:
+                    delay_pools.append({
+                        'directive': 'delay_pools',
+                        'value': parts[1]
+                    })
+            elif line.startswith('delay_class '):
+                parts = line.split()
+                if len(parts) >= 3:
+                    delay_pools.append({
+                        'directive': 'delay_class',
+                        'pool': parts[1],
+                        'class': parts[2]
+                    })
+            elif line.startswith('delay_parameters '):
+                parts = line.split()
+                if len(parts) >= 3:
+                    delay_pools.append({
+                        'directive': 'delay_parameters',
+                        'pool': parts[1],
+                        'parameters': ' '.join(parts[2:])
+                    })
+            elif line.startswith('delay_access '):
+                parts = line.split()
+                if len(parts) >= 4:
+                    delay_pools.append({
+                        'directive': 'delay_access',
+                        'pool': parts[1],
+                        'action': parts[2],
+                        'acl': ' '.join(parts[3:])
+                    })
+        return delay_pools
+
+    def get_http_access_rules(self):
+        """Extraer reglas de acceso HTTP"""
+        rules = []
+        lines = self.config_content.split('\n')
+        for line in lines:
+            line = line.strip()
+            if line.startswith('http_access ') and not line.startswith('#'):
+                parts = line.split()
+                if len(parts) >= 3:
+                    rules.append({
+                        'action': parts[1],
+                        'acl': ' '.join(parts[2:])
+                    })
+        return rules

+ 13 - 13
utils/size.py

@@ -1,15 +1,15 @@
 def size_to_bytes(size_str):
-    # Convierte '123 MB' o '1.2 GB' a bytes
-    size_str = str(size_str).strip().upper()
-    if size_str.endswith("GB"):
-        return int(float(size_str.replace("GB", "").strip()) * 1024**3)
-    elif size_str.endswith("MB"):
-        return int(float(size_str.replace("MB", "").strip()) * 1024**2)
-    elif size_str.endswith("KB"):
-        return int(float(size_str.replace("KB", "").strip()) * 1024)
-    elif size_str.endswith("BYTES"):
-        return int(float(size_str.replace("BYTES", "").strip()))
-    try:
-        return int(size_str)
-    except Exception:
+    if not size_str:
         return 0
+    parts = size_str.strip().split()
+    if len(parts) != 2:
+        return 0
+    value, unit = float(parts[0]), parts[1].upper()
+    multipliers = {
+        "B": 1,
+        "KB": 1024,
+        "MB": 1024**2,
+        "GB": 1024**3,
+        "TB": 1024**4,
+    }
+    return int(value * multipliers.get(unit, 1))