const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const adminSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true }, password: { type: String, required: true }, email: { type: String, required: true, unique: true }, role: { type: String, enum: ['superadmin', 'admin', 'editor'], default: 'editor' }, permissions: [{ type: String, enum: [ 'user:manage', // 用户管理权限 'game:manage', // 游戏管理权限 'category:manage', // 分类管理权限 'media:manage', // 媒体管理权限 'system:manage' // 系统管理权限 ] }], status: { type: String, enum: ['active', 'inactive'], default: 'active' }, lastLogin: Date, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' }, createdAt: { type: Date, default: Date.now } }); // 密码加密 adminSchema.pre('save', async function(next) { if (this.isModified('password')) { this.password = await bcrypt.hash(this.password, 10); } next(); }); // 根据角色设置默认权限 adminSchema.pre('save', function(next) { if (this.isNew || this.isModified('role')) { switch (this.role) { case 'superadmin': this.permissions = [ 'user:manage', 'game:manage', 'category:manage', 'media:manage', 'system:manage' ]; break; case 'admin': this.permissions = [ 'game:manage', 'category:manage', 'media:manage' ]; break; case 'editor': this.permissions = [ 'game:manage', 'media:manage' ]; break; } } next(); }); module.exports = mongoose.model('Admin', adminSchema);