11import { and , eq } from 'drizzle-orm'
22import { type NextRequest , NextResponse } from 'next/server'
33import { z } from 'zod'
4- import { getSession } from '@/lib/auth'
4+ import {
5+ authenticateCopilotRequestSessionOnly ,
6+ createInternalServerErrorResponse ,
7+ createNotFoundResponse ,
8+ createRequestTracker ,
9+ createUnauthorizedResponse ,
10+ } from '@/lib/copilot/auth'
511import { createLogger } from '@/lib/logs/console/logger'
612import { db } from '@/db'
713import { copilotChats } from '@/db/schema'
@@ -23,19 +29,19 @@ const UpdateMessagesSchema = z.object({
2329} )
2430
2531export async function POST ( req : NextRequest ) {
26- const requestId = crypto . randomUUID ( ) . slice ( 0 , 8 )
32+ const tracker = createRequestTracker ( )
2733
2834 try {
29- const session = await getSession ( )
30- if ( ! session ?. user ?. id ) {
31- return NextResponse . json ( { error : 'Unauthorized' } , { status : 401 } )
35+ const { userId , isAuthenticated } = await authenticateCopilotRequestSessionOnly ( )
36+ if ( ! isAuthenticated || ! userId ) {
37+ return createUnauthorizedResponse ( )
3238 }
3339
3440 const body = await req . json ( )
3541 const { chatId, messages } = UpdateMessagesSchema . parse ( body )
3642
37- logger . info ( `[${ requestId } ] Updating chat messages` , {
38- userId : session . user . id ,
43+ logger . info ( `[${ tracker . requestId } ] Updating chat messages` , {
44+ userId,
3945 chatId,
4046 messageCount : messages . length ,
4147 } )
@@ -44,11 +50,11 @@ export async function POST(req: NextRequest) {
4450 const [ chat ] = await db
4551 . select ( )
4652 . from ( copilotChats )
47- . where ( and ( eq ( copilotChats . id , chatId ) , eq ( copilotChats . userId , session . user . id ) ) )
53+ . where ( and ( eq ( copilotChats . id , chatId ) , eq ( copilotChats . userId , userId ) ) )
4854 . limit ( 1 )
4955
5056 if ( ! chat ) {
51- return NextResponse . json ( { error : 'Chat not found or unauthorized' } , { status : 404 } )
57+ return createNotFoundResponse ( 'Chat not found or unauthorized' )
5258 }
5359
5460 // Update chat with new messages
@@ -60,7 +66,7 @@ export async function POST(req: NextRequest) {
6066 } )
6167 . where ( eq ( copilotChats . id , chatId ) )
6268
63- logger . info ( `[${ requestId } ] Successfully updated chat messages` , {
69+ logger . info ( `[${ tracker . requestId } ] Successfully updated chat messages` , {
6470 chatId,
6571 newMessageCount : messages . length ,
6672 } )
@@ -70,7 +76,7 @@ export async function POST(req: NextRequest) {
7076 messageCount : messages . length ,
7177 } )
7278 } catch ( error ) {
73- logger . error ( `[${ requestId } ] Error updating chat messages:` , error )
74- return NextResponse . json ( { error : 'Failed to update chat messages' } , { status : 500 } )
79+ logger . error ( `[${ tracker . requestId } ] Error updating chat messages:` , error )
80+ return createInternalServerErrorResponse ( 'Failed to update chat messages' )
7581 }
7682}
0 commit comments