46 lines
1.3 KiB
JavaScript
46 lines
1.3 KiB
JavaScript
// 初始化管理员账号
|
|
require('dotenv').config();
|
|
const bcrypt = require('bcryptjs');
|
|
const { Admin, sequelize } = require('./models');
|
|
|
|
async function initAdmin() {
|
|
try {
|
|
// 使用 force: false 避免 alter 表时的问题
|
|
// 如果表不存在则创建,存在则跳过
|
|
await sequelize.sync({ force: false });
|
|
|
|
// 检查是否已存在管理员账号
|
|
const existingAdmin = await Admin.findOne({ where: { username: 'admin' } });
|
|
|
|
if (existingAdmin) {
|
|
console.log('✓ 管理员账号已存在');
|
|
console.log(' 用户名: admin');
|
|
console.log(' 提示: 如需重置密码,请删除数据库文件后重新初始化');
|
|
process.exit(0);
|
|
return;
|
|
}
|
|
|
|
const hashedPassword = bcrypt.hashSync('admin123', 10);
|
|
await Admin.create({
|
|
username: 'admin',
|
|
password: hashedPassword,
|
|
name: '管理员'
|
|
});
|
|
|
|
console.log('✓ 管理员账号创建成功');
|
|
console.log(' 用户名: admin');
|
|
console.log(' 密码: admin123');
|
|
process.exit(0);
|
|
} catch (error) {
|
|
console.error('✗ 初始化失败:', error.message);
|
|
if (error.name === 'SequelizeUniqueConstraintError') {
|
|
console.error(' 原因: 管理员账号已存在');
|
|
} else {
|
|
console.error(' 详细错误:', error);
|
|
}
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
initAdmin();
|