import { NextResponse } from 'next/server' import { cookies } from 'next/headers' import db from '@/lib/db' import { verifyJwt, generateApiKey, hashApiKey } from '@/lib/auth' import { checkPermission } from '@/lib/permissions' async function getSession() { const cookieStore = await cookies() const token = cookieStore.get('session_assets')?.value if (!token) return null return verifyJwt(token) } export async function GET() { const session = await getSession() if (!session) return NextResponse.json({ error: '未授权' }, { status: 401 }) if (!checkPermission(session.role, 'api-keys:read')) { return NextResponse.json({ error: '权限不足' }, { status: 403 }) } const keys = db.prepare('SELECT id, name, permissions, last_used_at, expires_at, is_active, created_at FROM api_keys ORDER BY id DESC').all() return NextResponse.json({ keys }) } export async function POST(request: Request) { 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 }) } try { const body = await request.json() const { name, permissions, expires_at } = body if (!name) { return NextResponse.json({ error: '名称不能为空' }, { status: 400 }) } const key = generateApiKey() const keyHash = hashApiKey(key) const perms = JSON.stringify(permissions || ['assets:read']) const result = db.prepare('INSERT INTO api_keys (name, key_hash, permissions, expires_at, created_by) VALUES (?, ?, ?, ?, ?)') .run(name, keyHash, perms, expires_at || null, session.userId) const apiKey = db.prepare('SELECT id, name, permissions, expires_at, is_active, created_at FROM api_keys WHERE id = ?').get(result.lastInsertRowid) return NextResponse.json({ key, apiKey }, { status: 201 }) } catch (e) { const msg = e instanceof Error ? e.message : '创建 API Key 失败' return NextResponse.json({ error: msg }, { status: 500 }) } }