#!/usr/bin/env node import mongoose from 'mongoose'; import bcrypt from 'bcryptjs'; import dotenv from 'dotenv'; // 加载环境变量 dotenv.config(); // 用户模型 const UserSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true, trim: true }, email: { type: String, required: true, unique: true, lowercase: true, trim: true }, password: { type: String, required: true }, role: { type: String, enum: ['admin', 'user', 'viewer'], default: 'user' }, isActive: { type: Boolean, default: true }, createdAt: { type: Date, default: Date.now } }); const User = mongoose.model('User', UserSchema); async function createAdminUser() { try { // 连接数据库 const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27018/marketing_agent'; await mongoose.connect(mongoUri); console.log('Connected to MongoDB'); // 检查是否已有管理员 const existingAdmin = await User.findOne({ username: 'admin' }); if (existingAdmin) { console.log('Admin user already exists'); process.exit(0); } // 创建管理员账号 const adminPassword = await bcrypt.hash('admin123456', 10); const admin = new User({ username: 'admin', email: 'admin@marketing-agent.com', password: adminPassword, role: 'admin', isActive: true }); await admin.save(); console.log('Admin user created successfully:'); console.log('Username: admin'); console.log('Password: admin123456'); console.log('Please change the password after first login!'); // 创建测试用户 const testPassword = await bcrypt.hash('test123456', 10); const testUser = new User({ username: 'test', email: 'test@marketing-agent.com', password: testPassword, role: 'user', isActive: true }); await testUser.save(); console.log('\nTest user created successfully:'); console.log('Username: test'); console.log('Password: test123456'); } catch (error) { console.error('Error creating admin user:', error); } finally { await mongoose.disconnect(); process.exit(0); } } createAdminUser();