2026-02-13 15:16:54 -08:00

77 lines
2.7 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { validateSession, hasServerPermission } from '@/lib/auth'
import connectToDatabase from '@/lib/mongodb'
import { Server } from '@/lib/models'
import { isValidObjectId } from '@/lib/input-validation'
import { createAuditLog, getClientIP } from '@/lib/audit'
import { getServerPath } from '@/lib/docker'
import { rename } from 'fs/promises'
import path from 'path'
// POST /api/servers/[id]/plugins/[filename]/toggle — Enable/disable a plugin
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string; filename: string }> }
) {
const clientIP = getClientIP(request)
try {
const session = await validateSession(request)
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { id, filename } = await params
if (!isValidObjectId(id)) {
return NextResponse.json({ error: 'Invalid server ID' }, { status: 400 })
}
const decodedFilename = decodeURIComponent(filename)
await connectToDatabase()
const server = await Server.findById(id)
if (!server || server.type !== 'bukkit') {
return NextResponse.json({ error: 'Server not found or not a Bukkit server' }, { status: 404 })
}
const adminIds = server.admins.map((a) => a.toString())
if (!hasServerPermission(session, 'plugins:toggle', adminIds)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
const pluginsDir = path.join(getServerPath(server._id.toString()), 'plugins')
const currentPath = path.join(pluginsDir, decodedFilename)
const isEnabled = decodedFilename.endsWith('.jar') && !decodedFilename.endsWith('.jar.disabled')
const newFilename = isEnabled
? `${decodedFilename}.disabled`
: decodedFilename.replace('.jar.disabled', '.jar')
const newPath = path.join(pluginsDir, newFilename)
try {
await rename(currentPath, newPath)
} catch {
return NextResponse.json({ error: 'Plugin file not found' }, { status: 404 })
}
await createAuditLog({
action: isEnabled ? 'plugin_disabled' : 'plugin_enabled',
entityType: 'plugin',
entityName: decodedFilename,
userId: session._id,
userName: session.username,
userEmail: session.email,
previousValues: { filename: decodedFilename },
newValues: { filename: newFilename },
clientIP,
status: 'success',
statusCode: 200,
})
return NextResponse.json({ success: true, message: `Plugin ${isEnabled ? 'disabled' : 'enabled'}. Restart to apply.` })
} catch (error) {
console.error('Toggle plugin error:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}