import streamlit as st import json import hashlib import os class ConfigurationPanel: def __init__(self): self.password_file = "admin_config.txt" self.config_file = "app_config.json" def verify_admin_password(self, password_input): """Verificar contraseña de administrador de forma segura""" try: # Crear archivo de configuración si no existe if not os.path.exists(self.password_file): # Contraseña por defecto: "admin123" (debes cambiarla) default_password_hash = hashlib.sha256("admin123".encode()).hexdigest() with open(self.password_file, 'w') as f: f.write(default_password_hash) return False # Leer hash almacenado with open(self.password_file, 'r') as f: stored_hash = f.read().strip() # Verificar contraseña input_hash = hashlib.sha256(password_input.encode()).hexdigest() return input_hash == stored_hash except Exception as e: st.error(f"Error verificando contraseña: {e}") return False def show_password_modal(self, action_type): """Mostrar modal para verificar contraseña para diferentes acciones""" # Inicializar estados por tipo de acción modal_key = f'show_password_{action_type}' attempts_key = f'password_attempts_{action_type}' if modal_key not in st.session_state: st.session_state[modal_key] = False if attempts_key not in st.session_state: st.session_state[attempts_key] = 0 # Si la sección está visible if st.session_state[modal_key]: st.markdown("---") st.warning("🔒 **ACCIÓN ADMINISTRATIVA - Se requiere contraseña**") max_attempts = 3 remaining = max_attempts - st.session_state[attempts_key] # Verificar si se alcanzó el límite de intentos if st.session_state[attempts_key] >= max_attempts: st.error("🚫 **Demasiados intentos fallidos. Sección bloqueada.**") if st.button("❌ Cerrar", key=f"close_blocked_{action_type}"): st.session_state[modal_key] = False st.session_state[attempts_key] = 0 st.rerun() return False st.write(f"**Intentos restantes:** {remaining}") # Input de contraseña password = st.text_input( "**Contraseña de administrador:**", type="password", help="Ingresa la contraseña para ejecutar esta acción", key=f"admin_password_{action_type}" ) col1, col2 = st.columns(2) with col1: if st.button("✅ Verificar", type="primary", key=f"verify_{action_type}"): if password: if self.verify_admin_password(password): # ✅ CONTRASEÑA CORRECTA st.session_state[modal_key] = False st.session_state[attempts_key] = 0 return True # Acción autorizada else: # ❌ CONTRASEÑA INCORRECTA st.session_state[attempts_key] += 1 remaining_after = max_attempts - st.session_state[attempts_key] if remaining_after > 0: st.error(f"❌ **Contraseña incorrecta.** Te quedan {remaining_after} intentos.") else: st.error("❌ **Contraseña incorrecta.** No te quedan más intentos.") st.rerun() else: st.warning("⚠️ Por favor ingresa una contraseña") with col2: if st.button("❌ Cancelar", key=f"cancel_{action_type}"): st.session_state[modal_key] = False st.session_state[attempts_key] = 0 st.rerun() return False def save_configuration(self): """Guardar configuración actual""" try: config = { "theme": { "primary_color": st.session_state.get("primary_color", "#FF4B4B"), "secondary_color": st.session_state.get("secondary_color", "#00D4AA"), "dark_mode": st.session_state.get("dark_mode", True), "layout_type": st.session_state.get("layout_type", "Wide"), "sidebar_width": st.session_state.get("sidebar_width", 280) }, "modules": { "max_file_size": st.session_state.get("max_file_size", 100), "max_rows": st.session_state.get("max_rows", 50000), "api_framework": st.session_state.get("api_framework", "FastAPI"), "auto_docs": st.session_state.get("auto_docs", True), "auto_validation": st.session_state.get("auto_validation", True), "db_engine": st.session_state.get("db_engine", "SQLite"), "auto_backup": st.session_state.get("auto_backup", True), "auto_indexes": st.session_state.get("auto_indexes", True) } } with open(self.config_file, 'w') as f: json.dump(config, f, indent=2) return True except Exception as e: st.error(f"Error guardando configuración: {e}") return False def show(): config_panel = ConfigurationPanel() st.header("🎛️ Panel de Configuración Avanzado") col1, col2 = st.columns([2, 1]) with col1: # Configuración de temas st.subheader("🎨 Personalización de Tema") theme_tab1, theme_tab2, theme_tab3 = st.tabs(["Colores", "Layout", "Avanzado"]) with theme_tab1: primary_color = st.color_picker("Color primario", "#FF4B4B", key="primary_color") secondary_color = st.color_picker("Color secundario", "#00D4AA", key="secondary_color") dark_mode = st.toggle("Modo oscuro", value=True, key="dark_mode") with theme_tab2: layout_type = st.selectbox("Tipo de layout", ["Wide", "Centered", "Compact"], key="layout_type") sidebar_width = st.slider("Ancho del sidebar", 200, 400, 280, key="sidebar_width") with theme_tab3: st.checkbox("Animaciones suaves", value=True, key="smooth_animations") st.checkbox("Sombras y profundidad", value=True, key="shadows") st.checkbox("Efectos hover", value=True, key="hover_effects") with col2: st.subheader("⚡ Estado del Sistema") st.metric("Módulos cargados", "6/6", "100%") st.metric("Memoria usada", "45%", "2%") st.metric("Rendimiento", "Óptimo", "0%") st.subheader("🔧 Acciones Rápidas") # BOTÓN 1: Reiniciar Session State (REQUIERE CONTRASEÑA) if 'show_password_reset_session' not in st.session_state: st.session_state.show_password_reset_session = False if not st.session_state.show_password_reset_session: if st.button("🔄 Reiniciar Session State", use_container_width=True, key="reset_session_btn"): st.session_state.show_password_reset_session = True st.rerun() if config_panel.show_password_modal("reset_session"): # Ejecutar acción de reinicio keys_to_delete = [key for key in st.session_state.keys() if not key.startswith('password') and not key.startswith('show_password')] for key in keys_to_delete: del st.session_state[key] st.success("✅ Session State reiniciado correctamente") st.rerun() # BOTÓN 2: Limpiar Cache (NO REQUIERE CONTRASEÑA - acción segura) if st.button("🗑️ Limpiar Cache", use_container_width=True, key="clear_cache_btn"): st.cache_data.clear() st.success("✅ Cache limpiado correctamente") # BOTÓN 3: Estado Completo (REQUIERE CONTRASEÑA) if 'show_password_show_state' not in st.session_state: st.session_state.show_password_show_state = False if not st.session_state.show_password_show_state: if st.button("📊 Estado Completo", use_container_width=True, key="show_state_btn"): st.session_state.show_password_show_state = True st.rerun() if config_panel.show_password_modal("show_state"): # Mostrar estado completo st.json({k: str(type(v)) for k, v in st.session_state.items()}) # Configuración de funcionalidades st.subheader("🛠️ Configuración de Módulos") mod_col1, mod_col2, mod_col3 = st.columns(3) with mod_col1: st.markdown("**📊 Procesamiento**") st.slider("Tamaño máximo de archivo (MB)", 1, 500, 100, key="max_file_size") st.number_input("Límite de filas para análisis", 1000, 1000000, 50000, key="max_rows") with mod_col2: st.markdown("**⚡ Generación API**") # FRAMEWORKS AGREGADOS st.selectbox( "Framework API", [ "FastAPI", "Flask", "Django REST Framework", "Express.js (Node.js)", "Spring Boot (Java)", "ASP.NET Core (C#)", "Gin (Go)", "Rocket (Rust)" ], key="api_framework" ) st.checkbox("Auto-documentación", value=True, key="auto_docs") st.checkbox("Validación automática", value=True, key="auto_validation") with mod_col3: st.markdown("**🗃️ Base de Datos**") # MONGODB AGREGADO st.selectbox( "Motor DB", [ "SQLite", "PostgreSQL", "MySQL", "MongoDB", "MariaDB", "SQL Server", "Oracle DB", "CouchDB", "Cassandra", "Redis" ], key="db_engine" ) st.checkbox("Backup automático", value=True, key="auto_backup") st.checkbox("Índices automáticos", value=True, key="auto_indexes") # Botones de acción st.markdown("---") action_col1, action_col2, action_col3 = st.columns(3) with action_col1: # BOTÓN: Guardar Configuración (NO REQUIERE CONTRASEÑA) if st.button("💾 Guardar Configuración", use_container_width=True, key="save_config_btn"): if config_panel.save_configuration(): st.success("✅ Configuración guardada exitosamente!") with action_col2: # BOTÓN: Restablecer Valores (REQUIERE CONTRASEÑA) if 'show_password_reset_values' not in st.session_state: st.session_state.show_password_reset_values = False if not st.session_state.show_password_reset_values: if st.button("🔄 Restablecer Valores", use_container_width=True, key="reset_values_btn"): st.session_state.show_password_reset_values = True st.rerun() if config_panel.show_password_modal("reset_values"): # Restablecer valores predeterminados st.session_state.max_file_size = 100 st.session_state.max_rows = 50000 st.session_state.api_framework = "FastAPI" st.session_state.db_engine = "SQLite" st.success("✅ Valores restablecidos a predeterminados") st.rerun() with action_col3: # BOTÓN: Exportar Configuración (NO REQUIERE CONTRASEÑA) if st.button("📥 Exportar Configuración", use_container_width=True, key="export_config_btn"): if config_panel.save_configuration(): try: with open(config_panel.config_file, 'r') as f: config_data = f.read() st.download_button( label="⬇️ Descargar Configuración JSON", data=config_data, file_name="app_config.json", mime="application/json", use_container_width=True ) except Exception as e: st.error(f"Error exportando configuración: {e}") if __name__ == "__main__": show()