refactor(auth): 프론트엔드/백엔드 로그인 로직 개선
- 프론트엔드: login.js, api-helper.js, auth.js 모듈화 및 책임 분리 - 백엔드: authController가 역할 기반 redirectUrl을 제공하도록 수정 - 로그인 프로세스의 안정성 및 유지보수성 향상
This commit is contained in:
@@ -1,18 +1,45 @@
|
||||
// /public/js/api-helper.js
|
||||
|
||||
// API 기본 URL 설정
|
||||
const API_BASE = location.hostname.includes('localhost')
|
||||
? 'http://localhost:3005/api'
|
||||
: 'https://api.hyungi.net/api';
|
||||
import { API_BASE_URL } from './api-config.js';
|
||||
import { getToken, clearAuthData } from './auth.js';
|
||||
|
||||
// 인증된 fetch 함수
|
||||
async function authFetch(url, options = {}) {
|
||||
const token = localStorage.getItem('token');
|
||||
/**
|
||||
* 로그인 API를 호출합니다. (인증이 필요 없는 public 요청)
|
||||
* @param {string} username - 사용자 아이디
|
||||
* @param {string} password - 사용자 비밀번호
|
||||
* @returns {Promise<object>} - API 응답 결과
|
||||
*/
|
||||
export 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('토큰이 없습니다. 로그인이 필요합니다.');
|
||||
window.location.href = '/index.html';
|
||||
return;
|
||||
clearAuthData(); // 인증 정보 정리
|
||||
window.location.href = '/index.html'; // 로그인 페이지로 리디렉션
|
||||
// 에러를 던져서 후속 실행을 중단
|
||||
throw new Error('인증 토큰이 없습니다.');
|
||||
}
|
||||
|
||||
const defaultHeaders = {
|
||||
@@ -20,7 +47,7 @@ async function authFetch(url, options = {}) {
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
|
||||
const response = await fetch(url, {
|
||||
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
||||
...options,
|
||||
headers: {
|
||||
...defaultHeaders,
|
||||
@@ -28,59 +55,61 @@ async function authFetch(url, options = {}) {
|
||||
}
|
||||
});
|
||||
|
||||
// 401 에러 시 로그인 페이지로
|
||||
// 401 Unauthorized 에러 발생 시, 토큰이 유효하지 않다는 의미
|
||||
if (response.status === 401) {
|
||||
console.error('인증 실패. 다시 로그인해주세요.');
|
||||
localStorage.removeItem('token');
|
||||
console.error('인증 실패. 토큰이 만료되었거나 유효하지 않습니다.');
|
||||
clearAuthData(); // 만료된 인증 정보 정리
|
||||
window.location.href = '/index.html';
|
||||
return;
|
||||
throw new Error('인증에 실패했습니다.');
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// GET 요청 헬퍼
|
||||
async function apiGet(endpoint) {
|
||||
const response = await authFetch(`${API_BASE}${endpoint}`);
|
||||
if (!response) return null;
|
||||
// 공통 API 요청 함수들
|
||||
|
||||
/**
|
||||
* GET 요청 헬퍼
|
||||
* @param {string} endpoint - API 엔드포인트
|
||||
*/
|
||||
export async function apiGet(endpoint) {
|
||||
const response = await authFetch(endpoint);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// POST 요청 헬퍼
|
||||
async function apiPost(endpoint, data) {
|
||||
const response = await authFetch(`${API_BASE}${endpoint}`, {
|
||||
/**
|
||||
* POST 요청 헬퍼
|
||||
* @param {string} endpoint - API 엔드포인트
|
||||
* @param {object} data - 전송할 데이터
|
||||
*/
|
||||
export async function apiPost(endpoint, data) {
|
||||
const response = await authFetch(endpoint, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
if (!response) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// PUT 요청 헬퍼
|
||||
async function apiPut(endpoint, data) {
|
||||
const response = await authFetch(`${API_BASE}${endpoint}`, {
|
||||
/**
|
||||
* PUT 요청 헬퍼
|
||||
* @param {string} endpoint - API 엔드포인트
|
||||
* @param {object} data - 전송할 데이터
|
||||
*/
|
||||
export async function apiPut(endpoint, data) {
|
||||
const response = await authFetch(endpoint, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
if (!response) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// DELETE 요청 헬퍼
|
||||
async function apiDelete(endpoint) {
|
||||
const response = await authFetch(`${API_BASE}${endpoint}`, {
|
||||
/**
|
||||
* DELETE 요청 헬퍼
|
||||
* @param {string} endpoint - API 엔드포인트
|
||||
*/
|
||||
export async function apiDelete(endpoint) {
|
||||
const response = await authFetch(endpoint, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (!response) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 내보내기 (다른 파일에서 사용 가능)
|
||||
window.API = {
|
||||
get: apiGet,
|
||||
post: apiPost,
|
||||
put: apiPut,
|
||||
delete: apiDelete,
|
||||
fetch: authFetch,
|
||||
BASE: API_BASE
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user