Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 28 additions & 23 deletions app/auth/callback/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { useEffect, useState, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { API_BASE_URL, getCookie, setTokens } from '../../utils/api';
import { API_BASE_URL, setTokens } from '../../utils/api';

function AuthCallbackContent() {
const router = useRouter();
Expand Down Expand Up @@ -55,35 +55,40 @@ function AuthCallbackContent() {
}),
});

console.log('=== Backend Response Debug ===');
console.log('Response status:', response.status);
console.log('Response ok:', response.ok);
console.log('Response headers:', Object.fromEntries(response.headers.entries()));

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();
console.log('Response data:', data);

if (data.success) {
// 백엔드에서 쿠키로 토큰을 설정했는지 확인
const accessToken = getCookie('access_social');
const refreshToken = getCookie('refresh_social');

console.log('=== Cookie Check After API Call ===');
console.log('Access Token from cookie:', accessToken ? 'Found' : 'Not found');
console.log('Refresh Token from cookie:', refreshToken ? 'Found' : 'Not found');

if (accessToken && refreshToken) {
console.log('✅ JWT tokens found in cookies - authentication successful');
setTokens(accessToken, refreshToken);
setStatus('success');
setMessage('로그인 성공! 홈으로 이동합니다.');
notifyAuthStateChange();
setTimeout(() => {
router.push('/home');
}, 1500);
} else {
console.log('❌ No JWT tokens in cookies after API call');
setStatus('error');
setMessage('인증 토큰을 받지 못했습니다. 다시 시도해주세요.');
}
console.log('✅ Backend API call successful - authentication successful');
console.log('Response data:', data);

// 로컬스토리지 저장 전 확인
console.log('=== LocalStorage Save Debug ===');
console.log('Before saving - localStorage:', localStorage.getItem('isAuthenticated'));

localStorage.setItem('isAuthenticated', 'true');
localStorage.setItem('authTimestamp', Date.now().toString());

// 로컬스토리지 저장 후 확인
console.log('After saving - isAuthenticated:', localStorage.getItem('isAuthenticated'));
console.log('After saving - authTimestamp:', localStorage.getItem('authTimestamp'));
console.log('All localStorage keys:', Object.keys(localStorage));

setStatus('success');
setMessage('로그인 성공! 홈으로 이동합니다.');
notifyAuthStateChange();
setTimeout(() => {
router.push('/home');
}, 1500);
} else {
throw new Error(data.message || '로그인 처리 중 오류가 발생했습니다.');
}
Expand Down
2 changes: 2 additions & 0 deletions app/components/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ export default function ProtectedRoute({ children, fallback }: ProtectedRoutePro
const router = useRouter();

useEffect(() => {
console.log('ProtectedRoute - Auth state:', { isLoggedIn, loading });
if (!loading && !isLoggedIn) {
console.log('ProtectedRoute - Redirecting to / due to not logged in');
router.push('/');
}
}, [isLoggedIn, loading, router]);
Expand Down
60 changes: 53 additions & 7 deletions app/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,48 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const [loading, setLoading] = useState(true);

const checkAuth = () => {
// JWT 토큰만 확인 (세션 기반 인증 제거)
const token = getAccessToken();
const newLoginState = !!token;
setIsLoggedIn(newLoginState);
setLoading(false);
console.log('=== AuthContext checkAuth ===');
console.log('Document available:', typeof document !== 'undefined');

console.log('Auth check:', { token: !!token, isLoggedIn: newLoginState });
// 백엔드 API를 호출해서 인증 상태 확인
const verifyAuth = async () => {
try {
console.log('Checking auth with backend...');
console.log('API_BASE_URL:', process.env.NEXT_PUBLIC_API_BASE_URL);
console.log('Full URL:', `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/auth/check`);

const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/auth/check`, {
method: 'GET',
credentials: 'include', // HttpOnly 쿠키 포함
});

if (response.ok) {
// 백엔드에서 인증 성공
localStorage.setItem('isAuthenticated', 'true');
localStorage.setItem('authTimestamp', Date.now().toString());
console.log('✅ Backend auth successful - setting localStorage');
} else {
// 백엔드에서 인증 실패
localStorage.removeItem('isAuthenticated');
localStorage.removeItem('authTimestamp');
console.log('❌ Backend auth failed - clearing localStorage');
}

const newLoginState = response.ok;
console.log('Setting isLoggedIn to:', newLoginState);

setIsLoggedIn(newLoginState);
setLoading(false);
} catch (error) {
console.error('Auth verification failed:', error);
localStorage.removeItem('isAuthenticated');
localStorage.removeItem('authTimestamp');
setIsLoggedIn(false);
setLoading(false);
}
};

verifyAuth();
};

const logout = () => {
Expand All @@ -51,6 +86,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
// localStorage 변경 감지
useEffect(() => {
const handleStorageChange = () => {
console.log('=== Storage change detected ===');
checkAuth();
};

Expand All @@ -59,12 +95,22 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {

// 현재 탭에서의 변경 감지를 위한 커스텀 이벤트
window.addEventListener('authStateChanged', handleStorageChange);

// 주기적으로 인증 상태 확인 (개발용)
const interval = setInterval(() => {
const currentAuth = isAuthenticated();
if (currentAuth !== isLoggedIn) {
console.log('Auth state changed from', isLoggedIn, 'to', currentAuth);
checkAuth();
}
}, 1000); // 1초마다 확인

return () => {
window.removeEventListener('storage', handleStorageChange);
window.removeEventListener('authStateChanged', handleStorageChange);
clearInterval(interval);
};
}, []);
}, [isLoggedIn]);

const value: AuthContextType = {
isLoggedIn,
Expand Down
Loading