develop #6
@@ -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 <AppMainLayout>{children}</AppMainLayout>;
|
||||
return <AuthSessionGate><AppMainLayout>{children}</AppMainLayout></AuthSessionGate>;
|
||||
}
|
||||
|
||||
22
src/app/api/auth/[[...slug]]/route.ts
Normal file
22
src/app/api/auth/[[...slug]]/route.ts
Normal file
@@ -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<unknown>("/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;
|
||||
}
|
||||
}
|
||||
@@ -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 (
|
||||
<p
|
||||
role="status"
|
||||
className="p-8 text-center text-sm text-muted-foreground"
|
||||
>
|
||||
로그인 정보를 확인하는 중입니다.
|
||||
</p>
|
||||
);
|
||||
return null;
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<ProjectEntry>
|
||||
<KriMainLayout
|
||||
className="bg-kart-bg text-kart-text"
|
||||
sidebarOpen={hasSidebar && menuOpen}
|
||||
@@ -59,10 +54,10 @@ export function AppMainLayout({ children }: { children: ReactNode }) {
|
||||
mainClassName="bg-kart-bg px-[1.0416vw] pt-2.5 pb-6"
|
||||
>
|
||||
<Fragment key={auth.user.userId + ":" + auth.user.userRole}>
|
||||
<Suspense fallback={<p role="status" className="p-8 text-center text-sm">로그인 정보를 확인하는 중입니다.</p>}>
|
||||
<ProjectEntry>{children}</ProjectEntry>
|
||||
</Suspense>
|
||||
{children}
|
||||
</Fragment>
|
||||
</KriMainLayout>
|
||||
</ProjectEntry>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
19
src/components/app-shell/AuthSessionGate.tsx
Normal file
19
src/components/app-shell/AuthSessionGate.tsx
Normal file
@@ -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 && <div role="alert" className="p-8 text-center text-sm">
|
||||
<p>로그인 정보를 확인하지 못했습니다.</p>
|
||||
<button type="button" onClick={() => { void session.refetch(); }}>다시 시도</button>
|
||||
</div>}
|
||||
{user && <div key={identity} hidden={session.isError}>{children}</div>}
|
||||
</>;
|
||||
}
|
||||
@@ -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<ProjectAccessEvent | null>(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 <p role="status" className="p-8 text-center text-sm">프로젝트 접근 권한을 확인하는 중입니다.</p>;
|
||||
return <QueryState error={result.error} onRetry={() => { setResult(null); setAttempt((value) => value + 1); }} />;
|
||||
}
|
||||
if (project && denied && !denied.allowed && projectKey(denied.project) === projectKey(project)) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<QueryState error={new Error(denied.message ?? "프로젝트에 접근할 권한이 없습니다.")} />
|
||||
<Button variant="outline" onClick={() => router.push("/")}>메인으로 이동</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
85
src/hooks/useAuthSession.ts
Normal file
85
src/hooks/useAuthSession.ts
Normal file
@@ -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<unknown>("/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;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
export const CookieKeys = {
|
||||
AuthToken: "kri_authToken",
|
||||
AuthToken: "kri_internal_authToken",
|
||||
} as const;
|
||||
|
||||
export type CookieKey = (typeof CookieKeys)[keyof typeof CookieKeys];
|
||||
|
||||
Reference in New Issue
Block a user