Files
tk-factory-services/system1-factory/web/js/auth-check.js
Hyungi Ahn 6495b8af32 feat: SSO 쿠키 인증 통합 + 서브도메인 라우팅 아키텍처
- Path-based 라우팅을 서브도메인 기반으로 전환
  (tkfb/tkreport/tkqc.technicalkorea.net)
- 3개 시스템 프론트엔드에 SSO 쿠키 인증 통합
  (domain=.technicalkorea.net, localStorage 폴백)
- Gateway: 포털+로그인+System1 프록시, 쿠키 SSO 설정
- System 1: 토큰키 통일, nginx.conf 생성, 신고페이지 리다이렉트
- System 2: api-base.js/app-init.js 생성, getSSOToken() 통합
- System 3: TokenManager 쿠키 지원, 중앙 로그인 리다이렉트
- docker-compose.yml에 cloudflared 서비스 추가
- DEPLOY-GUIDE.md 배포 가이드 작성

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 18:41:44 +09:00

160 lines
4.9 KiB
JavaScript

// /js/auth-check.js
// auth.js의 함수들을 직접 구현 (모듈 의존성 제거)
function isLoggedIn() {
var token = window.getSSOToken ? window.getSSOToken() : localStorage.getItem('sso_token');
return token && token !== 'undefined' && token !== 'null';
}
function getUser() {
return window.getSSOUser ? window.getSSOUser() : (function() {
var u = localStorage.getItem('sso_user');
return u ? JSON.parse(u) : null;
})();
}
function clearAuthData() {
if (window.clearSSOAuth) { window.clearSSOAuth(); return; }
localStorage.removeItem('sso_token');
localStorage.removeItem('sso_user');
localStorage.removeItem('userPageAccess');
}
/**
* 현재 페이지의 page_key를 URL 경로로부터 추출
* 예: /pages/work/tbm.html -> work.tbm
* /pages/admin/accounts.html -> admin.accounts
* /pages/dashboard.html -> dashboard
*/
function getCurrentPageKey() {
const path = window.location.pathname;
// /pages/로 시작하는지 확인
if (!path.startsWith('/pages/')) {
return null;
}
// /pages/ 이후 경로 추출
const pagePath = path.substring(7); // '/pages/' 제거
// .html 제거
const withoutExt = pagePath.replace('.html', '');
// 슬래시를 점으로 변환
const pageKey = withoutExt.replace(/\//g, '.');
return pageKey;
}
/**
* 사용자의 페이지 접근 권한 확인 (캐시 활용)
*/
async function checkPageAccess(pageKey) {
const currentUser = getUser();
// Admin은 모든 페이지 접근 가능
if (currentUser.role === 'Admin' || currentUser.role === 'System Admin') {
return true;
}
// 프로필 페이지는 모든 사용자 접근 가능
if (pageKey && pageKey.startsWith('profile.')) {
return true;
}
// 대시보드는 모든 사용자 접근 가능
if (pageKey === 'dashboard') {
return true;
}
try {
// 캐시된 권한 확인
const cached = localStorage.getItem('userPageAccess');
let accessiblePages = null;
if (cached) {
const cacheData = JSON.parse(cached);
// 캐시가 5분 이내인 경우 사용
if (Date.now() - cacheData.timestamp < 5 * 60 * 1000) {
accessiblePages = cacheData.pages;
}
}
// 캐시가 없으면 API 호출
if (!accessiblePages) {
const response = await fetch(`${window.API_BASE_URL}/users/${currentUser.user_id}/page-access`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + (window.getSSOToken ? window.getSSOToken() : localStorage.getItem('sso_token'))
}
});
if (!response.ok) {
console.error('페이지 권한 조회 실패:', response.status);
return false;
}
const data = await response.json();
accessiblePages = data.data.pageAccess || [];
// 캐시 저장
localStorage.setItem('userPageAccess', JSON.stringify({
pages: accessiblePages,
timestamp: Date.now()
}));
}
// 해당 페이지에 대한 접근 권한 확인
const pageAccess = accessiblePages.find(p => p.page_key === pageKey);
return pageAccess && pageAccess.can_access === 1;
} catch (error) {
console.error('페이지 권한 체크 오류:', error);
return false;
}
}
// 즉시 실행 함수로 스코프를 보호하고 로직을 실행
(async function() {
if (!isLoggedIn()) {
console.log('🚨 인증되지 않은 사용자. 로그인 페이지로 이동합니다.');
clearAuthData(); // 만약을 위해 한번 더 정리
window.location.href = window.getLoginUrl ? window.getLoginUrl() : '/login';
return; // 이후 코드 실행 방지
}
const currentUser = getUser();
// 사용자 정보가 유효한지 확인 (토큰은 있지만 유저 정보가 깨졌을 경우)
if (!currentUser || !currentUser.username) {
console.error('🚨 사용자 정보가 유효하지 않습니다. 강제 로그아웃 처리합니다.');
clearAuthData();
window.location.href = window.getLoginUrl ? window.getLoginUrl() : '/login';
return;
}
const userRole = currentUser.role || currentUser.access_level || '사용자';
console.log(`${currentUser.username}(${userRole})님 인증 성공.`);
// 페이지 접근 권한 체크 (Admin은 건너뛰기)
if (currentUser.role !== 'Admin' && currentUser.role !== 'System Admin') {
const pageKey = getCurrentPageKey();
if (pageKey) {
console.log(`🔍 페이지 권한 체크: ${pageKey}`);
const hasAccess = await checkPageAccess(pageKey);
if (!hasAccess) {
console.error(`🚫 페이지 접근 권한이 없습니다: ${pageKey}`);
alert('이 페이지에 접근할 권한이 없습니다.');
window.location.href = '/pages/dashboard.html';
return;
}
console.log(`✅ 페이지 접근 권한 확인됨: ${pageKey}`);
}
}
// 역할 기반 메뉴 제어 로직은 각 컴포넌트 로더(load-navbar.js 등)로 이전함.
// 전역 변수 할당(window.currentUser) 제거.
})();