// 初始化管理员账号 require('dotenv').config(); const bcrypt = require('bcryptjs'); const { Admin, sequelize } = require('./models'); async function initAdmin() { try { await sequelize.sync({ force: false }); // 检查role字段是否存在 const [results] = await sequelize.query("PRAGMA table_info(Admins);"); const hasRoleColumn = results.some(col => col.name === 'role'); if (!hasRoleColumn) { console.log('⚠️ role字段不存在,请先运行迁移: node backend/migrations/index.js'); console.log(' 或运行: npm run migrate (在backend目录)'); process.exit(1); return; } // 检查yvan超级管理员 const yvan = await Admin.findOne({ where: { username: 'yvan' } }); if (!yvan) { const hashedPassword = bcrypt.hashSync('Xu950329.', 10); await Admin.create({ username: 'yvan', password: hashedPassword, name: 'Yvan', role: 'super' }); console.log('✓ 超级管理员yvan创建成功'); } else { // 确保yvan是super角色 if (yvan.role !== 'super') { await yvan.update({ role: 'super' }); console.log('✓ 超级管理员yvan角色已更新'); } else { console.log('✓ 超级管理员yvan已存在'); } } // 检查默认管理员 const admin = await Admin.findOne({ where: { username: 'admin' } }); if (!admin) { const hashedPassword = bcrypt.hashSync('admin123', 10); await Admin.create({ username: 'admin', password: hashedPassword, name: '管理员', role: 'admin' }); console.log('✓ 默认管理员admin创建成功'); } else { // 确保admin是admin角色 if (!admin.role || admin.role === 'super') { await admin.update({ role: 'admin' }); console.log('✓ 默认管理员admin角色已更新'); } else { console.log('✓ 默认管理员admin已存在'); } } console.log('\n初始化完成!'); process.exit(0); } catch (error) { console.error('✗ 初始化失败:', error.message); console.error(' 详细错误:', error); process.exit(1); } } initAdmin();