mirror of
https://github.com/rmoren97/mc-manager.git
synced 2026-03-28 17:26:47 -07:00
76 lines
2.6 KiB
TypeScript
76 lines
2.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { validateSession, hasPermission } 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 })
|
|
}
|
|
|
|
if (!hasPermission(session, 'plugins:toggle')) {
|
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
}
|
|
|
|
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 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 })
|
|
}
|
|
}
|