@@ -4,6 +4,7 @@ import { type NextRequest, NextResponse } from 'next/server'
44import { z } from 'zod'
55import { getSession } from '@/lib/auth'
66import { createLogger } from '@/lib/logs/console-logger'
7+ import { getUserId } from '@/app/api/auth/oauth/utils'
78import { db } from '@/db'
89import { document } from '@/db/schema'
910import { checkKnowledgeBaseAccess , processDocumentAsync } from '../../utils'
@@ -269,27 +270,41 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
269270 const { id : knowledgeBaseId } = await params
270271
271272 try {
272- const session = await getSession ( )
273- if ( ! session ?. user ?. id ) {
274- logger . warn ( `[${ requestId } ] Unauthorized document creation attempt` )
275- return NextResponse . json ( { error : 'Unauthorized' } , { status : 401 } )
273+ const body = await req . json ( )
274+ const { workflowId } = body
275+
276+ logger . info ( `[${ requestId } ] Knowledge base document creation request` , {
277+ knowledgeBaseId,
278+ workflowId,
279+ hasWorkflowId : ! ! workflowId ,
280+ bodyKeys : Object . keys ( body ) ,
281+ } )
282+
283+ const userId = await getUserId ( requestId , workflowId )
284+
285+ if ( ! userId ) {
286+ const errorMessage = workflowId ? 'Workflow not found' : 'Unauthorized'
287+ const statusCode = workflowId ? 404 : 401
288+ logger . warn ( `[${ requestId } ] Authentication failed: ${ errorMessage } ` , {
289+ workflowId,
290+ hasWorkflowId : ! ! workflowId ,
291+ } )
292+ return NextResponse . json ( { error : errorMessage } , { status : statusCode } )
276293 }
277294
278- const accessCheck = await checkKnowledgeBaseAccess ( knowledgeBaseId , session . user . id )
295+ const accessCheck = await checkKnowledgeBaseAccess ( knowledgeBaseId , userId )
279296
280297 if ( ! accessCheck . hasAccess ) {
281298 if ( 'notFound' in accessCheck && accessCheck . notFound ) {
282299 logger . warn ( `[${ requestId } ] Knowledge base not found: ${ knowledgeBaseId } ` )
283300 return NextResponse . json ( { error : 'Knowledge base not found' } , { status : 404 } )
284301 }
285302 logger . warn (
286- `[${ requestId } ] User ${ session . user . id } attempted to create document in unauthorized knowledge base ${ knowledgeBaseId } `
303+ `[${ requestId } ] User ${ userId } attempted to create document in unauthorized knowledge base ${ knowledgeBaseId } `
287304 )
288305 return NextResponse . json ( { error : 'Unauthorized' } , { status : 401 } )
289306 }
290307
291- const body = await req . json ( )
292-
293308 // Check if this is a bulk operation
294309 if ( body . bulk === true ) {
295310 // Handle bulk processing (replaces process-documents endpoint)
0 commit comments