1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { SessionRepository } from '@/lib/users/session/repository'
import { authOptions } from '../../auth/[...nextauth]/route'
function ensureNumber(value: string | number): number {
return typeof value === 'string' ? parseInt(value, 10) : value
}
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions)
const trackingData = await request.json()
// IP 주소 추출
const getClientIP = (req: NextRequest): string => {
const forwarded = req.headers.get('x-forwarded-for')
const realIP = req.headers.get('x-real-ip')
const cfConnectingIP = req.headers.get('cf-connecting-ip')
if (cfConnectingIP) return cfConnectingIP
if (forwarded) return forwarded.split(',')[0].trim()
if (realIP) return realIP
return '127.0.0.1'
}
// 활성 세션 조회 및 업데이트
let sessionId = null
if (session?.user?.id && session?.user?.dbSessionId) {
sessionId = session.user.dbSessionId
// 세션 활동 시간 업데이트 (백그라운드)
SessionRepository.updateSessionActivity(sessionId).catch(error => {
console.error('Failed to update session activity:', error)
})
}
// 페이지 방문 기록
await SessionRepository.recordPageVisit({
userId: session?.user?.id ? ensureNumber(session.user.id) : undefined, // ✅ 타입 변환
sessionId,
route: trackingData.route,
pageTitle: trackingData.pageTitle || undefined,
referrer: trackingData.referrer || undefined,
ipAddress: getClientIP(request),
userAgent: trackingData.userAgent,
queryParams: new URL(request.url).search || undefined,
deviceType: trackingData.deviceType || undefined,
browserName: trackingData.browserName || undefined,
osName: trackingData.osName || undefined,
})
return NextResponse.json({ success: true })
} catch (error) {
console.error('Page visit tracking API error:', error)
// 추적 실패가 클라이언트에 영향을 주지 않도록 성공 응답
return NextResponse.json({ success: false }, { status: 200 })
}
}
|