Files
pfandsystem-demo/backend/scripts/bootstrap.js

53 lines
1.7 KiB
JavaScript
Raw Normal View History

import bcrypt from 'bcrypt';
import pool from '../config/database.js';
const EXPIRY_COLS = ['notified_7d_at', 'notified_1d_at', 'notified_expired_at'];
async function ensureExpiryColumns() {
const [cols] = await pool.query(
`SELECT COLUMN_NAME FROM information_schema.columns
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'tenants'`
);
const have = new Set(cols.map(c => c.COLUMN_NAME));
for (const col of EXPIRY_COLS) {
if (!have.has(col)) {
await pool.query(`ALTER TABLE tenants ADD COLUMN ${col} TIMESTAMP NULL`);
console.log('[bootstrap] tenants ALTER ADD', col);
}
}
}
export async function bootstrapSuperAdmin() {
// Auf DB warten (max 30s)
for (let i = 0; i < 30; i++) {
try { await pool.query('SELECT 1'); break; }
catch { await new Promise(r => setTimeout(r, 1000)); }
}
// Migrations
try { await ensureExpiryColumns(); }
catch (e) { console.error('[bootstrap] Migration-Fehler:', e.message); }
const email = process.env.SUPERADMIN_EMAIL;
const password = process.env.SUPERADMIN_PASSWORD;
if (!email || !password) {
console.warn('[bootstrap] SUPERADMIN_EMAIL/PASSWORD nicht gesetzt - skip');
return;
}
const [rows] = await pool.query(
"SELECT id FROM mitarbeiter WHERE email = ? AND tenant_id IS NULL AND rolle = 'superadmin'",
[email]
);
if (rows.length > 0) {
console.log('[bootstrap] SuperAdmin existiert:', email);
return;
}
const hash = await bcrypt.hash(password, 10);
await pool.query(
`INSERT INTO mitarbeiter (id, tenant_id, email, password_hash, name, rolle, aktiv)
VALUES (UUID(), NULL, ?, ?, 'SuperAdmin', 'superadmin', 1)`,
[email, hash]
);
console.log('[bootstrap] SuperAdmin angelegt:', email);
}