/** * 인증 가드 - 모든 보호된 페이지에서 사용 * 로그인하지 않은 사용자를 자동으로 로그인 페이지로 리다이렉트 */ (function() { 'use strict'; // 인증이 필요하지 않은 페이지들 const PUBLIC_PAGES = [ 'login.html', 'setup.html' ]; // 현재 페이지가 공개 페이지인지 확인 function isPublicPage() { const currentPath = window.location.pathname; return PUBLIC_PAGES.some(page => currentPath.includes(page)); } // 로그인 페이지로 리다이렉트 function redirectToLogin() { const currentUrl = encodeURIComponent(window.location.href); console.log('🔐 인증되지 않은 접근. 로그인 페이지로 이동합니다.'); window.location.href = `login.html?redirect=${currentUrl}`; } // 인증 체크 함수 async function checkAuthentication() { // 공개 페이지는 체크하지 않음 if (isPublicPage()) { return; } const token = localStorage.getItem('access_token'); // 토큰이 없으면 즉시 리다이렉트 if (!token) { redirectToLogin(); return; } try { // 토큰 유효성 검사 const response = await fetch('/api/auth/me', { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' } }); if (!response.ok) { console.log('🔐 토큰이 유효하지 않습니다. 상태:', response.status); localStorage.removeItem('access_token'); redirectToLogin(); return; } // 인증 성공 const user = await response.json(); console.log('✅ 인증 성공:', user.email); // 전역 사용자 정보 설정 window.currentUser = user; // 헤더 사용자 메뉴 업데이트 if (typeof window.updateUserMenu === 'function') { window.updateUserMenu(user); } } catch (error) { console.error('🔐 인증 확인 중 오류:', error); localStorage.removeItem('access_token'); redirectToLogin(); } } // DOM 로드 완료 전에 인증 체크 실행 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', checkAuthentication); } else { checkAuthentication(); } // 전역 함수로 노출 window.authGuard = { checkAuthentication, redirectToLogin, isPublicPage }; })();