Files
sam-react-prod/src/app/api/auth/check/route.ts

114 lines
3.7 KiB
TypeScript
Raw Normal View History

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { refreshAccessToken } from '@/lib/api/refresh-token';
/**
* 🔵 Next.js API - (PHP X)
*
* :
* - 최적화: 매번 PHP
* - 감소: 간단한 Next.js에서
* - 경험: 즉시
*
* 📍 :
* - LoginPage.tsx: 이미
* - SignupPage.tsx: 이미
* -
*
* 🔄 :
* 1. HttpOnly access_token, refresh_token
* 2. access_token { authenticated: true }
* 3. refresh_token만 PHP /api/v1/refresh
* 4. { authenticated: false }
*
* :
* - API는 PHP
* - Next.js API입니다
* - PHP
*/
export async function GET(request: NextRequest) {
try {
// Get tokens from HttpOnly cookies
const accessToken = request.cookies.get('access_token')?.value;
const refreshToken = request.cookies.get('refresh_token')?.value;
// No tokens at all - not authenticated
if (!accessToken && !refreshToken) {
return NextResponse.json(
{ error: 'Not authenticated' },
{ status: 401 }
);
}
// Has access token - authenticated
if (accessToken) {
return NextResponse.json(
{ authenticated: true },
{ status: 200 }
);
}
// Only has refresh token - try to refresh
if (refreshToken && !accessToken) {
console.log('🔄 [auth/check] Access token missing, attempting refresh...');
// 공유 캐시를 사용하는 refreshAccessToken 함수 사용
const refreshResult = await refreshAccessToken(refreshToken, 'auth/check');
if (refreshResult.success && refreshResult.accessToken) {
console.log('✅ [auth/check] Token refreshed successfully');
// Set new tokens with Safari-compatible configuration
const isProduction = process.env.NODE_ENV === 'production';
const accessTokenCookie = [
`access_token=${refreshResult.accessToken}`,
'HttpOnly',
...(isProduction ? ['Secure'] : []),
'SameSite=Lax',
'Path=/',
`Max-Age=${refreshResult.expiresIn || 7200}`,
].join('; ');
const refreshTokenCookie = [
`refresh_token=${refreshResult.refreshToken}`,
'HttpOnly',
...(isProduction ? ['Secure'] : []),
'SameSite=Lax',
'Path=/',
'Max-Age=604800',
].join('; ');
const response = NextResponse.json(
{ authenticated: true, refreshed: true },
{ status: 200 }
);
response.headers.append('Set-Cookie', accessTokenCookie);
response.headers.append('Set-Cookie', refreshTokenCookie);
return response;
}
// Refresh failed - not authenticated
console.log('⚠️ [auth/check] Refresh failed, returning 401');
return NextResponse.json(
{ error: 'Token refresh failed' },
{ status: 401 }
);
}
// Fallback - not authenticated
return NextResponse.json(
{ error: 'Not authenticated' },
{ status: 401 }
);
} catch (error) {
console.error('Auth check error:', error);
return NextResponse.json(
{ error: 'Internal server error', authenticated: false },
{ status: 500 }
);
}
}