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

58 lines
2.2 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'
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 FROM api_keys WHERE id = ?').get(id)
if (!existing) return NextResponse.json({ error: 'API Key 不存在' }, { status: 404 })
getDb().prepare('DELETE FROM api_keys WHERE id = ?').run(id)
return NextResponse.json({ success: true })
}