From 5f41995c841fd511f23b02d91ded707e1bd9472a Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Tue, 3 Nov 2026 15:22:19 +0900 Subject: [PATCH] =?UTF-8?q?261103=5F02=5FENH:=20=EA=B3=B5=EC=9C=A0=20?= =?UTF-8?q?=EC=9D=B8=EC=A6=9D=20=EC=82=AC=EC=9A=A9=EC=9E=90=20=EC=A0=95?= =?UTF-8?q?=EB=B3=B4=20=EB=8F=99=EA=B8=B0=ED=99=94=20=EB=B0=8F=20=ED=94=84?= =?UTF-8?q?=EB=A1=9C=EC=A0=9D=ED=8A=B8=20=EC=A0=91=EA=B7=BC=20=EC=A0=84?= =?UTF-8?q?=ED=99=98=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/(pages)/(main)/layout.tsx | 3 +- src/app/api/auth/[[...slug]]/route.ts | 22 +++++ src/components/app-shell/AppMainLayout.tsx | 17 ++-- src/components/app-shell/AuthSessionGate.tsx | 19 +++++ src/components/project/ProjectEntry.tsx | 73 +++++++++-------- src/hooks/useAuthSession.ts | 85 ++++++++++++++++++++ 6 files changed, 174 insertions(+), 45 deletions(-) create mode 100644 src/app/api/auth/[[...slug]]/route.ts create mode 100644 src/components/app-shell/AuthSessionGate.tsx create mode 100644 src/hooks/useAuthSession.ts diff --git a/src/app/(pages)/(main)/layout.tsx b/src/app/(pages)/(main)/layout.tsx index 137f857..74c3051 100644 --- a/src/app/(pages)/(main)/layout.tsx +++ b/src/app/(pages)/(main)/layout.tsx @@ -1,3 +1,4 @@ +import { AuthSessionGate } from "@/components/app-shell/AuthSessionGate"; import { AppMainLayout } from "@/components/app-shell/AppMainLayout"; export const dynamic = "force-dynamic"; @@ -5,5 +6,5 @@ export const dynamic = "force-dynamic"; export default function MainLayout({ children }: Readonly<{ children: React.ReactNode }>) { // External JWTs live in this tab, so authentication is checked after hydration. // Every BFF/API request still enforces verified server authentication and scope. - return {children}; + return {children}; } diff --git a/src/app/api/auth/[[...slug]]/route.ts b/src/app/api/auth/[[...slug]]/route.ts new file mode 100644 index 0000000..8bfe535 --- /dev/null +++ b/src/app/api/auth/[[...slug]]/route.ts @@ -0,0 +1,22 @@ +import { NextResponse } from "next/server"; +import { errorToResponse } from "@kri/common/http"; +import { createServerApi } from "@/lib/http-server"; +import { isLoginUser } from "@/types/kart"; + +export async function GET(_request: Request, context: { params: Promise<{ slug?: string[] }> }) { + const { slug = [] } = await context.params; + if (slug.length !== 1 || slug[0] !== "my-info") + return NextResponse.json({ message: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } }); + try { + const api = await createServerApi(); + const user = await api.get("/auth/my-info", { cache: "no-store" }); + if (!isLoginUser(user)) { + return NextResponse.json({ message: "Invalid user response" }, { status: 502, headers: { "Cache-Control": "no-store" } }); + } + return NextResponse.json({ userId: user.userId, userName: user.userName, userCmpn: user.userCmpn, userTeam: user.userTeam, userRole: user.userRole }, { headers: { "Cache-Control": "no-store" } }); + } catch (error) { + const response = errorToResponse(error); + response.headers.set("Cache-Control", "no-store"); + return response; + } +} diff --git a/src/components/app-shell/AppMainLayout.tsx b/src/components/app-shell/AppMainLayout.tsx index 017fb0f..8ae1f5c 100644 --- a/src/components/app-shell/AppMainLayout.tsx +++ b/src/components/app-shell/AppMainLayout.tsx @@ -28,15 +28,10 @@ export function AppMainLayout({ children }: { children: ReactNode }) { }, [hydrated, auth.user, auth.external, auth.accessToken, external, externalAllowed, pathname, router]); const hasSidebar = sideMenus.length > 0; if (!hydrated || !auth.user || !externalAllowed || (external && !auth.accessToken)) - return ( -

- 로그인 정보를 확인하는 중입니다. -

- ); + return null; return ( + + - 로그인 정보를 확인하는 중입니다.

}> - {children} -
+ {children}
+
+
); } diff --git a/src/components/app-shell/AuthSessionGate.tsx b/src/components/app-shell/AuthSessionGate.tsx new file mode 100644 index 0000000..a759aa7 --- /dev/null +++ b/src/components/app-shell/AuthSessionGate.tsx @@ -0,0 +1,19 @@ +"use client"; + +import type { ReactNode } from "react"; +import { useAuthSession } from "@/hooks/useAuthSession"; + +export function AuthSessionGate({ children }: { children: ReactNode }) { + const session = useAuthSession(); + const user = session.data; + const checking = session.isPending || session.isFetching; + const identity = user && JSON.stringify([user.userId, user.userRole, user.userTeam, user.userCmpn]); + + return <> + {session.isError && !checking &&
+

로그인 정보를 확인하지 못했습니다.

+ +
} + {user && } + ; +} diff --git a/src/components/project/ProjectEntry.tsx b/src/components/project/ProjectEntry.tsx index 46cf481..f8629ad 100644 --- a/src/components/project/ProjectEntry.tsx +++ b/src/components/project/ProjectEntry.tsx @@ -4,20 +4,18 @@ import { useEffect, useState, type ReactNode } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import type { Route } from "next"; import { useStore } from "jotai"; -import { useQueryClient } from "@tanstack/react-query"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import { authStateAtom, useAuth } from "@/hooks/useAuth"; import { selectedProjectAtom, useSelectedProject } from "@/hooks/useSelectedProject"; import { projectSelectionAtom } from "@/hooks/useProjectNavigation"; import { cancelPreviousProjectQueries, checkProjectAccess } from "@/query/project"; import { isProjectPage } from "@/lib/report-navigation"; import { - announceProjectAccess, PROJECT_ACCESS_EVENT, projectAccessMessage, projectFromSearch, + announceProjectAccess, PROJECT_ACCESS_EVENT, projectFromSearch, type ProjectAccessEvent, } from "@/lib/project-access"; import { isExternalUser } from "@/types/share"; import { projectKey } from "@/types/kart"; -import { Button } from "@/components/ui/button"; -import { QueryState } from "./QueryState"; /** Resolve incoming project parameters before mounting any project data consumers. */ export function ProjectEntry({ children }: { children: ReactNode }) { @@ -31,13 +29,28 @@ export function ProjectEntry({ children }: { children: ReactNode }) { const external = isExternalUser(auth.user); const hasParams = isProjectPage(pathname) && (new URLSearchParams(search).has("projectType") || new URLSearchParams(search).has("pkey")); - const signature = pathname + "?" + search; - const [attempt, setAttempt] = useState(0); - const [result, setResult] = useState<{ signature: string; error: Error | null } | null>(null); const [denied, setDenied] = useState(null); + const candidate = hasParams ? projectFromSearch(new URLSearchParams(search)) : project; + const projectType = candidate?.projectType; + const pkey = candidate?.pkey; + const needsAccess = isProjectPage(pathname) && !external && !!candidate; + const access = useQuery({ + queryKey: ["kart", auth.user?.userId, auth.user?.userRole, auth.user?.userTeam, + "project-access", projectType, pkey], + enabled: needsAccess, + queryFn: async () => { + if (!candidate) throw new Error("Project required"); + await checkProjectAccess(candidate); + return true; + }, + staleTime: 0, + retry: false, + refetchOnWindowFocus: false, + meta: { ignoreGlobalLoading: true }, + }); useEffect(() => { - if (!hasParams) return; + if (!hasParams || (!external && (!access.isSuccess || access.isFetching))) return; let active = true; const id = store.get(projectSelectionAtom).id + 1; store.set(projectSelectionAtom, { id, pending: true }); @@ -46,26 +59,22 @@ export function ProjectEntry({ children }: { children: ReactNode }) { const enter = async () => { // External scope always comes from the verified link, never address parameters. if (!external) { - const candidate = projectFromSearch(new URLSearchParams(search)); - if (!candidate) throw new Error("projectType과 pkey를 올바르게 지정해 주세요."); - await checkProjectAccess(candidate); + if (projectType === undefined || !pkey || !auth.user) return; + const incoming = { projectType, pkey }; + await cancelPreviousProjectQueries(queryClient, auth.user, store.get(selectedProjectAtom), incoming); if (!current()) return; - if (!auth.user) return; - await cancelPreviousProjectQueries(queryClient, auth.user, store.get(selectedProjectAtom), candidate); - if (!current()) return; - select(candidate); - announceProjectAccess({ project: candidate, allowed: true }); + select(incoming); + announceProjectAccess({ project: incoming, allowed: true }); } if (!current()) return; const params = new URLSearchParams(search); params.delete("projectType"); params.delete("pkey"); const clean = pathname + (params.size ? "?" + params : "") + window.location.hash; - setResult({ signature, error: null }); router.replace(clean as Route, { scroll: false }); }; - void Promise.resolve().then(enter).catch((error: unknown) => { - if (current()) setResult({ signature, error: new Error(projectAccessMessage(error)) }); + void Promise.resolve().then(enter).catch(() => { + if (current()) router.replace("/"); }).finally(() => { if (store.get(projectSelectionAtom).id === id) store.set(projectSelectionAtom, { id, pending: false }); @@ -75,7 +84,8 @@ export function ProjectEntry({ children }: { children: ReactNode }) { if (store.get(projectSelectionAtom).id === id) store.set(projectSelectionAtom, { id: id + 1, pending: false }); }; - }, [hasParams, search, pathname, signature, auth, external, select, router, store, queryClient, attempt]); + }, [hasParams, search, pathname, projectType, pkey, access.isSuccess, access.isFetching, + auth, external, select, router, store, queryClient]); useEffect(() => { const onAccess = (event: Event) => { @@ -94,18 +104,15 @@ export function ProjectEntry({ children }: { children: ReactNode }) { return () => window.removeEventListener(PROJECT_ACCESS_EVENT, onAccess); }, [project, auth.user?.userId, queryClient]); - if (hasParams) { - const resolved = result?.signature === signature; - if (!resolved || !result.error) return

프로젝트 접근 권한을 확인하는 중입니다.

; - return { setResult(null); setAttempt((value) => value + 1); }} />; - } - if (project && denied && !denied.allowed && projectKey(denied.project) === projectKey(project)) { - return ( -
- - -
- ); - } + const failed = isProjectPage(pathname) && ( + (needsAccess && access.isError) || + (hasParams && !external && !candidate) || + (!hasParams && !!project && !!denied && !denied.allowed && projectKey(denied.project) === projectKey(project)) + ); + useEffect(() => { + if (failed) router.replace("/"); + }, [failed, router]); + + if (hasParams || failed || (needsAccess && !access.isSuccess)) return null; return children; } diff --git a/src/hooks/useAuthSession.ts b/src/hooks/useAuthSession.ts new file mode 100644 index 0000000..c14139b --- /dev/null +++ b/src/hooks/useAuthSession.ts @@ -0,0 +1,85 @@ +"use client"; + +import { useEffect } from "react"; +import { useAtomValue, useStore } from "jotai"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useRouter } from "next/navigation"; +import { apiError } from "@kri/common/http"; +import { authStateAtom, useAuth } from "@/hooks/useAuth"; +import { selectedProjectAtom } from "@/hooks/useSelectedProject"; +import { authApi } from "@/lib/http-client"; +import { isLoginUser } from "@/types/kart"; +import { isExternalSession, isExternalUser } from "@/types/share"; + +const SESSION_QUERY_KEY = ["auth-session"] as const; + +export function useAuthSession() { + const store = useStore(); + const queryClient = useQueryClient(); + const router = useRouter(); + const { setAuth, hydrated } = useAuth(); + useAtomValue(selectedProjectAtom); + const projectHydrated = useAtomValue(selectedProjectAtom.hydratedAtom); + const otherQueries = { predicate: (query: { queryKey: readonly unknown[] }) => query.queryKey[0] !== SESSION_QUERY_KEY[0] }; + + useEffect(() => { + const refresh = () => { + void queryClient.refetchQueries({ queryKey: SESSION_QUERY_KEY, exact: true, type: "active" }, { cancelRefetch: false }); + }; + window.addEventListener("focus", refresh); + return () => window.removeEventListener("focus", refresh); + }, [queryClient]); + + return useQuery({ + queryKey: SESSION_QUERY_KEY, + enabled: hydrated && projectHydrated, + staleTime: 0, + gcTime: 0, + retry: false, + refetchOnMount: "always", + refetchOnWindowFocus: "always", + meta: { ignoreGlobalLoading: true }, + queryFn: async ({ signal }) => { + const previous = store.get(authStateAtom); + try { + const user = await authApi.get("/auth/my-info", { + cache: "no-store", + skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true, + headers: previous.mode === "external" ? { Authorization: `Bearer ${previous.accessToken ?? ""}` } : undefined, + }); + signal.throwIfAborted(); + if (!isLoginUser(user)) throw new Error("Invalid user response"); + if (previous.mode === "external" && !isExternalSession({ user, link: previous.external })) throw new Error("Invalid link session"); + if (previous.mode !== "external" && isExternalUser(user)) throw new Error("Invalid normal session"); + const before = previous.user; + const changed = !before || before.userId !== user.userId || before.userRole !== user.userRole || + before.userTeam !== user.userTeam || before.userCmpn !== user.userCmpn; + if (changed) { + await queryClient.cancelQueries(otherQueries); + signal.throwIfAborted(); + queryClient.removeQueries(otherQueries); + queryClient.getMutationCache().clear(); + if (previous.mode !== "external") { + const selected = store.get(selectedProjectAtom); + if (selected) store.set(selectedProjectAtom, { ...selected, userId: user.userId }); + } + } + if (changed || before?.userName !== user.userName) setAuth(previous.mode === "external" ? { ...previous, user } : { user }); + return user; + } catch (reason) { + signal.throwIfAborted(); + const status = apiError(reason).status; + if (status === 401 || status === 403) { + await queryClient.cancelQueries(otherQueries); + signal.throwIfAborted(); + queryClient.removeQueries(otherQueries); + queryClient.getMutationCache().clear(); + store.set(selectedProjectAtom, null); + setAuth({ user: null }); + router.replace(previous.mode === "external" ? "/logout" : "/login"); + } + throw reason; + } + }, + }); +}