system1-factory의 자체 로그인 폼을 제거하고 게이트웨이 SSO 로그인 페이지(/login)로 리다이렉트하도록 변경. 기존에는 /api/auth/login(system1-api)으로 직접 인증하여 SSO 사용자가 401 오류를 받았음. - index.html: 로그인 폼 제거, SSO 토큰 없으면 /login으로 리다이렉트 - api-base.js: getLoginUrl() 개발환경에서도 SSO 로그인 경로 반환 - api-helper.js: authFetch 401/토큰없음 시 SSO 로그인으로 리다이렉트 - app-init.js: 로그아웃 및 인증실패 시 SSO 로그인으로 리다이렉트 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
142 lines
4.1 KiB
JavaScript
142 lines
4.1 KiB
JavaScript
// /public/js/api-helper.js
|
|
// ES6 모듈 의존성 제거 - 브라우저 호환성 개선
|
|
|
|
// API 설정 (window 객체에서 가져오기)
|
|
const API_BASE_URL = window.API_BASE_URL || 'http://localhost:30005/api';
|
|
|
|
// 인증 관련 함수들 (직접 구현)
|
|
function getToken() {
|
|
// SSO 토큰 우선, 기존 token 폴백
|
|
if (window.getSSOToken) return window.getSSOToken();
|
|
const token = localStorage.getItem('sso_token') || localStorage.getItem('token');
|
|
return token && token !== 'undefined' && token !== 'null' ? token : null;
|
|
}
|
|
|
|
function clearAuthData() {
|
|
if (window.clearSSOAuth) { window.clearSSOAuth(); return; }
|
|
localStorage.removeItem('sso_token');
|
|
localStorage.removeItem('sso_user');
|
|
localStorage.removeItem('token');
|
|
localStorage.removeItem('user');
|
|
}
|
|
|
|
/**
|
|
* 로그인 API를 호출합니다. (인증이 필요 없는 public 요청)
|
|
* @param {string} username - 사용자 아이디
|
|
* @param {string} password - 사용자 비밀번호
|
|
* @returns {Promise<object>} - API 응답 결과
|
|
*/
|
|
async function login(username, password) {
|
|
const response = await fetch(`${API_BASE_URL}/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username, password }),
|
|
});
|
|
|
|
const result = await response.json();
|
|
if (!response.ok) {
|
|
// API 에러 응답을 그대로 에러 객체로 던져서 호출부에서 처리하도록 함
|
|
throw new Error(result.error || '로그인에 실패했습니다.');
|
|
}
|
|
return result;
|
|
}
|
|
|
|
|
|
/**
|
|
* 인증이 필요한 API 요청을 위한 fetch 래퍼 함수
|
|
* @param {string} endpoint - /로 시작하는 API 엔드포인트
|
|
* @param {object} options - fetch 함수에 전달할 옵션
|
|
* @returns {Promise<Response>} - fetch 응답 객체
|
|
*/
|
|
async function authFetch(endpoint, options = {}) {
|
|
const token = getToken();
|
|
|
|
if (!token) {
|
|
console.error('토큰이 없습니다. 로그인이 필요합니다.');
|
|
clearAuthData(); // 인증 정보 정리
|
|
window.location.href = window.getLoginUrl ? window.getLoginUrl() : '/login?redirect=' + encodeURIComponent(window.location.href);
|
|
// 에러를 던져서 후속 실행을 중단
|
|
throw new Error('인증 토큰이 없습니다.');
|
|
}
|
|
|
|
const defaultHeaders = {
|
|
'Authorization': `Bearer ${token}`,
|
|
'Content-Type': 'application/json'
|
|
};
|
|
|
|
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
|
...options,
|
|
headers: {
|
|
...defaultHeaders,
|
|
...options.headers
|
|
}
|
|
});
|
|
|
|
// 401 Unauthorized 에러 발생 시, 토큰이 유효하지 않다는 의미
|
|
if (response.status === 401) {
|
|
console.error('인증 실패. 토큰이 만료되었거나 유효하지 않습니다.');
|
|
clearAuthData(); // 만료된 인증 정보 정리
|
|
window.location.href = window.getLoginUrl ? window.getLoginUrl() : '/login?redirect=' + encodeURIComponent(window.location.href);
|
|
throw new Error('인증에 실패했습니다.');
|
|
}
|
|
|
|
return response;
|
|
}
|
|
|
|
// 공통 API 요청 함수들
|
|
|
|
/**
|
|
* GET 요청 헬퍼
|
|
* @param {string} endpoint - API 엔드포인트
|
|
*/
|
|
async function apiGet(endpoint) {
|
|
const response = await authFetch(endpoint);
|
|
return response.json();
|
|
}
|
|
|
|
/**
|
|
* POST 요청 헬퍼
|
|
* @param {string} endpoint - API 엔드포인트
|
|
* @param {object} data - 전송할 데이터
|
|
*/
|
|
async function apiPost(endpoint, data) {
|
|
const response = await authFetch(endpoint, {
|
|
method: 'POST',
|
|
body: JSON.stringify(data)
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
/**
|
|
* PUT 요청 헬퍼
|
|
* @param {string} endpoint - API 엔드포인트
|
|
* @param {object} data - 전송할 데이터
|
|
*/
|
|
async function apiPut(endpoint, data) {
|
|
const response = await authFetch(endpoint, {
|
|
method: 'PUT',
|
|
body: JSON.stringify(data)
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
/**
|
|
* DELETE 요청 헬퍼
|
|
* @param {string} endpoint - API 엔드포인트
|
|
*/
|
|
async function apiDelete(endpoint) {
|
|
const response = await authFetch(endpoint, {
|
|
method: 'DELETE'
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
// 전역 함수로 설정
|
|
window.login = login;
|
|
window.apiGet = apiGet;
|
|
window.apiPost = apiPost;
|
|
window.apiPut = apiPut;
|
|
window.apiDelete = apiDelete;
|
|
window.getToken = getToken;
|
|
window.clearAuthData = clearAuthData;
|