An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
refactor: rename createToolCallingStreamResponse to createChatStreamResponse and update auth logic
Yoshiki Miurafdea49ca73b0
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex 3f2fba19..05361305 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -1,5 +1,5 @@import { getCurrentUserId } from '@/lib/auth/get-current-user'-import { createToolCallingStreamResponse } from '@/lib/streaming/create-tool-calling-stream'+import { createChatStreamResponse } from '@/lib/streaming/create-chat-stream-response'import { Model } from '@/lib/types/models'import { isProviderEnabled } from '@/lib/utils/registry'import { cookies } from 'next/headers'@@ -56,7 +56,7 @@ export async function POST(req: Request) {)}- return createToolCallingStreamResponse({+ return await createChatStreamResponse({message,model: selectedModel,chatId,diff --git a/lib/streaming/create-tool-calling-stream.ts b/lib/streaming/create-chat-stream-response.tssimilarity index 58%rename from lib/streaming/create-tool-calling-stream.tsrename to lib/streaming/create-chat-stream-response.tsindex 262e75fe..6f15870b 100644--- a/lib/streaming/create-tool-calling-stream.ts+++ b/lib/streaming/create-chat-stream-response.ts@@ -14,44 +14,50 @@ import { generateUUID } from '../utils'import { getTextFromParts } from '../utils/message-utils'import { BaseStreamConfig } from './types'-export function createToolCallingStreamResponse(config: BaseStreamConfig) {+export async function createChatStreamResponse(+ config: BaseStreamConfig+): Promise<Response> {+ const { message, model, chatId, searchMode, userId } = config+ const modelId = `${model.providerId}:${model.id}`++ // Fetch chat data for authorization check before stream creation+ const chatForAuth = await getChat(chatId, userId)++ // Authorization check: if chat exists and does not belong to the user+ if (chatForAuth && chatForAuth.userId !== userId) {+ return new Response('You are not allowed to access this chat', {+ status: 403,+ statusText: 'Forbidden'+ })+ }++ // If authorized or it's a new chat, proceed to create the streamconst stream = createUIMessageStream({execute: async (writer: UIMessageStreamWriter) => {- const { message, model, chatId, searchMode, userId } = config- const modelId = `${model.providerId}:${model.id}`-try {- const chat = await getChat(chatId, userId)- if (!chat) {+ // Use chatForAuth (from outer scope) to decide new/existing path+ if (!chatForAuth) {+ // New chatconst userContent = getTextFromParts(message.parts)const title = await generateChatTitle({userMessageContent: userContent,- model: openai('gpt-4o-mini')+ model: openai('gpt-4o-mini') // TODO: Consider making this model configurable})-await saveChatMessage(chatId, message, userId, title)} else {- if (chat.userId !== userId) {- // TODO: Handle this- // return new Response('You are not allowed to access this chat', {- // status: 403,- // statusText: 'Forbidden'- // })- }-- // Save just the user message to an existing chat+ // Existing chat, and user is authorized (auth check done outside)await saveSingleMessage(chatId, message)}const previousMessages = await getChatMessages(chatId)- const messages = appendClientMessage({+ const messagesToModel = appendClientMessage({// @ts-ignoremessages: previousMessages,message})const result = await researcher({- messages: convertToModelMessages(messages),+ messages: convertToModelMessages(messagesToModel),model: modelId,searchMode})@@ -59,9 +65,9 @@ export function createToolCallingStreamResponse(config: BaseStreamConfig) {writer.merge(result.toUIMessageStream({newMessageId: generateUUID(),- onFinish({ messages }) {- const assistantMessage = messages.find(- message => message.role === 'assistant'+ onFinish({ messages: resultingMessages }) {+ const assistantMessage = resultingMessages.find(+ m => m.role === 'assistant')if (assistantMessage) {saveSingleMessage(chatId, assistantMessage)@@ -71,7 +77,7 @@ export function createToolCallingStreamResponse(config: BaseStreamConfig) {)} catch (error) {console.error('Stream execution error:', error)- throw error+ throw error // This error will be handled by the onError callback}},onError: (error: any) => {