const User = require('../models/User'); const bcrypt = require('bcryptjs'); /** * Initialize a superadmin user * This will run when the application starts */ const seedSuperAdmin = async () => { try { console.log('Checking for superadmin account...'); // Get credentials from environment variables const email = process.env.SUPERADMIN_EMAIL || 'admin@example.com'; const password = process.env.SUPERADMIN_PASSWORD || 'changeme123'; // Check if superadmin already exists const existingAdmin = await User.findOne({ role: 'superadmin' }); if (existingAdmin) { console.log('Superadmin account already exists'); return existingAdmin; } // Create a new superadmin console.log('Creating superadmin account...'); const superadmin = new User({ email: email, password: password, // This will be hashed by the pre-save hook role: 'superadmin' }); // Save the user to trigger the pre-save hook that hashes the password await superadmin.save(); console.log(`Superadmin created with email: ${email}`); console.log('IMPORTANT: Change the default password after first login!'); // Only store plain password in development for testing if (process.env.NODE_ENV === 'development') { console.log('Development mode: Password is set from SUPERADMIN_PASSWORD env variable'); } return superadmin; } catch (error) { console.error('Error seeding superadmin:', error); throw error; } }; module.exports = seedSuperAdmin;