From fd6c93cb3021f6fcd443a483d8e4dda7508fd332 Mon Sep 17 00:00:00 2001 From: gaoziman <2942894660@qq.com> Date: Sun, 21 Dec 2025 14:04:01 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E8=81=8A=E5=A4=A9):=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E8=AE=A4=E8=AF=81=E5=92=8C=20API=20Key=20?= =?UTF-8?q?=E8=A7=A3=E5=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 聊天前检查用户登录状态 - 获取当前用户的设置和 API Key - 使用时解密 API Key - 优化未配置 API Key 的错误提示 --- src/app/api/chat/route.ts | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.ts index af164e9..cbb338b 100644 --- a/src/app/api/chat/route.ts +++ b/src/app/api/chat/route.ts @@ -4,6 +4,8 @@ import { conversations, messages, userSettings } from '@/drizzle/schema'; import { eq } from 'drizzle-orm'; import { nanoid } from 'nanoid'; import { executeTool } from '@/services/tools'; +import { getCurrentUser } from '@/lib/auth'; +import { decryptApiKey } from '@/lib/crypto'; interface ChatRequest { conversationId: string; @@ -212,18 +214,30 @@ export async function POST(request: Request) { })) : undefined, }); - // 获取用户设置 + // 获取当前登录用户 + const user = await getCurrentUser(); + if (!user) { + return NextResponse.json( + { error: '请先登录后再使用聊天功能' }, + { status: 401 } + ); + } + + // 获取该用户的设置 const settings = await db.query.userSettings.findFirst({ - where: eq(userSettings.id, 1), + where: eq(userSettings.userId, user.userId), }); if (!settings?.cchApiKey) { return NextResponse.json( - { error: 'Please configure your CCH API key in settings' }, + { error: '请先在设置中配置您的 API Key 才能使用聊天功能', code: 'API_KEY_NOT_CONFIGURED' }, { status: 400 } ); } + // 解密 API Key + const decryptedApiKey = decryptApiKey(settings.cchApiKey); + // 获取对话信息 const conversation = await db.query.conversations.findFirst({ where: eq(conversations.conversationId, conversationId), @@ -267,7 +281,7 @@ export async function POST(request: Request) { const stream = new ReadableStream({ async start(controller) { try { - const cchUrl = settings.cchUrl || 'http://localhost:13500'; + const cchUrl = settings.cchUrl || process.env.CCH_DEFAULT_URL || 'https://claude.leocoder.cn/'; // 获取系统提示词(叠加模式) // 1. 始终使用 DEFAULT_SYSTEM_PROMPT 作为基础 @@ -302,7 +316,7 @@ export async function POST(request: Request) { // ==================== Codex 模型处理(OpenAI 格式) ==================== const result = await handleCodexChat({ cchUrl, - apiKey: settings.cchApiKey!, + apiKey: decryptedApiKey, model: useModel, systemPrompt, temperature, @@ -321,7 +335,7 @@ export async function POST(request: Request) { // ==================== Claude 模型处理(原有逻辑) ==================== const result = await handleClaudeChat({ cchUrl, - apiKey: settings.cchApiKey!, + apiKey: decryptedApiKey, model: useModel, systemPrompt, temperature,