로그인 되어있을 시 /main 으로 이동

This commit is contained in:
dohyeons
2025-10-24 10:09:19 +09:00
parent bc8587f688
commit 03039ab743
3 changed files with 76 additions and 8 deletions

View File

@@ -63,13 +63,19 @@ const TokenManager = {
setToken: (token: string): void => {
if (typeof window !== "undefined") {
// localStorage에 저장
localStorage.setItem("authToken", token);
// 쿠키에도 저장 (미들웨어에서 사용)
document.cookie = `authToken=${token}; path=/; max-age=86400; SameSite=Lax`;
}
},
removeToken: (): void => {
if (typeof window !== "undefined") {
// localStorage에서 제거
localStorage.removeItem("authToken");
// 쿠키에서도 제거
document.cookie = "authToken=; path=/; max-age=0; SameSite=Lax";
}
},

View File

@@ -61,11 +61,15 @@ export const useLogin = () => {
* API 호출 공통 함수
*/
const apiCall = useCallback(async (endpoint: string, options: RequestInit = {}): Promise<LoginResponse> => {
// 로컬 스토리지에서 토큰 가져오기
const token = localStorage.getItem("authToken");
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
credentials: "include",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
...(token && { Authorization: `Bearer ${token}` }),
...options.headers,
},
...options,
@@ -90,16 +94,19 @@ export const useLogin = () => {
// 토큰이 있으면 API 호출로 유효성 확인
const result = await apiCall(AUTH_CONFIG.ENDPOINTS.STATUS);
if (result.success && result.data?.isLoggedIn) {
// 백엔드가 isAuthenticated 필드를 반환함
if (result.success && result.data?.isAuthenticated) {
// 이미 로그인된 경우 메인으로 리다이렉트
router.push(AUTH_CONFIG.ROUTES.MAIN);
} else {
// 토큰이 유효하지 않으면 제거
localStorage.removeItem("authToken");
document.cookie = "authToken=; path=/; max-age=0; SameSite=Lax";
}
} catch (error) {
// 에러가 발생하면 토큰 제거
localStorage.removeItem("authToken");
document.cookie = "authToken=; path=/; max-age=0; SameSite=Lax";
console.debug("기존 인증 체크 중 오류 (정상):", error);
}
}, [apiCall, router]);
@@ -128,9 +135,12 @@ export const useLogin = () => {
});
if (result.success && result.data?.token) {
// JWT 토큰 저장
// JWT 토큰 저장 (localStorage와 쿠키 모두에 저장)
localStorage.setItem("authToken", result.data.token);
// 쿠키에도 저장 (미들웨어에서 사용)
document.cookie = `authToken=${result.data.token}; path=/; max-age=86400; SameSite=Lax`;
// 로그인 성공
router.push(AUTH_CONFIG.ROUTES.MAIN);
} else {
@@ -148,13 +158,10 @@ export const useLogin = () => {
[formData, validateForm, apiCall, router],
);
// 컴포넌트 마운트 시 기존 인증 상태 확인 (한 번만 실행)
// 컴포넌트 마운트 시 기존 인증 상태 확인
useEffect(() => {
// 로그인 페이지에서만 실행
if (window.location.pathname === "/login") {
checkExistingAuth();
}
}, []); // 의존성 배열을 비워서 한 번만 실행
checkExistingAuth();
}, [checkExistingAuth]);
return {
// 상태