issue-ai/src/app/api/api-keys/[id]/route.ts

72 lines
2.5 KiB
TypeScript

import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { getDb } from '@/lib/db'
import { verifyToken } from '@/lib/auth'
import { checkPermission } from '@/lib/permissions'
import { writeAuditLog, getClientIP } from '@/lib/audit'
async function getSession() {
const cookieStore = await cookies()
const token = cookieStore.get('session_issue')?.value
if (!token) return null
return verifyToken(token)
}
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
const session = await getSession()
if (!session) return NextResponse.json({ error: '未授权' }, { status: 401 })
if (!checkPermission(session.role, 'api-keys:write')) {
return NextResponse.json({ error: '权限不足' }, { status: 403 })
}
const { id } = await params
const existing = getDb().prepare('SELECT id FROM api_keys WHERE id = ?').get(id)
if (!existing) return NextResponse.json({ error: 'API Key 不存在' }, { status: 404 })
try {
const body = await request.json()
const { name, permissions, expires_at, is_active } = body
getDb().prepare(
'UPDATE api_keys SET name = ?, permissions = ?, expires_at = ?, is_active = ? WHERE id = ?'
).run(
name,
JSON.stringify(permissions || ['tickets:read']),
expires_at || null,
is_active !== undefined ? (is_active ? 1 : 0) : 1,
id
)
return NextResponse.json({ success: true })
} catch (e) {
const msg = e instanceof Error ? e.message : '更新失败'
return NextResponse.json({ error: msg }, { status: 500 })
}
}
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
const session = await getSession()
if (!session) return NextResponse.json({ error: '未授权' }, { status: 401 })
if (!checkPermission(session.role, 'api-keys:write')) {
return NextResponse.json({ error: '权限不足' }, { status: 403 })
}
const { id } = await params
const existing = getDb().prepare('SELECT id, name FROM api_keys WHERE id = ?').get(id) as { id: number; name: string } | undefined
if (!existing) return NextResponse.json({ error: 'API Key 不存在' }, { status: 404 })
const snapshot = { id: existing.id, name: existing.name }
getDb().prepare('DELETE FROM api_keys WHERE id = ?').run(id)
writeAuditLog({
userId: session.id,
apiKeyId: null,
action: 'delete',
entityType: 'api_key',
entityId: Number(id),
details: { deleted: snapshot },
ipAddress: getClientIP(_request),
})
return NextResponse.json({ success: true })
}