261103_02_ENH: 공유 인증 사용자 정보 동기화 및 프로젝트 접근 전환 개선
This commit is contained in:
@@ -1,3 +1,4 @@
|
|||||||
|
import { AuthSessionGate } from "@/components/app-shell/AuthSessionGate";
|
||||||
import { AppMainLayout } from "@/components/app-shell/AppMainLayout";
|
import { AppMainLayout } from "@/components/app-shell/AppMainLayout";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
@@ -5,5 +6,5 @@ export const dynamic = "force-dynamic";
|
|||||||
export default function MainLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
export default function MainLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
||||||
// External JWTs live in this tab, so authentication is checked after hydration.
|
// External JWTs live in this tab, so authentication is checked after hydration.
|
||||||
// Every BFF/API request still enforces verified server authentication and scope.
|
// 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]);
|
}, [hydrated, auth.user, auth.external, auth.accessToken, external, externalAllowed, pathname, router]);
|
||||||
const hasSidebar = sideMenus.length > 0;
|
const hasSidebar = sideMenus.length > 0;
|
||||||
if (!hydrated || !auth.user || !externalAllowed || (external && !auth.accessToken))
|
if (!hydrated || !auth.user || !externalAllowed || (external && !auth.accessToken))
|
||||||
return (
|
return null;
|
||||||
<p
|
|
||||||
role="status"
|
|
||||||
className="p-8 text-center text-sm text-muted-foreground"
|
|
||||||
>
|
|
||||||
로그인 정보를 확인하는 중입니다.
|
|
||||||
</p>
|
|
||||||
);
|
|
||||||
return (
|
return (
|
||||||
|
<Suspense fallback={null}>
|
||||||
|
<ProjectEntry>
|
||||||
<KriMainLayout
|
<KriMainLayout
|
||||||
className="bg-kart-bg text-kart-text"
|
className="bg-kart-bg text-kart-text"
|
||||||
sidebarOpen={hasSidebar && menuOpen}
|
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"
|
mainClassName="bg-kart-bg px-[1.0416vw] pt-2.5 pb-6"
|
||||||
>
|
>
|
||||||
<Fragment key={auth.user.userId + ":" + auth.user.userRole}>
|
<Fragment key={auth.user.userId + ":" + auth.user.userRole}>
|
||||||
<Suspense fallback={<p role="status" className="p-8 text-center text-sm">로그인 정보를 확인하는 중입니다.</p>}>
|
{children}
|
||||||
<ProjectEntry>{children}</ProjectEntry>
|
|
||||||
</Suspense>
|
|
||||||
</Fragment>
|
</Fragment>
|
||||||
</KriMainLayout>
|
</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 { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||||
import type { Route } from "next";
|
import type { Route } from "next";
|
||||||
import { useStore } from "jotai";
|
import { useStore } from "jotai";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { authStateAtom, useAuth } from "@/hooks/useAuth";
|
import { authStateAtom, useAuth } from "@/hooks/useAuth";
|
||||||
import { selectedProjectAtom, useSelectedProject } from "@/hooks/useSelectedProject";
|
import { selectedProjectAtom, useSelectedProject } from "@/hooks/useSelectedProject";
|
||||||
import { projectSelectionAtom } from "@/hooks/useProjectNavigation";
|
import { projectSelectionAtom } from "@/hooks/useProjectNavigation";
|
||||||
import { cancelPreviousProjectQueries, checkProjectAccess } from "@/query/project";
|
import { cancelPreviousProjectQueries, checkProjectAccess } from "@/query/project";
|
||||||
import { isProjectPage } from "@/lib/report-navigation";
|
import { isProjectPage } from "@/lib/report-navigation";
|
||||||
import {
|
import {
|
||||||
announceProjectAccess, PROJECT_ACCESS_EVENT, projectAccessMessage, projectFromSearch,
|
announceProjectAccess, PROJECT_ACCESS_EVENT, projectFromSearch,
|
||||||
type ProjectAccessEvent,
|
type ProjectAccessEvent,
|
||||||
} from "@/lib/project-access";
|
} from "@/lib/project-access";
|
||||||
import { isExternalUser } from "@/types/share";
|
import { isExternalUser } from "@/types/share";
|
||||||
import { projectKey } from "@/types/kart";
|
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. */
|
/** Resolve incoming project parameters before mounting any project data consumers. */
|
||||||
export function ProjectEntry({ children }: { children: ReactNode }) {
|
export function ProjectEntry({ children }: { children: ReactNode }) {
|
||||||
@@ -31,13 +29,28 @@ export function ProjectEntry({ children }: { children: ReactNode }) {
|
|||||||
const external = isExternalUser(auth.user);
|
const external = isExternalUser(auth.user);
|
||||||
const hasParams = isProjectPage(pathname) &&
|
const hasParams = isProjectPage(pathname) &&
|
||||||
(new URLSearchParams(search).has("projectType") || new URLSearchParams(search).has("pkey"));
|
(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 [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(() => {
|
useEffect(() => {
|
||||||
if (!hasParams) return;
|
if (!hasParams || (!external && (!access.isSuccess || access.isFetching))) return;
|
||||||
let active = true;
|
let active = true;
|
||||||
const id = store.get(projectSelectionAtom).id + 1;
|
const id = store.get(projectSelectionAtom).id + 1;
|
||||||
store.set(projectSelectionAtom, { id, pending: true });
|
store.set(projectSelectionAtom, { id, pending: true });
|
||||||
@@ -46,26 +59,22 @@ export function ProjectEntry({ children }: { children: ReactNode }) {
|
|||||||
const enter = async () => {
|
const enter = async () => {
|
||||||
// External scope always comes from the verified link, never address parameters.
|
// External scope always comes from the verified link, never address parameters.
|
||||||
if (!external) {
|
if (!external) {
|
||||||
const candidate = projectFromSearch(new URLSearchParams(search));
|
if (projectType === undefined || !pkey || !auth.user) return;
|
||||||
if (!candidate) throw new Error("projectType과 pkey를 올바르게 지정해 주세요.");
|
const incoming = { projectType, pkey };
|
||||||
await checkProjectAccess(candidate);
|
await cancelPreviousProjectQueries(queryClient, auth.user, store.get(selectedProjectAtom), incoming);
|
||||||
if (!current()) return;
|
if (!current()) return;
|
||||||
if (!auth.user) return;
|
select(incoming);
|
||||||
await cancelPreviousProjectQueries(queryClient, auth.user, store.get(selectedProjectAtom), candidate);
|
announceProjectAccess({ project: incoming, allowed: true });
|
||||||
if (!current()) return;
|
|
||||||
select(candidate);
|
|
||||||
announceProjectAccess({ project: candidate, allowed: true });
|
|
||||||
}
|
}
|
||||||
if (!current()) return;
|
if (!current()) return;
|
||||||
const params = new URLSearchParams(search);
|
const params = new URLSearchParams(search);
|
||||||
params.delete("projectType");
|
params.delete("projectType");
|
||||||
params.delete("pkey");
|
params.delete("pkey");
|
||||||
const clean = pathname + (params.size ? "?" + params : "") + window.location.hash;
|
const clean = pathname + (params.size ? "?" + params : "") + window.location.hash;
|
||||||
setResult({ signature, error: null });
|
|
||||||
router.replace(clean as Route, { scroll: false });
|
router.replace(clean as Route, { scroll: false });
|
||||||
};
|
};
|
||||||
void Promise.resolve().then(enter).catch((error: unknown) => {
|
void Promise.resolve().then(enter).catch(() => {
|
||||||
if (current()) setResult({ signature, error: new Error(projectAccessMessage(error)) });
|
if (current()) router.replace("/");
|
||||||
}).finally(() => {
|
}).finally(() => {
|
||||||
if (store.get(projectSelectionAtom).id === id)
|
if (store.get(projectSelectionAtom).id === id)
|
||||||
store.set(projectSelectionAtom, { id, pending: false });
|
store.set(projectSelectionAtom, { id, pending: false });
|
||||||
@@ -75,7 +84,8 @@ export function ProjectEntry({ children }: { children: ReactNode }) {
|
|||||||
if (store.get(projectSelectionAtom).id === id)
|
if (store.get(projectSelectionAtom).id === id)
|
||||||
store.set(projectSelectionAtom, { id: id + 1, pending: false });
|
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(() => {
|
useEffect(() => {
|
||||||
const onAccess = (event: Event) => {
|
const onAccess = (event: Event) => {
|
||||||
@@ -94,18 +104,15 @@ export function ProjectEntry({ children }: { children: ReactNode }) {
|
|||||||
return () => window.removeEventListener(PROJECT_ACCESS_EVENT, onAccess);
|
return () => window.removeEventListener(PROJECT_ACCESS_EVENT, onAccess);
|
||||||
}, [project, auth.user?.userId, queryClient]);
|
}, [project, auth.user?.userId, queryClient]);
|
||||||
|
|
||||||
if (hasParams) {
|
const failed = isProjectPage(pathname) && (
|
||||||
const resolved = result?.signature === signature;
|
(needsAccess && access.isError) ||
|
||||||
if (!resolved || !result.error) return <p role="status" className="p-8 text-center text-sm">프로젝트 접근 권한을 확인하는 중입니다.</p>;
|
(hasParams && !external && !candidate) ||
|
||||||
return <QueryState error={result.error} onRetry={() => { setResult(null); setAttempt((value) => value + 1); }} />;
|
(!hasParams && !!project && !!denied && !denied.allowed && projectKey(denied.project) === projectKey(project))
|
||||||
}
|
);
|
||||||
if (project && denied && !denied.allowed && projectKey(denied.project) === projectKey(project)) {
|
useEffect(() => {
|
||||||
return (
|
if (failed) router.replace("/");
|
||||||
<div className="space-y-3">
|
}, [failed, router]);
|
||||||
<QueryState error={new Error(denied.message ?? "프로젝트에 접근할 권한이 없습니다.")} />
|
|
||||||
<Button variant="outline" onClick={() => router.push("/")}>메인으로 이동</Button>
|
if (hasParams || failed || (needsAccess && !access.isSuccess)) return null;
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return children;
|
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;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user