/** * API Key 管理接口 * GET - 获取 API Key 列表 * POST - 创建新的 API Key */ import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; import { isSuperAdmin, hasSystemAdminPermission } from '@/lib/department-permission'; import { getApiKeys, createApiKey, getApiKeyPreview } from '@/lib/external-api'; /** * GET - 获取 API Key 列表 */ export async function GET(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.user || !(session.user as any).id) { return NextResponse.json( { success: false, error: '未登录' }, { status: 401 } ); } // 检查权限(仅超级管理员和系统管理员可访问) const userId = (session.user as any).id; const userRole = (session.user as any).role; const isSuperAdminUser = await isSuperAdmin(userId); const hasPermission = hasSystemAdminPermission(userRole, isSuperAdminUser); if (!hasPermission) { return NextResponse.json( { success: false, error: '无权限访问' }, { status: 403 } ); } const apiKeys = await getApiKeys(); // 隐藏完整 key,只显示前8位 const maskedKeys = apiKeys.map((k: any) => ({ ...k, key: getApiKeyPreview(k.key), })); return NextResponse.json({ success: true, data: maskedKeys, }); } catch (error) { console.error('[admin/api-keys] GET error:', error); return NextResponse.json( { success: false, error: '服务器错误' }, { status: 500 } ); } } /** * POST - 创建新的 API Key */ export async function POST(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.user || !(session.user as any).id) { return NextResponse.json( { success: false, error: '未登录' }, { status: 401 } ); } // 检查权限 const userId = (session.user as any).id; const userRole = (session.user as any).role; const isSuperAdminUser = await isSuperAdmin(userId); const hasPermission = hasSystemAdminPermission(userRole, isSuperAdminUser); if (!hasPermission) { return NextResponse.json( { success: false, error: '无权限操作' }, { status: 403 } ); } const body = await request.json(); const { name } = body; if (!name || typeof name !== 'string' || name.trim().length === 0) { return NextResponse.json( { success: false, error: '密钥名称不能为空' }, { status: 400 } ); } const apiKey = await createApiKey(name.trim(), userId); return NextResponse.json({ success: true, data: apiKey, message: 'API Key 创建成功,请妥善保管密钥,此密钥仅显示一次', }); } catch (error) { console.error('[admin/api-keys] POST error:', error); return NextResponse.json( { success: false, error: '服务器错误' }, { status: 500 } ); } }