Files
PANEL_BASES_ANEXO24/scripts/init-database.js
AlexeerCT 0bf9c9e68d Refactor database configuration and user management
- Updated .env.example to consolidate SQL Server credentials under PANEL_MSSQL_* variables.
- Removed deprecated docker-compose.postgres.yml file.
- Adjusted docker-compose.yml to utilize new SQL Server credential structure.
- Enhanced README.md with Docker build and push instructions.
- Refined database schema in schema.sql to align with new user and permission structures.
- Updated init-database.js to reflect changes in user and session table names.
- Modified user management functions in users.ts to accommodate new database schema.
- Streamlined API routes to utilize PostgreSQL for user and database management.
- Improved error handling and logging in various server routes.
2026-04-14 14:16:11 -05:00

116 lines
4.2 KiB
JavaScript

// Script para inicializar la base de datos PostgreSQL
import { Pool } from 'pg';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Configuración de PostgreSQL (Docker local)
const pool = new Pool({
host: 'localhost',
port: 5432,
database: 'CONTROLDESK',
user: 'postgres',
password: 'Control.',
max: 1
});
async function initDatabase() {
console.log('=================================');
console.log('Inicializando Base de Datos');
console.log('=================================\n');
try {
// Leer el archivo SQL
const schemaPath = path.join(__dirname, '..', 'database', 'schema.sql');
console.log('1. Leyendo schema.sql...');
const sql = fs.readFileSync(schemaPath, 'utf8');
// Conectar a PostgreSQL
console.log('2. Conectando a PostgreSQL...');
const client = await pool.connect();
console.log(' ✓ Conectado exitosamente\n');
// Ejecutar el script SQL
console.log('3. Ejecutando script SQL...');
await client.query(sql);
console.log(' ✓ Tablas creadas exitosamente\n');
// Verificar las tablas creadas
console.log('4. Verificando tablas creadas...');
const result = await client.query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'a24c'
AND table_name IN (
'dashboard_users',
'dashboard_user_database_permissions',
'dashboard_sessions'
)
ORDER BY table_name;
`);
if (result.rows.length === 3) {
console.log(' ✓ Tablas verificadas (esquema a24c):');
result.rows.forEach(row => {
console.log(` - a24c.${row.table_name}`);
});
} else {
console.log(' ⚠ No todas las tablas fueron creadas');
}
// Verificar usuario admin
console.log('\n5. Verificando usuario admin...');
const userResult = await client.query(
'SELECT username, email, is_admin FROM a24c.dashboard_users WHERE username = $1',
['admin']
);
if (userResult.rows.length > 0) {
console.log(' ✓ Usuario admin creado:');
console.log(` - Username: ${userResult.rows[0].username}`);
console.log(` - Email: ${userResult.rows[0].email}`);
console.log(` - Es Admin: ${userResult.rows[0].is_admin}`);
} else {
console.log(' ⚠ Usuario admin no encontrado');
}
client.release();
console.log('\n=================================');
console.log('✓ Inicialización Completa');
console.log('=================================\n');
console.log('IMPORTANTE: Ahora debes actualizar la contraseña del admin:');
console.log('1. Ejecuta: node scripts/generate-password-hash.js');
console.log('2. Copia el hash generado');
console.log('3. Ejecuta este SQL en PostgreSQL:');
console.log(' UPDATE a24c.dashboard_users SET password_hash = \'TU_HASH_AQUI\' WHERE username = \'admin\';');
console.log('\n4. Luego inicia el servidor: npm run dev');
console.log('5. Ve a: http://localhost:5173/login');
console.log(' Usuario: admin');
console.log(' Contraseña: Admin123!\n');
} catch (error) {
console.error('\n❌ Error durante la inicialización:');
console.error(error.message);
if (error.code === 'ECONNREFUSED' || error.code === 'ETIMEDOUT') {
console.error('\n⚠ No se pudo conectar a PostgreSQL.');
console.error('Verifica que:');
console.error('1. PostgreSQL esté corriendo en Docker:');
console.error(' docker-compose -f docker-compose.postgres.yml up -d');
console.error('2. Verifica el estado: docker ps');
console.error('3. Ve los logs: docker-compose -f docker-compose.postgres.yml logs postgres');
}
process.exit(1);
} finally {
await pool.end();
}
}
// Ejecutar
initDatabase();