chenpei ea9076df45 feat: 实现统一的下载错误处理系统并修复产品全案数据库Schema
- 创建统一的下载错误处理模块 (lib/download-errors.ts)
- 实现13种错误类型分类和中文错误消息
- 后端统一使用 createDownloadError 创建标准化错误响应
- 前端统一使用 parseDownloadError 解析错误并显示
- 修复正式系统数据库Schema,添加产品全案相关字段和表
- 执行数据库迁移:添加 task_no, task_status, task_fetched_at 字段
- 创建 material_assets, api_keys, api_call_logs 表
2026-01-05 17:52:42 +08:00

107 lines
2.8 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, hasSystemAdminPermission } from '@/lib/department-permission';
import { getApiKeys, createApiKey } from '@/lib/external-api';
/**
* GET - 获取 API Key 列表
*/
export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ success: false, error: '未登录' },
{ status: 401 }
);
}
// 检查权限(仅超级管理员和系统管理员可访问)
const isSuperAdminUser = await isSuperAdmin(session.user.id);
const hasPermission = hasSystemAdminPermission(session.user.role, 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: k.key.substring(0, 8) + '...',
}));
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?.id) {
return NextResponse.json(
{ success: false, error: '未登录' },
{ status: 401 }
);
}
// 检查权限
const isSuperAdminUser = await isSuperAdmin(session.user.id);
const hasPermission = hasSystemAdminPermission(session.user.role, 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(), session.user.id);
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 }
);
}
}