← back to Letsbegin
app/api/auth/session/route.ts
51 lines
import { NextRequest, NextResponse } from 'next/server'
import { AUTH_CONFIG, isWhitelistedIP } from '@/lib/auth'
import { cookies } from 'next/headers'
export async function GET(request: NextRequest) {
try {
// Check if IP is whitelisted
const forwardedFor = request.headers.get('x-forwarded-for')
const ip = forwardedFor?.split(',')[0]?.trim() || ''
// Also check request URL hostname for localhost
const url = new URL(request.url)
const isLocalhost = url.hostname === 'localhost' || url.hostname === '127.0.0.1'
if (isWhitelistedIP(ip) || isLocalhost) {
return NextResponse.json({
authenticated: true,
username: 'admin',
bypassReason: 'whitelisted_ip'
})
}
// Check session cookie
const cookieStore = await cookies()
const sessionCookie = cookieStore.get(AUTH_CONFIG.sessionName)
if (!sessionCookie?.value) {
return NextResponse.json({ authenticated: false }, { status: 401 })
}
try {
const sessionData = JSON.parse(Buffer.from(sessionCookie.value, 'base64').toString())
if (sessionData.authenticated) {
return NextResponse.json({
authenticated: true,
username: sessionData.username,
loginTime: sessionData.loginTime
})
}
} catch {
// Invalid session format
}
return NextResponse.json({ authenticated: false }, { status: 401 })
} catch (error) {
console.error('Session check error:', error)
return NextResponse.json({ authenticated: false, error: 'Session check failed' }, { status: 500 })
}
}