117 lines
3.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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 } from '@/lib/department-permission';
import {
ApiKeyEncryptionConfigError,
createApiKey,
getApiKeyPreview,
getApiKeys,
} 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;
if (!(await isSuperAdmin(userId))) {
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;
if (!(await isSuperAdmin(userId))) {
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 创建成功,之后仍可由超级管理员按需查看',
},
{ headers: { 'Cache-Control': 'no-store, max-age=0', Pragma: 'no-cache' } },
);
} catch (error) {
if (error instanceof ApiKeyEncryptionConfigError) {
return NextResponse.json(
{ success: false, error: 'API Key 加密配置缺失,请联系运维配置后重试' },
{ status: 503 },
);
}
console.error('[admin/api-keys] POST error:', error);
return NextResponse.json(
{ success: false, error: '服务器错误' },
{ status: 500 }
);
}
}