71 lines
2.0 KiB
TypeScript
71 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
|
|
import { authOptions } from '@/lib/auth';
|
|
import { isSuperAdmin } from '@/lib/department-permission';
|
|
import {
|
|
ApiKeyEncryptionConfigError,
|
|
ApiKeyNotRecoverableError,
|
|
revealApiKey,
|
|
} from '@/lib/external-api';
|
|
|
|
const NO_STORE_HEADERS = {
|
|
'Cache-Control': 'no-store, max-age=0',
|
|
Pragma: 'no-cache',
|
|
};
|
|
|
|
export async function POST(
|
|
_request: NextRequest,
|
|
{ params }: { params: { id: string } },
|
|
) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
const userId = (session?.user as { id?: string } | undefined)?.id;
|
|
if (!userId) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '未登录' },
|
|
{ status: 401, headers: NO_STORE_HEADERS },
|
|
);
|
|
}
|
|
|
|
if (!(await isSuperAdmin(userId))) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '仅超级管理员可查看' },
|
|
{ status: 403, headers: NO_STORE_HEADERS },
|
|
);
|
|
}
|
|
|
|
const key = await revealApiKey(params.id, userId);
|
|
if (!key) {
|
|
return NextResponse.json(
|
|
{ success: false, error: 'API Key 不存在' },
|
|
{ status: 404, headers: NO_STORE_HEADERS },
|
|
);
|
|
}
|
|
|
|
return NextResponse.json(
|
|
{ success: true, data: { key } },
|
|
{ headers: NO_STORE_HEADERS },
|
|
);
|
|
} catch (error) {
|
|
if (error instanceof ApiKeyNotRecoverableError) {
|
|
return NextResponse.json(
|
|
{ success: false, error: error.message, code: 'API_KEY_NOT_RECOVERABLE' },
|
|
{ status: 409, headers: NO_STORE_HEADERS },
|
|
);
|
|
}
|
|
if (error instanceof ApiKeyEncryptionConfigError) {
|
|
return NextResponse.json(
|
|
{ success: false, error: 'API Key 加密配置缺失,请联系运维配置后重试' },
|
|
{ status: 503, headers: NO_STORE_HEADERS },
|
|
);
|
|
}
|
|
|
|
console.error('[admin/api-keys/[id]/reveal] POST error:', error);
|
|
return NextResponse.json(
|
|
{ success: false, error: '读取 API Key 失败' },
|
|
{ status: 500, headers: NO_STORE_HEADERS },
|
|
);
|
|
}
|
|
}
|