diff --git a/apps/fo/.env.local b/apps/fo/.env.local index 78fb4ed09..d87605414 100644 --- a/apps/fo/.env.local +++ b/apps/fo/.env.local @@ -6,7 +6,7 @@ NEXT_PUBLIC_ACCESS_TOKEN = access-token NEXT_PUBLIC_REFRESH_TOKEN = refresh-token NEXT_PUBLIC_PROXY_HOST = http://localhost:3000 NEXT_PUBLIC_SUB_DOMAIN = http://localhost:13000 -#NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://localhost:3001/auth/login +#NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = http://localhost:3001/auth/login SERVER_API_URL = http://con.mind-one.co.kr:11083/operation-service/api/v1 # FO_SERVER_API_URL = http://con.mind-one.co.kr:11083/operation-service/api/v1 FO_SERVER_API_URL = http://localhost:3000/operation-service/api/v1 @@ -19,8 +19,10 @@ DC_URL = https://apigateway.apps.rsonesoft.com/dc-service SEWERAGE_API_URL = http://con.mind-one.co.kr:11083/sewerage-service # 개발 서버 API NEXT_PUBLIC_NGII_URL = https://map.ngii.go.kr NEXT_PUBLIC_NGII_PARAM = 04trYP9_xwLAfALjwZ-B8g&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={x}&tilerow={y} -# NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = / +# NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = http://dev.onasys.co.kr:3000/auth/login +# 로그인 이동 주소: 설정하지 않으면 /auth/login +# (.env.local은 운영 빌드에서도 .env.production보다 우선하므로 값을 켜지 않는다) +# NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = /auth/login NEXT_PUBLIC_COOKIE_COMAIN=.mind-one.co.kr REACT_EDITOR=atom \ No newline at end of file diff --git a/apps/fo/.env.mindone b/apps/fo/.env.mindone index 740770113..a5a173b20 100644 --- a/apps/fo/.env.mindone +++ b/apps/fo/.env.mindone @@ -6,7 +6,7 @@ NEXT_PUBLIC_ACCESS_TOKEN = access-token NEXT_PUBLIC_REFRESH_TOKEN = refresh-token NEXT_PUBLIC_PROXY_HOST = http://con.mind-one.co.kr:11300 NEXT_PUBLIC_SUB_DOMAIN = http://con.mind-one.co.kr:13000 -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login +NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = /auth/login SERVER_API_URL = http://con.mind-one.co.kr:11083/operation-service/api/v1 FO_SERVER_API_URL = http://con.mind-one.co.kr:11083/operation-service/api/v1 WR_SERVER_API_URL = http://con.mind-one.co.kr:11083/reuse-service/api/v1 @@ -17,5 +17,4 @@ DC_URL = https://apigateway.apps.rsonesoft.com/dc-service SEWERAGE_API_URL = http://con.mind-one.co.kr:11083/sewerage-service NEXT_PUBLIC_NGII_URL = https://map.ngii.go.kr NEXT_PUBLIC_NGII_PARAM = 04trYP9_xwLAfALjwZ-B8g&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={x}&tilerow={y} -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = / NEXT_PUBLIC_COOKIE_COMAIN=.mind-one.co.kr \ No newline at end of file diff --git a/apps/fo/.env.production b/apps/fo/.env.production index 30dc5098c..892548446 100644 --- a/apps/fo/.env.production +++ b/apps/fo/.env.production @@ -6,7 +6,7 @@ NEXT_PUBLIC_AUTH_USER_ID = token-id NEXT_PUBLIC_ACCESS_TOKEN = access-token NEXT_PUBLIC_REFRESH_TOKEN = refresh-token #NEXT_PUBLIC_PROXY_HOST = https://devlarva.hasuon.or.kr -#NEXT_PUBLIC_CM_LOGIN_PAGE_URL = https://devqueen.hasuon.or.kr/auth/login +#NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = https://devqueen.hasuon.or.kr/auth/login SERVER_API_URL = http://apigateway.iipbs-was.svc.cluster.local:8000/operation-service/api/v1 FO_SERVER_API_URL = http://apigateway.iipbs-was.svc.cluster.local:8000/operation-service/api/v1 WR_SERVER_API_URL = http://apigateway.iipbs-was.svc.cluster.local:8000/reuse-service/api/v1 @@ -18,8 +18,7 @@ DC_URL = http://apigateway.iipbs-was.svc.cluster.local:8000/dc-service SEWERAGE_API_URL = http://apigateway.iipbs-was.svc.cluster.local:8000/sewerage-service NEXT_PUBLIC_NGII_URL = http://172.29.143.87/poiact NEXT_PUBLIC_NGII_PARAM = BDE2BEF39DAFEC293AB6730150F222AC&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={y}&tilerow={x} -#NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login +#NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = http://dev.onasys.co.kr:3000/auth/login # 로그인 필요(토큰 없음·401·갱신 실패) 시 공통 포털 로그인으로 이동 -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = https://portal.hasuon.or.kr/auth/login NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = https://portal.hasuon.or.kr/auth/login NEXT_PUBLIC_COOKIE_DOMAIN=.hasuon.or.kr \ No newline at end of file diff --git a/apps/fo/app/(auth)/auth/layout.tsx b/apps/fo/app/(auth)/auth/layout.tsx index f2a01bd1b..1f5319b18 100644 --- a/apps/fo/app/(auth)/auth/layout.tsx +++ b/apps/fo/app/(auth)/auth/layout.tsx @@ -9,9 +9,6 @@ export default function AuthLayout({ }: { children: React.ReactNode; }) { - return ( - -
{children} - - ); + // , 는 루트 레이아웃(app/layout.tsx)에서 그린다 + return children; } diff --git a/apps/fo/app/components/api/index.ts b/apps/fo/app/components/api/index.ts index 5fab2ee12..8a2910145 100644 --- a/apps/fo/app/components/api/index.ts +++ b/apps/fo/app/components/api/index.ts @@ -1,11 +1,8 @@ -import { CLAIM_NAME, SITE_ID } from "@/src/shared/config/env"; +import { AUTH_LOGIN_REDIRECT_URL, CLAIM_NAME, SITE_ID } from "@/src/shared/config/env"; import { tokenManager } from "@/src/entities/auth/lib/token-manager"; import { getRemainingMs } from "@common/auth"; import { DEV_URL_FO, DEV_URL_WR, LOCAL_URL } from "./config/env"; -const LOGIN_PAGE_URL = - process.env.NEXT_PUBLIC_CM_LOGIN_PAGE_URL || "/auth/login"; - // client 화면인 경우, 토큰 만료여부 점검하여 로그인 페이지로 이동 const handleUnauthorizedResponse = () => { if (typeof window === "undefined") return; @@ -23,7 +20,7 @@ const handleUnauthorizedResponse = () => { window.location.pathname.startsWith("/auth/login/"); if (!isLoginPage) { - window.location.assign(LOGIN_PAGE_URL); + window.location.assign(AUTH_LOGIN_REDIRECT_URL); } }; diff --git a/apps/fo/app/page.tsx b/apps/fo/app/page.tsx index 351e87885..dc6ef4219 100644 --- a/apps/fo/app/page.tsx +++ b/apps/fo/app/page.tsx @@ -1,5 +1,4 @@ "use client"; -import { authService } from "@/src/entities/auth"; import { useEffect } from "react"; import { AUTH_USER_ID } from "@/src/shared/config"; import { getCookie } from "@/src/shared/lib/cookie"; @@ -14,17 +13,8 @@ export default function Home() { const hostname = window.location.hostname; if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "con.mind-one.co.kr") { - if (!checkToken) { - async function doLogin() { - try { - await authService.login({ userId: "CLEANWATER", password: "gktneh12!@" }); - window.location.href = "/pages/dashboard"; - } catch (err) { - console.error("로그인 실패", err); - } - } - doLogin(); - } else router.push("/pages/dashboard"); + if (!checkToken) router.push("/auth/login"); + else router.push("/pages/dashboard"); } else router.push("/pages/dashboard"); }, []); } \ No newline at end of file diff --git a/apps/fo/src/entities/auth/lib/auth-wrapper.tsx b/apps/fo/src/entities/auth/lib/auth-wrapper.tsx index 083b4c812..594ef4c22 100644 --- a/apps/fo/src/entities/auth/lib/auth-wrapper.tsx +++ b/apps/fo/src/entities/auth/lib/auth-wrapper.tsx @@ -1,7 +1,7 @@ "use client"; -import { useEffect } from "react"; -import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; +import { usePathname, useRouter } from "next/navigation"; import { isAxiosError } from "axios"; @@ -21,35 +21,20 @@ import { authService } from "../api/auth-service"; import { getToken, setupRefreshTimer } from "./token-manager"; -/** - * 로그인 주소가 다른 도메인(예: 공통 포털)인지 확인한다. - * @param url 로그인 이동 주소(상대경로 또는 절대경로) - * @returns 현재 사이트와 origin이 다르면 true - */ -function isExternalLoginUrl(url: string): boolean { - try { - return new URL(url, window.location.href).origin !== window.location.origin; - } catch { - return false; - } -} - const AuthWrapper = ({ children }: { children: React.ReactNode }) => { const router = useRouter(); + const pathname = usePathname(); const userInfo = useUserStore((state) => state.userInfo); const setUserInfo = useUserStore((state) => state.setUserInfo); + // 화면(children) 표시 여부. false인 동안에는 자식 화면의 API 호출이 시작되지 않는다 + const [canRender, setCanRender] = useState(false); - /** - * 로그인 화면으로 이동한다. - * 다른 도메인(포털)이면 브라우저 이동, 같은 앱이면 Next 라우터로 이동한다. - */ - function goToLogin() { - if (isExternalLoginUrl(AUTH_LOGIN_REDIRECT_URL)) { - window.location.replace(AUTH_LOGIN_REDIRECT_URL); - return; + // 로그인 화면이거나 토큰이 있을 때만 화면을 연다. 로그인 화면으로 이동하면 다시 확인한다 + useEffect(() => { + if (isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL) || getToken(AUTH_USER_ID)) { + setCanRender(true); } - router.replace(AUTH_LOGIN_REDIRECT_URL); - } + }, [pathname]); useEffect(() => { // 페이지 새로고침 시 silentRefresh 타이머 복구 @@ -69,7 +54,7 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { async function authCheck() { const userId = getToken(AUTH_USER_ID); if (!userId) { - goToLogin(); + router.replace(AUTH_LOGIN_REDIRECT_URL); return; } @@ -88,7 +73,7 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { console.error(error); setUserInfo(null); if (!isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) { - goToLogin(); + router.replace(AUTH_LOGIN_REDIRECT_URL); } }); }, []); @@ -98,7 +83,7 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { function handleAuthLogout() { setUserInfo(null); if (!isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) { - goToLogin(); + router.replace(AUTH_LOGIN_REDIRECT_URL); } } @@ -107,7 +92,7 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { window.removeEventListener("auth:logout", handleAuthLogout); }, []); - return <>{children}>; + return <>{canRender ? children : null}>; }; export { AuthWrapper }; diff --git a/apps/fo/src/shared/config/env.ts b/apps/fo/src/shared/config/env.ts index 8c4153b70..ca4bc4926 100644 --- a/apps/fo/src/shared/config/env.ts +++ b/apps/fo/src/shared/config/env.ts @@ -16,18 +16,12 @@ export const SERVER_API_URL = export const SERVER_API_CS_TUS_URL = process.env.NEXT_PUBLIC_CS_TUS_UPLOAD || "/attach-service/api/v1/tus/upload"; -// 로그인 이동 주소: @common/network getAuthLoginRedirectUrl()과 같은 순서로 찾는다 +// 로그인 이동 주소: 상대경로 또는 다른 도메인(공통 포털)의 절대경로 export const AUTH_LOGIN_REDIRECT_URL = - process.env.NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL || - process.env.NEXT_PUBLIC_CM_LOGIN_PAGE_URL || - "/auth/login"; + process.env.NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL || "/auth/login"; export const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization"; -export const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token"; -export const REFRESH_TOKEN =process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token"; +export const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token"; +export const REFRESH_TOKEN = process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token"; export const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id"; export const SERVER_SEWERAGE_API_URL = process.env.SEWERAGE_API_URL; export const COOKIE_DOMAIN = process.env.NEXT_PUBLIC_COOKIE_DOMAIN; - - - - diff --git a/apps/sn/.env.local b/apps/sn/.env.local index 256b4daac..87f456490 100644 --- a/apps/sn/.env.local +++ b/apps/sn/.env.local @@ -15,8 +15,10 @@ SERVER_API_URL = https://apigateway.onasys.co.kr SEWERAGE_API_URL = http://localhost:8883 # SEWERAGE_API_URL = http://con.mind-one.co.kr:11083 DC_URL = https://apigateway.apps.rsonesoft.com -# NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = /auth/login +# NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = http://dev.onasys.co.kr:3000/auth/login +# 로그인 이동 주소: 설정하지 않으면 /auth/login +# (.env.local은 운영 빌드에서도 .env.production보다 우선하므로 값을 켜지 않는다) +# NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = /auth/login # NEXT_PUBLIC_SEWERAGE_API_URL=http://192.168.1.66:8883 NEXT_PUBLIC_COOKIE_COMAIN=.mind-one.co.kr NEXT_PUBLIC_NODE_ENV = "development" \ No newline at end of file diff --git a/apps/sn/.env.mindone b/apps/sn/.env.mindone index fb477b3bb..6bb8fcfe8 100644 --- a/apps/sn/.env.mindone +++ b/apps/sn/.env.mindone @@ -13,6 +13,6 @@ NEXT_PUBLIC_NGII_URL = https://map.ngii.go.kr NEXT_PUBLIC_NGII_PARAM = 04trYP9_xwLAfALjwZ-B8g&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={x}&tilerow={y} SEWERAGE_API_URL = http://con.mind-one.co.kr:11083 DC_URL = https://apigateway.apps.rsonesoft.com -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = /auth/login +NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = /auth/login NEXT_PUBLIC_COOKIE_COMAIN=.mind-one.co.kr NEXT_PUBLIC_NODE_ENV = "development" \ No newline at end of file diff --git a/apps/sn/.env.production b/apps/sn/.env.production index f60cba1a1..9ff2f9233 100644 --- a/apps/sn/.env.production +++ b/apps/sn/.env.production @@ -7,7 +7,9 @@ NEXT_PUBLIC_ACCESS_TOKEN = access-token NEXT_PUBLIC_REFRESH_TOKEN = refresh-token #NEXT_PUBLIC_PROXY_HOST = https://devlion.hasuon.or.kr #NEXT_PUBLIC_SUB_DOMAIN = http://front-sn-feature.iipbs-web.svc.cluster.local:13000 -#NEXT_PUBLIC_CM_LOGIN_PAGE_URL = https://devqueen.hasuon.or.kr/auth/login +#NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = https://devqueen.hasuon.or.kr/auth/login +# 로그인 필요(토큰 없음·401·갱신 실패) 시 공통 포털 로그인으로 이동 +NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = https://portal.hasuon.or.kr/auth/login SERVER_API_URL = http://apigateway.iipbs-was.svc.cluster.local:8000 NEXT_PUBLIC_GEOSERVER_URL = http://172.29.143.87:8080/geoserver NEXT_PUBLIC_LX_GEOSERVER_URL = http://172.29.143.87:8080/geoserver_swl diff --git a/apps/sn/docs/작업계획/SN-로그인이동주소통일/001-fe-SN-로그인이동주소통일-작업계획.md b/apps/sn/docs/작업계획/SN-로그인이동주소통일/001-fe-SN-로그인이동주소통일-작업계획.md new file mode 100644 index 000000000..0ef056690 --- /dev/null +++ b/apps/sn/docs/작업계획/SN-로그인이동주소통일/001-fe-SN-로그인이동주소통일-작업계획.md @@ -0,0 +1,122 @@ +# SN·WR·FO 로그인 이동 주소 환경변수 통일 작업계획 + +## 1. 작업 개요 +- 작업명: 로그인 이동 주소 환경변수를 `NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL`로 통일 +- 작성일: 2026-12-03 +- 담당 역할: FE +- 대상 앱: `apps/sn`, `apps/wr`, `apps/fo` +- 근거: 사용자 지시 + +## 2. 작업 목적 +- 로그인 이동 주소를 `NEXT_PUBLIC_CM_LOGIN_PAGE_URL`과 `NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL` 두 변수로 읽던 것을 하나로 정리한다. +- 세 앱의 `env.ts` 인증 설정과 `auth-wrapper.tsx`를 같은 형태로 맞춘다. +- `isExternalLoginUrl()`을 삭제해 인증 흐름을 단순하게 만든다. + +## 3. 수정 대상 +| 구분 | 파일 | 변경 | +| --- | --- | --- | +| 설정 | `apps/{sn,wr,fo}/src/shared/config/env.ts` | `NEXT_PUBLIC_CM_LOGIN_PAGE_URL` 대체 조회 삭제, 인증 설정 구간 동일화 | +| 인증 | `apps/{sn,wr,fo}/src/entities/auth/lib/auth-wrapper.tsx` | `isExternalLoginUrl()`, `goToLogin()` 삭제, `router.replace()` 직접 호출 | +| API | `apps/sn/src/entities/auth/lib/http-unauthorized.ts` | 환경변수 직접 조회 대신 `AUTH_LOGIN_REDIRECT_URL` 사용 | +| API | `apps/wr/components/lib/api/index.ts` | 위와 같음 | +| API | `apps/fo/app/components/api/index.ts` | 위와 같음 | +| 환경 | `.env.production` (세 앱), `apps/wr/.env.dmz` | `CM` 변수 줄 삭제 | +| 환경 | `.env.mindone` (세 앱) | 변수 이름 변경. `fo`는 중복 두 줄을 `/auth/login` 한 줄로 정리 | +| 환경 | `.env.local` (세 앱) | 설정을 주석 처리(코드 기본값 `/auth/login` 사용) | +| 화면 | `apps/fo/app/page.tsx` | 코드에 적힌 계정의 자동 로그인 삭제, 토큰이 없으면 `/auth/login` 이동 | +| 화면 | `apps/wr/app/page.tsx` | 주석으로 남은 계정 정보 삭제 | + +## 4. 설계 판단 + +### 4-1. `isExternalLoginUrl()` 삭제 +Next.js 15.5.18의 `router.replace()`는 이동 주소의 origin이 현재 사이트와 다르면 스스로 `window.location.replace()`로 이동한다. +따라서 다른 도메인(포털)을 구분하는 함수는 필요하지 않다. + +### 4-2. `.env.local`에 새 변수 이름을 그대로 넣지 않는 이유 +`next build`는 `.env.local`을 `.env.production`보다 우선해서 읽는다. +`.env.local`은 저장소에 포함되어 있어 서버에서 받아 빌드하면 함께 적용된다. +이 파일에 `NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL`을 넣으면 운영 빌드의 포털 주소가 로컬 경로로 바뀐다. + +| 앱 | 개발 모드 목표값 | 운영 빌드 목표값 | 처리 | +| --- | --- | --- | --- | +| sn, wr, fo | `/auth/login` | 포털 로그인 | `.env.local` 주석 처리, 코드 기본값 사용 | + +### 4-3. 공통 패키지는 수정하지 않음 +`packages/common/network/utils.ts`는 `NEXT_PUBLIC_CM_LOGIN_PAGE_URL` 대체 조회를 유지한다. +`dm` 등 다른 앱이 이 변수를 사용하며, 세 앱은 `NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL`이 우선 적용되거나 둘 다 없으면 `/auth/login`을 쓴다. + +## 5. 영향 범위 +- 세 앱의 로그인 이동(토큰 없음, 사용자 조회 실패, 갱신 실패, 401) +- 백엔드 API, DB 영향 없음 +- 다른 앱 영향 없음 + +## 6. 검증 방법 +- `@next/env`로 앱별 개발·운영 모드의 실제 적용값을 변경 전후 비교한다. +- 세 앱의 `auth-wrapper.tsx`가 import 경로 외에 같은지 비교한다. +- 수정한 파일의 타입 오류를 확인한다. +- 브라우저 확인: 로그아웃 상태에서 보호 화면에 접속해 로그인 주소로 이동하는지 본다. + +## 7. 롤백 방법 +- 이 작업의 변경 파일을 Git에서 되돌린 뒤 다시 빌드한다. + +## 8. 확인 필요 +- 서버나 배포 파이프라인에서 `NEXT_PUBLIC_CM_LOGIN_PAGE_URL`만 따로 주입하는 환경이 있으면 `NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL`로 바꿔야 한다. +- `.env.mindone`, `.env.dmz`를 어떤 파일 이름으로 복사해 쓰는지 확인해야 한다. + +## 9. 작업 결과 +- 3장의 파일 수정 완료 +- 적용값 비교: 개발 모드는 세 앱 모두 `/auth/login`(코드 기본값). `fo`는 기존 `/`에서 `/auth/login`으로 변경(사용자 확인). 운영 빌드는 세 앱 모두 포털 로그인 주소로 변경 전과 같음 +- 세 앱의 `auth-wrapper.tsx`는 import 경로만 다름. `env.ts`는 사이트 ID, 포트, 서버 API 주소 구간만 다름 +- 타입 검사: `wr`·`fo` 오류 0건, `sn` 오류 3건(수정 파일에서 발생한 것은 없음) +- `git diff --check` 통과 +- `fo` 개발 서버를 임시로 띄워 `/auth/login` 응답 200과 로그인 폼 출력을 확인한 뒤 종료 +- 빌드, 브라우저 조작, 실제 로그인은 수행하지 않음 +- 추가 작업: `fo`·`wr` 루트 화면의 계정 정보 삭제, `fo/.env.mindone` 로그인 주소를 `/auth/login`으로 통일 +- 삭제한 계정 정보는 Git 이력에 남아 있으므로 비밀번호 변경 필요 + +## 10. 추가 작업: 첫 화면에서 로그인 점검 + +### 10-1. 배경 +- 로그아웃 상태에서 `wr` 화면에 접속하면 `common-codes` 등을 호출한 뒤에 로그인 화면으로 이동했다. +- `AuthWrapper`가 자식 화면을 바로 그리고 토큰은 `useEffect`에서 확인했다. 자식의 `useEffect`가 먼저 실행되고, 이동이 끝나기 전에 공통코드 조회 타이머(2초)도 실행됐다. + +### 10-2. 적용 방안 +- 대상: `apps/{sn,wr,fo}/src/entities/auth/lib/auth-wrapper.tsx` +- 로그인 화면이거나 토큰(`token-id`)이 있을 때만 `children`을 그린다(`canRender`). +- 로그인 화면으로 이동한 뒤에도 화면이 열리도록 주소(`pathname`)가 바뀔 때 다시 확인한다. +- 토큰 유무만 확인한다. 만료된 토큰은 첫 API의 401 응답에서 이동한다. +- `middleware.ts`에서의 서버 점검은 적용하지 않는다. + +### 10-3. 영향 범위 +- 세 앱의 모든 화면. 서버에서 미리 그리던 본문이 없어지고, 브라우저에서 토큰을 확인한 뒤 그린다. +- 백엔드 API, DB 영향 없음 + +### 10-4. 검증 방법 +- 임시 개발 서버와 헤드리스 브라우저로 토큰이 없을 때 로그인 화면 이동과 API 호출 여부를 확인한다. +- 토큰 쿠키가 있을 때 화면이 그려지는지 확인한다. API는 빈 응답으로 대체한다. + +### 10-5. 롤백 방법 +- 세 `auth-wrapper.tsx`에서 `canRender` 관련 코드를 제거하고 `children`을 바로 반환한다. + +### 10-6. 작업 결과 +- 코드 수정 완료. 타입 검사에서 `auth-wrapper.tsx` 오류 없음 +- 브라우저 확인(임시 개발 서버, 헤드리스 브라우저, API는 빈 응답으로 대체, 확인 후 서버 종료) + +| 앱 | 토큰 없음: 접속 화면 | 결과 | 토큰 있음 | +| --- | --- | --- | --- | +| sn | `/map` | `/auth/login` 이동, 보호 화면 API 호출 없음 | 지도 화면 API 호출 확인 | +| wr | `/map/mainMap` | `/auth/login` 이동, `common-codes` 호출 없음 | `common-codes` 등 호출 확인 | +| fo | `/pages/dashboard` | `/auth/login` 이동, 보호 화면 API 호출 없음 | 대시보드 API 호출 확인 | + +- 토큰이 없을 때 로그인 화면 자체의 메뉴 조회(`menu-roles`) 1건은 남아 있음 +- 비교: 화면 보류를 끄면 `wr`은 이동 전에 `menu-roles`를 호출했고, `fo`는 대시보드에 머문 채 업무 API를 호출함 +- `wr`·`fo` 로그인 화면의 `` 중첩 콘솔 오류는 10-7에서 수정 +- 실제 백엔드를 연결한 로그인과 운영 빌드는 확인하지 않음 + +### 10-7. 후속 수정: 로그인 화면 `` 중첩 +- 대상: `apps/{wr,fo}/app/(auth)/auth/layout.tsx` +- 원인: 인증 레이아웃이 루트 레이아웃 안에서 ``, ``를 한 번 더 그림 +- 수정: `sn`과 같이 `children`만 반환 +- 확인: 두 앱 로그인 화면에서 `` 중첩 오류가 사라지고 화면이 정상 표시됨. 타입 검사 오류 0건 +- 롤백: 두 `layout.tsx`를 Git에서 되돌림 +- 로그인 화면의 `menu-roles` 조회 1건은 수정하지 않음(사용자 결정) diff --git a/apps/sn/src/entities/auth/lib/auth-wrapper.tsx b/apps/sn/src/entities/auth/lib/auth-wrapper.tsx index fb6edd37a..08823a1f6 100644 --- a/apps/sn/src/entities/auth/lib/auth-wrapper.tsx +++ b/apps/sn/src/entities/auth/lib/auth-wrapper.tsx @@ -1,7 +1,7 @@ "use client"; -import { useEffect } from "react"; -import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; +import { usePathname, useRouter } from "next/navigation"; import { isAxiosError } from "axios"; @@ -23,8 +23,18 @@ import { getToken, setupRefreshTimer } from "./token-manager"; const AuthWrapper = ({ children }: { children: React.ReactNode }) => { const router = useRouter(); + const pathname = usePathname(); const userInfo = useUserStore((state) => state.userInfo); const setUserInfo = useUserStore((state) => state.setUserInfo); + // 화면(children) 표시 여부. false인 동안에는 자식 화면의 API 호출이 시작되지 않는다 + const [canRender, setCanRender] = useState(false); + + // 로그인 화면이거나 토큰이 있을 때만 화면을 연다. 로그인 화면으로 이동하면 다시 확인한다 + useEffect(() => { + if (isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL) || getToken(AUTH_USER_ID)) { + setCanRender(true); + } + }, [pathname]); useEffect(() => { // 페이지 새로고침 시 silentRefresh 타이머 복구 @@ -82,7 +92,7 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { window.removeEventListener("auth:logout", handleAuthLogout); }, []); - return <>{children}>; + return <>{canRender ? children : null}>; }; export { AuthWrapper }; diff --git a/apps/sn/src/entities/auth/lib/http-unauthorized.ts b/apps/sn/src/entities/auth/lib/http-unauthorized.ts index f0c090efa..48caa2ec1 100644 --- a/apps/sn/src/entities/auth/lib/http-unauthorized.ts +++ b/apps/sn/src/entities/auth/lib/http-unauthorized.ts @@ -1,10 +1,7 @@ -import { CLAIM_NAME } from "@/shared/config/env"; +import { AUTH_LOGIN_REDIRECT_URL, CLAIM_NAME } from "@/shared/config/env"; import { getRemainingMs } from "@common/auth"; import { tokenManager } from "./token-manager"; -const LOGIN_PAGE_URL = - process.env.NEXT_PUBLIC_CM_LOGIN_PAGE_URL || "/auth/login"; - export const handleUnauthorizedResponse = () => { if (typeof window === "undefined") return; @@ -21,6 +18,6 @@ export const handleUnauthorizedResponse = () => { window.location.pathname.startsWith("/auth/login/"); if (!isLoginPage) { - window.location.assign(LOGIN_PAGE_URL); + window.location.assign(AUTH_LOGIN_REDIRECT_URL); } }; diff --git a/apps/sn/src/shared/config/env.ts b/apps/sn/src/shared/config/env.ts index 0ec1c73ea..2ea442800 100644 --- a/apps/sn/src/shared/config/env.ts +++ b/apps/sn/src/shared/config/env.ts @@ -3,15 +3,12 @@ export const PORT = process.env.NEXT_PUBLIC_PORT || "3000"; export const PROXY_HOST = process.env.NEXT_PUBLIC_PROXY_HOST || `http://localhost:${PORT}`; export const SERVER_API_URL = process.env.SERVER_API_URL||'https://apigateway.onasys.co.kr'; +// 로그인 이동 주소: 상대경로 또는 다른 도메인(공통 포털)의 절대경로 export const AUTH_LOGIN_REDIRECT_URL = process.env.NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL || "/auth/login"; export const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization"; -export const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token"; -export const REFRESH_TOKEN =process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token"; +export const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token"; +export const REFRESH_TOKEN = process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token"; export const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id"; export const SERVER_SEWERAGE_API_URL = process.env.SEWERAGE_API_URL; export const COOKIE_DOMAIN = process.env.NEXT_PUBLIC_COOKIE_DOMAIN; - - - - diff --git a/apps/wr/.env.dmz b/apps/wr/.env.dmz index bd1dd9e62..0e1a1c180 100644 --- a/apps/wr/.env.dmz +++ b/apps/wr/.env.dmz @@ -7,7 +7,6 @@ NEXT_PUBLIC_ACCESS_TOKEN = access-token NEXT_PUBLIC_REFRESH_TOKEN = refresh-token NEXT_PUBLIC_PROXY_HOST = https://reusematch.hasuon.or.kr # 로그인 필요(토큰 없음·401·갱신 실패) 시 공통 포털 로그인으로 이동 -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = https://portal.hasuon.or.kr/auth/login NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = https://portal.hasuon.or.kr/auth/login SERVER_API_URL = https://apigateway.hasuon.or.kr FO_SERVER_API_URL = https://apigateway.hasuon.or.kr/operation-service/api/v1 diff --git a/apps/wr/.env.local b/apps/wr/.env.local index ad382980f..98becc7c8 100644 --- a/apps/wr/.env.local +++ b/apps/wr/.env.local @@ -19,8 +19,10 @@ SEWERAGE_API_URL = http://con.mind-one.co.kr:11083/sewerage-service # 개발 # SEWERAGE_API_URL=http://localhost:8883/sewerage-service NEXT_PUBLIC_NGII_URL = https://map.ngii.go.kr NEXT_PUBLIC_NGII_PARAM = 04trYP9_xwLAfALjwZ-B8g&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={x}&tilerow={y} -# NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = /auth/login +# NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = http://dev.onasys.co.kr:3000/auth/login +# 로그인 이동 주소: 설정하지 않으면 /auth/login +# (.env.local은 운영 빌드에서도 .env.production보다 우선하므로 값을 켜지 않는다) +# NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = /auth/login NEXT_PUBLIC_HASUDOINFO = https://www.hasudoinfo.or.kr NEXT_PUBLIC_HASUDOINFO_IN = https://www.hasudoinfo.or.kr NEXT_PUBLIC_FINDADRESS_URL = https://business.juso.go.kr/addrlink/addrLinkApi.do diff --git a/apps/wr/.env.mindone b/apps/wr/.env.mindone index a37bd3d2e..9d2bc4e1b 100644 --- a/apps/wr/.env.mindone +++ b/apps/wr/.env.mindone @@ -16,7 +16,7 @@ WR_SERVER_API_URL = http://con.mind-one.co.kr:11083/reuse-service/api/v1 SEWERAGE_API_URL = http://con.mind-one.co.kr:11083/sewerage-service # 개발 서버 API NEXT_PUBLIC_NGII_URL = https://map.ngii.go.kr NEXT_PUBLIC_NGII_PARAM = 04trYP9_xwLAfALjwZ-B8g&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={x}&tilerow={y} -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = /auth/login +NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = /auth/login NEXT_PUBLIC_HASUDOINFO = https://www.hasudoinfo.or.kr NEXT_PUBLIC_HASUDOINFO_IN = https://www.hasudoinfo.or.kr NEXT_PUBLIC_FINDADRESS_URL=https://business.juso.go.kr/addrlink/addrLinkApi.do diff --git a/apps/wr/.env.production b/apps/wr/.env.production index 0cab6a659..63493a0a1 100644 --- a/apps/wr/.env.production +++ b/apps/wr/.env.production @@ -7,7 +7,6 @@ NEXT_PUBLIC_ACCESS_TOKEN = access-token NEXT_PUBLIC_REFRESH_TOKEN = refresh-token NEXT_PUBLIC_PROXY_HOST = https://reuse.hasuon.or.kr # 로그인 필요(토큰 없음·401·갱신 실패) 시 공통 포털 로그인으로 이동 -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = https://portal.hasuon.or.kr/auth/login NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL = https://portal.hasuon.or.kr/auth/login SERVER_API_URL = http://apigateway.iipbs-was.svc.cluster.local:8000 FO_SERVER_API_URL = http://apigateway.iipbs-was.svc.cluster.local:8000/operation-service/api/v1 diff --git a/apps/wr/app/(auth)/auth/layout.tsx b/apps/wr/app/(auth)/auth/layout.tsx index f2a01bd1b..1f5319b18 100644 --- a/apps/wr/app/(auth)/auth/layout.tsx +++ b/apps/wr/app/(auth)/auth/layout.tsx @@ -9,9 +9,6 @@ export default function AuthLayout({ }: { children: React.ReactNode; }) { - return ( - - {children} - - ); + // , 는 루트 레이아웃(app/layout.tsx)에서 그린다 + return children; } diff --git a/apps/wr/app/api/common-codes/route.ts b/apps/wr/app/api/common-codes/route.ts index cd4261ece..9fdc10408 100644 --- a/apps/wr/app/api/common-codes/route.ts +++ b/apps/wr/app/api/common-codes/route.ts @@ -53,6 +53,9 @@ function getServerBaseUrl() { return proxyHost || `http://localhost:${port}`; } +// 요청 1건당 최대 대기 시간(ms). 넘으면 그 요청만 실패 처리하고 나머지는 정상 응답한다. +const REQUEST_TIMEOUT_MS = 5000; + async function fetchJson(url: string, cookieHeader?: string) { const response = await fetch(url, { method: "GET", @@ -61,6 +64,7 @@ async function fetchJson(url: string, cookieHeader?: string) { ...(cookieHeader ? { cookie: cookieHeader } : {}), }, next: { revalidate }, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }); if (!response.ok) { @@ -87,55 +91,111 @@ async function fetchCmsData(path: string, cookieHeader?: string) { return fetchJson(`${getServerBaseUrl()}${path}`, cookieHeader); } -async function fetchCommonCodesByKeys(keys: string[], cookieHeader?: string) { +// 조회에 실패한 항목 1건. 응답의 failedCodes로 브라우저에 전달해 개발자 도구 콘솔에 표시한다. +type FailedCodeType = { + label: string; // 요청 이름(예: "/addr/sgg", "WR003") + reason: string; // 실패 사유(시간 초과, HTTP 상태, 연결 오류 등) +}; + +/** + * 요청 결과(Promise.allSettled)에서 성공 값만 꺼낸다. 실패하면 로그를 남기고 기본값을 돌려준다. + * @param result allSettled가 돌려준 요청 1건의 결과 + * @param label 로그에 남길 요청 이름(예: "/addr/sgg", "WR001") + * @param fallback 실패했을 때 대신 쓸 값 + * @param failures 실패 항목을 모으는 배열(요청마다 새로 만든 배열을 넘긴다) + */ +function settledValue