quanyoumi/backend/init-admin.js

73 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 初始化管理员账号
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();