develop #5
@@ -1,3 +1,4 @@
|
||||
NEXT_PUBLIC_ENV=development
|
||||
ENV=development
|
||||
API_SERVER=http://127.0.0.1:4015/api/v1
|
||||
AUTH_COOKIE_DOMAIN=kric.com
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
NEXT_PUBLIC_ENV=local
|
||||
ENV=local
|
||||
API_SERVER=http://localhost:4015/api/v1
|
||||
AUTH_COOKIE_DOMAIN=
|
||||
@@ -1,3 +1,4 @@
|
||||
NEXT_PUBLIC_ENV=production
|
||||
ENV=production
|
||||
ENV=prod
|
||||
API_SERVER=http://127.0.0.1:4015/api/v1
|
||||
AUTH_COOKIE_DOMAIN=kric.com
|
||||
|
||||
@@ -229,6 +229,7 @@ When implementation is complete, report in Korean:
|
||||
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
|
||||
- Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
|
||||
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects.
|
||||
- Do not use nested ternary expressions. Use clear `if`/`else` branches, early returns, or well-named intermediate variables instead; a single, non-nested ternary is acceptable only when it remains immediately readable.
|
||||
- Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable.
|
||||
- Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states.
|
||||
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { AppMainLayout } from "@/components/app-shell/AppMainLayout";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
|
||||
export default async function MainLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
||||
const cookieStore = await cookies();
|
||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
|
||||
if (!accessToken) redirect("/logout");
|
||||
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>;
|
||||
}
|
||||
|
||||
@@ -3,18 +3,20 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useLogoutMutation } from "@/query/auth";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
|
||||
export default function LogoutPage() {
|
||||
const router = useRouter();
|
||||
const { hydrated } = useAuth();
|
||||
const logoutMutation = useLogoutMutation();
|
||||
const started = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (started.current) return;
|
||||
if (!hydrated || started.current) return;
|
||||
started.current = true;
|
||||
void logoutMutation.mutateAsync().finally(() => router.replace("/login"));
|
||||
}, [logoutMutation, router]);
|
||||
}, [hydrated, logoutMutation, router]);
|
||||
|
||||
return <LoadingOverlayAdapter force label="로그아웃 중" />;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||
import {
|
||||
bookmarkUpstreamPath,
|
||||
isBookmarkCreatePath,
|
||||
@@ -9,7 +8,6 @@ import {
|
||||
isBookmarkListPath,
|
||||
} from "@/lib/project-proxy-policy";
|
||||
import { isBookmarkPage, readBookmarkSaveRequest } from "@/types/bookmark";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
|
||||
const notFound = () =>
|
||||
@@ -19,7 +17,7 @@ const unauthorized = () =>
|
||||
const badRequest = () =>
|
||||
NextResponse.json({ message: "북마크 저장 내용을 확인해 주세요." }, { status: 400 });
|
||||
const noStore = { headers: { "Cache-Control": "no-store" } };
|
||||
const loggedIn = async () => !!(await cookies()).get(CookieKeys.AuthToken)?.value;
|
||||
const loggedIn = async () => !!(await getServerAccessToken());
|
||||
|
||||
export async function GET(request: NextRequest, context: RouteContext) {
|
||||
const { slug = [] } = await context.params;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||
import {
|
||||
derivedUpstreamPath,
|
||||
isDerivedCreatePath,
|
||||
@@ -9,7 +8,6 @@ import {
|
||||
isDerivedListPath,
|
||||
} from "@/lib/project-proxy-policy";
|
||||
import { readDerivedSaveRequest } from "@/types/derived";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
|
||||
const notFound = () =>
|
||||
@@ -17,7 +15,7 @@ const notFound = () =>
|
||||
const unauthorized = () =>
|
||||
NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||
const noStore = { headers: { "Cache-Control": "no-store" } };
|
||||
const loggedIn = async () => !!(await cookies()).get(CookieKeys.AuthToken)?.value;
|
||||
const loggedIn = async () => !!(await getServerAccessToken());
|
||||
|
||||
export async function GET(_request: NextRequest, context: RouteContext) {
|
||||
const { slug = [] } = await context.params;
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||
import { exportTarget } from "@/lib/project-proxy-policy";
|
||||
import { readExcelRequest, readRawDataRequest } from "@/types/export";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
|
||||
// Workbooks for large projects take a while to build on the server.
|
||||
@@ -20,7 +18,7 @@ async function download(request: NextRequest, context: RouteContext, method: "GE
|
||||
const target = exportTarget(method, slug);
|
||||
if (!target)
|
||||
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
||||
if (!(await getServerAccessToken()))
|
||||
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||
let body: unknown;
|
||||
if (target.body !== "none") {
|
||||
|
||||
13
src/app/api/external/[urlkey]/login/route.ts
vendored
13
src/app/api/external/[urlkey]/login/route.ts
vendored
@@ -1,21 +1,17 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
|
||||
import { serverEnv } from "@/lib/env.server";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import { isRecord } from "@/types/kart";
|
||||
import { isExternalSession, isUrlKey } from "@/types/share";
|
||||
|
||||
export async function POST(_request: NextRequest, context: { params: Promise<{ urlkey: string }> }) {
|
||||
const { urlkey } = await context.params;
|
||||
let response: NextResponse;
|
||||
let token = "";
|
||||
try {
|
||||
if (!isUrlKey(urlkey)) {
|
||||
response = NextResponse.json({ message: "공유 링크를 찾을 수 없습니다." }, { status: 404 });
|
||||
} else {
|
||||
// Link login replaces the previous identity, including an expired credential cookie.
|
||||
// A link login issues a tab-scoped credential without touching normal-login cookies.
|
||||
const api = await createServerApi(false);
|
||||
const result = await api.post<unknown>(`/external/${urlkey}/login`, null, { cache: "no-store" });
|
||||
const accessToken = isRecord(result) ? result.accessToken : null;
|
||||
@@ -23,8 +19,7 @@ export async function POST(_request: NextRequest, context: { params: Promise<{ u
|
||||
typeof accessToken !== "string" || !accessToken) {
|
||||
response = NextResponse.json({ message: "공유 링크 로그인 응답을 확인해 주세요." }, { status: 502 });
|
||||
} else {
|
||||
token = accessToken;
|
||||
response = NextResponse.json({ user: result.user, link: result.link });
|
||||
response = NextResponse.json({ user: result.user, link: result.link, accessToken });
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -32,9 +27,5 @@ export async function POST(_request: NextRequest, context: { params: Promise<{ u
|
||||
response = new NextResponse(failure.body, { status: failure.status, headers: failure.headers });
|
||||
}
|
||||
response.headers.set("Cache-Control", "no-store");
|
||||
response.cookies.set(CookieKeys.AuthToken, token, {
|
||||
httpOnly: true, secure: ["prod", "production"].includes(serverEnv.ENV),
|
||||
sameSite: "lax", path: "/", maxAge: token ? AUTH_COOKIE_MAX_AGE : 0,
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||
import { isImportPath } from "@/lib/project-proxy-policy";
|
||||
import { readImportResult } from "@/types/export";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
|
||||
// Imports replace project data on the server and may run for minutes.
|
||||
@@ -15,7 +13,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
||||
const { slug = [] } = await context.params;
|
||||
if (!isImportPath(slug))
|
||||
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
||||
if (!(await getServerAccessToken()))
|
||||
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||
let file: File;
|
||||
try {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||
import { isProjectRef, isRecord } from "@/types/kart";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
||||
if (!(await getServerAccessToken()))
|
||||
return NextResponse.json(
|
||||
{ message: "로그인이 필요합니다." },
|
||||
{ status: 401 },
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
|
||||
import { serverEnv } from "@/lib/env.server";
|
||||
import { setAuthCookie } from "@/lib/auth-cookie";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import { isLoginUser, isRecord } from "@/types/kart";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
|
||||
@@ -28,7 +26,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const serverApi = await createServerApi();
|
||||
const serverApi = await createServerApi(false);
|
||||
const result = await serverApi.post<unknown>(
|
||||
"/auth/login",
|
||||
{ userId: body.userId.trim(), userPw: body.userPw },
|
||||
@@ -48,13 +46,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
||||
const response = NextResponse.json(result.user, {
|
||||
headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
response.cookies.set(CookieKeys.AuthToken, result.accessToken, {
|
||||
httpOnly: true,
|
||||
secure: ["prod", "production"].includes(serverEnv.ENV),
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: AUTH_COOKIE_MAX_AGE,
|
||||
});
|
||||
setAuthCookie(response, result.accessToken);
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SyntaxError)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { serverEnv } from "@/lib/env.server";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import { setAuthCookie } from "@/lib/auth-cookie";
|
||||
|
||||
/** Stateless backend authentication has no logout API; discard the frontend session cookie. */
|
||||
export async function POST() {
|
||||
@@ -8,12 +7,6 @@ export async function POST() {
|
||||
{ ok: true },
|
||||
{ headers: { "Cache-Control": "no-store" } },
|
||||
);
|
||||
response.cookies.set(CookieKeys.AuthToken, "", {
|
||||
httpOnly: true,
|
||||
secure: ["prod", "production"].includes(serverEnv.ENV),
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 0,
|
||||
});
|
||||
setAuthCookie(response, "");
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||
import { readReportBatch } from "@/lib/report-contract";
|
||||
import {
|
||||
isProjectReadPath,
|
||||
projectReadQuery,
|
||||
isReportStreamPath,
|
||||
} from "@/lib/project-proxy-policy";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
|
||||
export async function GET(request: NextRequest, context: RouteContext) {
|
||||
@@ -18,7 +16,7 @@ export async function GET(request: NextRequest, context: RouteContext) {
|
||||
{ message: "지원하지 않는 경로입니다." },
|
||||
{ status: 404 },
|
||||
);
|
||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
||||
if (!(await getServerAccessToken()))
|
||||
return NextResponse.json(
|
||||
{ message: "로그인이 필요합니다." },
|
||||
{ status: 401 },
|
||||
@@ -49,7 +47,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
||||
{ message: "지원하지 않는 경로입니다." },
|
||||
{ status: 404 },
|
||||
);
|
||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
||||
if (!(await getServerAccessToken()))
|
||||
return NextResponse.json(
|
||||
{ message: "로그인이 필요합니다." },
|
||||
{ status: 401 },
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||
import { isQuotaListPath, isQuotaResultPath } from "@/lib/project-proxy-policy";
|
||||
import { readQuotaRequest } from "@/types/quota";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
|
||||
const notFound = () =>
|
||||
@@ -15,7 +13,7 @@ const unauthorized = () =>
|
||||
export async function GET(_request: NextRequest, context: RouteContext) {
|
||||
const { slug = [] } = await context.params;
|
||||
if (!isQuotaListPath(slug)) return notFound();
|
||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value) return unauthorized();
|
||||
if (!(await getServerAccessToken())) return unauthorized();
|
||||
try {
|
||||
const serverApi = await createServerApi();
|
||||
const result = await serverApi.get<unknown>(
|
||||
@@ -31,7 +29,7 @@ export async function GET(_request: NextRequest, context: RouteContext) {
|
||||
export async function POST(request: NextRequest, context: RouteContext) {
|
||||
const { slug = [] } = await context.params;
|
||||
if (!isQuotaResultPath(slug)) return notFound();
|
||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value) return unauthorized();
|
||||
if (!(await getServerAccessToken())) return unauthorized();
|
||||
let body;
|
||||
try {
|
||||
body = readQuotaRequest(await request.json());
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { createServerApi } from "@/lib/http-server";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||
import { isProjectRef, isRecord } from "@/types/kart";
|
||||
import { isShareLink } from "@/types/share";
|
||||
|
||||
@@ -12,7 +10,7 @@ export async function POST(request: NextRequest, context: {
|
||||
const params = await context.params;
|
||||
const project = { projectType: params.projectType === "0" ? 0 : params.projectType === "1" ? 1 : null, pkey: params.pkey };
|
||||
if (!isProjectRef(project)) return NextResponse.json({ message: "프로젝트를 확인해 주세요." }, { status: 400 });
|
||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
||||
if (!(await getServerAccessToken()))
|
||||
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||
let body: unknown;
|
||||
try { body = await request.json(); } catch { body = null; }
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Fragment, Suspense, useEffect, useState, type ReactNode } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
||||
import { AppHeader } from "./AppHeader";
|
||||
import { ProjectEntry } from "@/components/project/ProjectEntry";
|
||||
import { AppSidebar } from "./AppSidebar";
|
||||
import { sideMenus } from "@/config/menu.data";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
@@ -19,13 +20,14 @@ export function AppMainLayout({ children }: { children: ReactNode }) {
|
||||
const externalAllowed = !external || (!!auth.external && externalPageAllowed(auth.external, pathname));
|
||||
useEffect(() => {
|
||||
if (hydrated && !auth.user) router.replace("/logout");
|
||||
else if (hydrated && external && !auth.accessToken) router.replace("/logout");
|
||||
// Legacy Main sends shared-link users (isAdmin > 8) to Logout, ending the External session.
|
||||
else if (hydrated && external && pathname === "/") router.replace("/logout");
|
||||
else if (hydrated && !externalAllowed)
|
||||
router.replace((auth.external ? reportUrl(auth.external.realUrl) : "/logout") as Route);
|
||||
}, [hydrated, auth.user, auth.external, external, externalAllowed, pathname, router]);
|
||||
}, [hydrated, auth.user, auth.external, auth.accessToken, external, externalAllowed, pathname, router]);
|
||||
const hasSidebar = sideMenus.length > 0;
|
||||
if (!hydrated || !auth.user || !externalAllowed)
|
||||
if (!hydrated || !auth.user || !externalAllowed || (external && !auth.accessToken))
|
||||
return (
|
||||
<p
|
||||
role="status"
|
||||
@@ -56,7 +58,11 @@ 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}>{children}</Fragment>
|
||||
<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>
|
||||
</Fragment>
|
||||
</KriMainLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,29 +7,28 @@ import { useSetAtom } from "jotai";
|
||||
import { apiError } from "@kri/common/http";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useResetSession } from "@/hooks/useResetSession";
|
||||
import { notifyAuthChange } from "@/lib/auth-change";
|
||||
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { isExternalSession, reportUrl, type ExternalSession } from "@/types/share";
|
||||
import { authApi } from "@/lib/http-client";
|
||||
import { isExternalLoginResponse, reportUrl, type ExternalLoginResponse } from "@/types/share";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
|
||||
export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
||||
const router = useRouter();
|
||||
const { hydrated, setAuth, logout } = useAuth();
|
||||
const { hydrated, setAuth } = useAuth();
|
||||
const setProject = useSetAtom(selectedProjectAtom);
|
||||
const resetSession = useResetSession();
|
||||
const pending = useRef<Promise<ExternalSession> | null>(null);
|
||||
const pending = useRef<Promise<ExternalLoginResponse> | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
useEffect(() => {
|
||||
if (!hydrated) return;
|
||||
let active = true;
|
||||
const enter = async () => {
|
||||
logout();
|
||||
setAuth({ mode: "external", user: null });
|
||||
await resetSession();
|
||||
const result = await nextApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
|
||||
const result = await authApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
|
||||
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
||||
});
|
||||
if (!isExternalSession(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
|
||||
if (!isExternalLoginResponse(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
|
||||
return result;
|
||||
};
|
||||
// Reuse the request during StrictMode effect replay; each entry records one landing.
|
||||
@@ -37,17 +36,15 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
||||
void pending.current.then((result) => {
|
||||
if (!active) return;
|
||||
setProject({ userId: result.user.userId, project: { projectType: result.link.projectType, pkey: result.link.pkey } });
|
||||
setAuth({ user: result.user, external: result.link });
|
||||
notifyAuthChange(result.link.realUrl);
|
||||
setAuth({ mode: "external", user: result.user, external: result.link, accessToken: result.accessToken });
|
||||
router.replace(reportUrl(result.link.realUrl) as Route);
|
||||
}).catch((reason: unknown) => {
|
||||
if (active) {
|
||||
notifyAuthChange("/login");
|
||||
setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
|
||||
}
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, [hydrated, logout, setAuth, setProject, resetSession, router, urlKey]);
|
||||
}, [hydrated, setAuth, setProject, resetSession, router, urlKey]);
|
||||
if (error) return <p role="alert" className="p-8 text-center text-sm">{error}</p>;
|
||||
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
|
||||
}
|
||||
|
||||
111
src/components/project/ProjectEntry.tsx
Normal file
111
src/components/project/ProjectEntry.tsx
Normal file
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
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 { 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,
|
||||
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 }) {
|
||||
const pathname = usePathname();
|
||||
const search = useSearchParams().toString();
|
||||
const router = useRouter();
|
||||
const store = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const { auth } = useAuth();
|
||||
const { project, select } = useSelectedProject();
|
||||
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);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasParams) return;
|
||||
let active = true;
|
||||
const id = store.get(projectSelectionAtom).id + 1;
|
||||
store.set(projectSelectionAtom, { id, pending: true });
|
||||
const current = () => active && store.get(projectSelectionAtom).id === id &&
|
||||
store.get(authStateAtom) === auth;
|
||||
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 (!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 });
|
||||
}
|
||||
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)) });
|
||||
}).finally(() => {
|
||||
if (store.get(projectSelectionAtom).id === id)
|
||||
store.set(projectSelectionAtom, { id, pending: false });
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
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]);
|
||||
|
||||
useEffect(() => {
|
||||
const onAccess = (event: Event) => {
|
||||
const detail = (event as CustomEvent<ProjectAccessEvent>).detail;
|
||||
if (!project || projectKey(detail.project) !== projectKey(project)) return;
|
||||
setDenied(detail.allowed ? null : detail);
|
||||
if (!detail.allowed) {
|
||||
const predicate = (query: { queryKey: readonly unknown[] }) =>
|
||||
query.queryKey[0] === "kart" && query.queryKey[1] === auth.user?.userId &&
|
||||
query.queryKey.some((part, index, key) =>
|
||||
part === project.projectType && key[index + 1] === project.pkey);
|
||||
void queryClient.cancelQueries({ predicate }).then(() => queryClient.removeQueries({ predicate }));
|
||||
}
|
||||
};
|
||||
window.addEventListener(PROJECT_ACCESS_EVENT, onAccess);
|
||||
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>
|
||||
);
|
||||
}
|
||||
return children;
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import type { Route } from "next";
|
||||
import { useProjectNavigation } from "@/hooks/useProjectNavigation";
|
||||
import { projectPageUrl } from "@/lib/project-access";
|
||||
import { useEffect } from "react";
|
||||
import { KriPieChart } from "@/components/chart";
|
||||
import { useProjectSummaryQuery } from "@/query/project";
|
||||
@@ -21,7 +24,8 @@ export function ProjectOverview() {
|
||||
const { auth } = useAuth();
|
||||
const summary = useProjectSummaryQuery();
|
||||
const fontReady = useChartFontReady(labels.join("") + "0123456789");
|
||||
const { hydrated, select, clear } = useSelectedProject();
|
||||
const { hydrated, clear } = useSelectedProject();
|
||||
const { navigate, pending } = useProjectNavigation();
|
||||
useVisitLog("/");
|
||||
// Legacy Main.js resets the selected project whenever the overview opens.
|
||||
useEffect(() => {
|
||||
@@ -47,8 +51,14 @@ export function ProjectOverview() {
|
||||
className="relative h-[420px] rounded-[15px] border border-kart-line bg-white"
|
||||
>
|
||||
<Link
|
||||
href="/Report/Current"
|
||||
onClick={() => select(project)}
|
||||
href={projectPageUrl("/Report/Current", project) as Route}
|
||||
prefetch={false}
|
||||
aria-disabled={pending}
|
||||
onClick={(event) => {
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||||
event.preventDefault();
|
||||
if (!pending) void navigate(project, "/Report/Current");
|
||||
}}
|
||||
title={project.title ?? project.pkey}
|
||||
className="-m-px flex h-[55px] items-center justify-between rounded-[15px] border border-kart-line bg-kart-soft p-4"
|
||||
>
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { KriSingleSelect } from "@/components/common/KriAutoComplete";
|
||||
import { useProjectListQuery } from "@/query/project";
|
||||
import { useProjectNavigation } from "@/hooks/useProjectNavigation";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { projectKey } from "@/types/kart";
|
||||
import { projectPagePath } from "@/lib/report-navigation";
|
||||
import { QueryState } from "./QueryState";
|
||||
|
||||
function getProjectPlaceholder(checkingAccess: boolean, loading: boolean, projectCount: number): string {
|
||||
if (checkingAccess) return "접근 권한을 확인하는 중...";
|
||||
if (loading) return "목록을 불러오는 중...";
|
||||
if (projectCount > 0) return "프로젝트 선택";
|
||||
return "조회 가능한 프로젝트가 없습니다.";
|
||||
}
|
||||
|
||||
/** Legacy ProjectSelect: search dropdown that always reads "프로젝트 선택". */
|
||||
export function ProjectSelector() {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const { project: selected, select } = useSelectedProject();
|
||||
const { project: selected } = useSelectedProject();
|
||||
const { navigate, pending } = useProjectNavigation();
|
||||
const projects = useProjectListQuery();
|
||||
if (projects.isError)
|
||||
return (
|
||||
@@ -35,16 +43,9 @@ export function ProjectSelector() {
|
||||
);
|
||||
if (!project) return;
|
||||
// Same page for the new project (legacy keeps the current menu), progress from home.
|
||||
select(project);
|
||||
router.push(projectPagePath(pathname));
|
||||
void navigate(project, projectPagePath(pathname));
|
||||
}}
|
||||
placeholder={
|
||||
projects.isPending
|
||||
? "목록을 불러오는 중..."
|
||||
: projects.data?.length
|
||||
? "프로젝트 선택"
|
||||
: "조회 가능한 프로젝트가 없습니다."
|
||||
}
|
||||
placeholder={getProjectPlaceholder(pending, projects.isPending, projects.data?.length ?? 0)}
|
||||
widthClassName="w-full"
|
||||
className="h-8 min-h-8 rounded-[39px] border-[#d0d0d0] bg-kart-soft px-[22px] py-0 text-sm shadow-none"
|
||||
spanClassName="text-sm [&_span]:text-kart-text"
|
||||
@@ -57,7 +58,7 @@ export function ProjectSelector() {
|
||||
optionTooltipClassName="opacity-65"
|
||||
preventDeselect
|
||||
hideOptionCheck
|
||||
disabled={projects.isPending}
|
||||
disabled={projects.isPending || pending}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback } from "react";
|
||||
import { useAtom, useAtomValue } from "jotai";
|
||||
import { atom, useAtom, useAtomValue } from "jotai";
|
||||
import type { SetStateAction } from "react";
|
||||
import type { LoginUser } from "@kri/common";
|
||||
import { isRecord, isLoginUser } from "@/types/kart";
|
||||
import type { AuthState as CommonAuthState } from "@kri/common/hooks";
|
||||
@@ -10,25 +11,27 @@ import {
|
||||
getLocalStorage,
|
||||
removeLocalStorage,
|
||||
setLocalStorage,
|
||||
getSessionStorage,
|
||||
setSessionStorage,
|
||||
removeSessionStorage,
|
||||
} from "@/store/storage/secure-storage";
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import { isExternalSession, isExternalUser, type ShareLink } from "@/types/share";
|
||||
import { isExternalUser, type ShareLink } from "@/types/share";
|
||||
import { isExternalAuth, type ExternalAuth } from "@/lib/external-auth";
|
||||
|
||||
export type AuthState = CommonAuthState<LoginUser> & { external?: ShareLink };
|
||||
export type AuthState = CommonAuthState<LoginUser> & { external?: ShareLink; accessToken?: string; mode?: "external" };
|
||||
const initialAuthState: AuthState = { user: null };
|
||||
|
||||
const isPersistedAuthState = (value: unknown): value is AuthState =>
|
||||
isRecord(value) && isLoginUser(value.user) &&
|
||||
(isExternalUser(value.user)
|
||||
? isExternalSession({ user: value.user, link: value.external })
|
||||
: value.external === undefined);
|
||||
isRecord(value) && isLoginUser(value.user) && !isExternalUser(value.user) &&
|
||||
value.accessToken === undefined && value.external === undefined;
|
||||
|
||||
/*
|
||||
* atom은 서버·클라이언트 최초 렌더 모두 initialAuthState로 시작한다.
|
||||
* 저장소 값은 onMount(마운트 이후 시점)에만 반영되므로
|
||||
* 서버 HTML과 클라이언트 최초 렌더가 항상 일치해 하이드레이션 오류가 발생하지 않는다.
|
||||
*/
|
||||
export const authStateAtom = createPersistentAtom<AuthState>(
|
||||
const normalAuthStateAtom = createPersistentAtom<AuthState>(
|
||||
StorageKeys.AuthState,
|
||||
initialAuthState,
|
||||
{
|
||||
@@ -43,6 +46,48 @@ export const authStateAtom = createPersistentAtom<AuthState>(
|
||||
},
|
||||
);
|
||||
|
||||
const sessionStorage = { get: getSessionStorage, set: setSessionStorage, remove: removeSessionStorage };
|
||||
const authModeAtom = createPersistentAtom<"normal" | "external">(StorageKeys.AuthMode, "normal", {
|
||||
storage: sessionStorage,
|
||||
validate: (value): value is "normal" | "external" => value === "normal" || value === "external",
|
||||
shouldRemove: (value) => value === "normal",
|
||||
});
|
||||
const externalAuthStateAtom = createPersistentAtom<ExternalAuth | null>(StorageKeys.ExternalAuth, null, {
|
||||
storage: sessionStorage,
|
||||
validate: (value): value is ExternalAuth | null => value === null || isExternalAuth(value),
|
||||
});
|
||||
const emptyExternalAuth: ExternalAuth = { mode: "external", user: null };
|
||||
|
||||
export const authStateAtom = Object.assign(atom(
|
||||
(get): AuthState => {
|
||||
const normal = get(normalAuthStateAtom);
|
||||
const mode = get(authModeAtom);
|
||||
const external = get(externalAuthStateAtom);
|
||||
if (mode === "external") return external ?? emptyExternalAuth;
|
||||
return normal;
|
||||
},
|
||||
(get, set, action: SetStateAction<AuthState>) => {
|
||||
const previous = get(authStateAtom);
|
||||
const next = typeof action === "function" ? action(previous) : action;
|
||||
if (next.mode === "external" || isExternalUser(next.user)) {
|
||||
set(authModeAtom, "external");
|
||||
set(externalAuthStateAtom, { ...next, mode: "external" });
|
||||
return;
|
||||
}
|
||||
if (!next.user && previous.mode === "external") {
|
||||
set(authModeAtom, "external");
|
||||
set(externalAuthStateAtom, null);
|
||||
return;
|
||||
}
|
||||
set(authModeAtom, "normal");
|
||||
set(externalAuthStateAtom, null);
|
||||
set(normalAuthStateAtom, { user: next.user });
|
||||
},
|
||||
), {
|
||||
hydratedAtom: atom((get) => get(normalAuthStateAtom.hydratedAtom) &&
|
||||
get(authModeAtom.hydratedAtom) && get(externalAuthStateAtom.hydratedAtom)),
|
||||
});
|
||||
|
||||
export function useAuth() {
|
||||
const [auth, setAuth] = useAtom(authStateAtom);
|
||||
const hydrated = useAtomValue(authStateAtom.hydratedAtom);
|
||||
|
||||
54
src/hooks/useProjectNavigation.ts
Normal file
54
src/hooks/useProjectNavigation.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { atom, useAtomValue, useStore } from "jotai";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { Route } from "next";
|
||||
import { toast } from "sonner";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { authStateAtom } from "@/hooks/useAuth";
|
||||
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
||||
import { cancelPreviousProjectQueries, checkProjectAccess } from "@/query/project";
|
||||
import { announceProjectAccess, projectAccessMessage } from "@/lib/project-access";
|
||||
import { isExternalUser } from "@/types/share";
|
||||
import type { ProjectRef } from "@/types/kart";
|
||||
|
||||
// Both the overview and header share one selection lock in this Jotai provider.
|
||||
export const projectSelectionAtom = atom({ id: 0, pending: false });
|
||||
|
||||
export function useProjectNavigation() {
|
||||
const store = useStore();
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const selection = useAtomValue(projectSelectionAtom);
|
||||
const request = useRef<number | null>(null);
|
||||
useEffect(() => () => {
|
||||
if (request.current === store.get(projectSelectionAtom).id)
|
||||
store.set(projectSelectionAtom, (value) => ({ id: value.id + 1, pending: false }));
|
||||
}, [store]);
|
||||
|
||||
const navigate = useCallback(async (project: ProjectRef, path: Route) => {
|
||||
const auth = store.get(authStateAtom);
|
||||
if (!auth.user || isExternalUser(auth.user) || store.get(projectSelectionAtom).pending) return;
|
||||
const id = store.get(projectSelectionAtom).id + 1;
|
||||
request.current = id;
|
||||
store.set(projectSelectionAtom, { id, pending: true });
|
||||
const current = () => store.get(projectSelectionAtom).id === id && store.get(authStateAtom) === auth;
|
||||
try {
|
||||
await checkProjectAccess(project);
|
||||
if (!current()) return;
|
||||
await cancelPreviousProjectQueries(queryClient, auth.user, store.get(selectedProjectAtom), project);
|
||||
if (!current()) return;
|
||||
store.set(selectedProjectAtom, { userId: auth.user.userId, project: { projectType: project.projectType, pkey: project.pkey } });
|
||||
announceProjectAccess({ project, allowed: true });
|
||||
router.push(path);
|
||||
} catch (error: unknown) {
|
||||
if (current()) toast.error(projectAccessMessage(error));
|
||||
} finally {
|
||||
if (store.get(projectSelectionAtom).id === id)
|
||||
store.set(projectSelectionAtom, { id, pending: false });
|
||||
}
|
||||
}, [store, router, queryClient]);
|
||||
|
||||
return { navigate, pending: selection.pending };
|
||||
}
|
||||
@@ -6,9 +6,9 @@ import { createPersistentAtom } from "@kri/common/jotai";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { isExternalUser } from "@/types/share";
|
||||
import {
|
||||
getLocalStorage,
|
||||
removeLocalStorage,
|
||||
setLocalStorage,
|
||||
getSessionStorage,
|
||||
removeSessionStorage,
|
||||
setSessionStorage,
|
||||
} from "@/store/storage/secure-storage";
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import { isProjectRef, isRecord, type ProjectRef } from "@/types/kart";
|
||||
@@ -23,19 +23,15 @@ const isSelectedProject = (value: unknown): value is SelectedProject =>
|
||||
value.userId !== "" &&
|
||||
isProjectRef(value.project));
|
||||
|
||||
/**
|
||||
* Legacy KART kept the selected project in ptokenState (recoil-persist, localStorage) instead of
|
||||
* the URL. Like authStateAtom, the stored value is applied after mount, so server and first
|
||||
* client renders agree.
|
||||
*/
|
||||
/** Each tab owns its selection. */
|
||||
export const selectedProjectAtom = createPersistentAtom<SelectedProject>(
|
||||
StorageKeys.SelectedProject,
|
||||
null,
|
||||
{
|
||||
storage: {
|
||||
get: getLocalStorage,
|
||||
set: setLocalStorage,
|
||||
remove: removeLocalStorage,
|
||||
get: getSessionStorage,
|
||||
set: setSessionStorage,
|
||||
remove: removeSessionStorage,
|
||||
},
|
||||
validate: isSelectedProject,
|
||||
shouldRemove: (value) => value === null,
|
||||
@@ -44,8 +40,8 @@ export const selectedProjectAtom = createPersistentAtom<SelectedProject>(
|
||||
);
|
||||
|
||||
/**
|
||||
* Current project for the signed-in user. Address parameters (old `?projectType=&pkey=` links)
|
||||
* never select a project; links are shared only through generated Page Copy / URL Copy links.
|
||||
* Current project for the signed-in user. Incoming address parameters are applied only
|
||||
* after ProjectEntry verifies normal-user access; External scope comes from the link.
|
||||
*/
|
||||
export function useSelectedProject() {
|
||||
const { auth, hydrated: authHydrated } = useAuth();
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { reportUrl } from "@/types/share";
|
||||
import { readExternalAuth } from "@/lib/external-auth";
|
||||
|
||||
// Set false to disable only cross-tab notifications and their listener.
|
||||
const AUTH_CHANGE_SYNC_ENABLED = true;
|
||||
const CHANNEL = "kart:auth-change";
|
||||
const CHANNEL = "kart:internal-auth-change";
|
||||
let channel: BroadcastChannel | undefined;
|
||||
|
||||
function authChannel() {
|
||||
@@ -15,7 +15,7 @@ function authChannel() {
|
||||
}
|
||||
}
|
||||
|
||||
export function notifyAuthChange(path: string) {
|
||||
export function notifyAuthChange(path: "/" | "/login") {
|
||||
authChannel()?.postMessage(path);
|
||||
}
|
||||
|
||||
@@ -23,10 +23,11 @@ export function subscribeToAuthChanges() {
|
||||
const listener = authChannel();
|
||||
if (!listener) return;
|
||||
listener.onmessage = (event: MessageEvent<unknown>) => {
|
||||
const path = event.data === "/" || event.data === "/login"
|
||||
? event.data : reportUrl(event.data);
|
||||
// A normal-login change must not navigate an independently authenticated link tab.
|
||||
if (readExternalAuth()) return;
|
||||
if (event.data !== "/" && event.data !== "/login") return;
|
||||
// A full navigation discards this tab's cache/state without clearing the new cookie.
|
||||
if (path) window.location.replace(path);
|
||||
window.location.replace(event.data);
|
||||
};
|
||||
return () => {
|
||||
listener.close();
|
||||
|
||||
33
src/lib/auth-cookie.ts
Normal file
33
src/lib/auth-cookie.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import "server-only";
|
||||
import { NextResponse } from "next/server";
|
||||
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
|
||||
import { serverEnv } from "@/lib/env.server";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
|
||||
/** Issue/renew the normal-login cookie, or expire it when the token is empty. */
|
||||
export function setAuthCookie(response: NextResponse, token: string): void {
|
||||
const production = serverEnv.ENV === "prod";
|
||||
const domain = serverEnv.AUTH_COOKIE_DOMAIN;
|
||||
|
||||
const options = {
|
||||
httpOnly: true,
|
||||
secure: production,
|
||||
sameSite: "lax" as const,
|
||||
path: "/",
|
||||
};
|
||||
// Serialize each cookie separately: ResponseCookies indexes cookies by name,
|
||||
// so setting the shared and host-only variants on one instance loses a header.
|
||||
const append = (value: string, cookieDomain: string | undefined, maxAge: number) => {
|
||||
const cookieResponse = new NextResponse(null);
|
||||
cookieResponse.cookies.set(CookieKeys.AuthToken, value, {
|
||||
...options,
|
||||
...(cookieDomain ? { domain: cookieDomain } : {}),
|
||||
maxAge,
|
||||
});
|
||||
for (const header of cookieResponse.headers.getSetCookie())
|
||||
response.headers.append("Set-Cookie", header);
|
||||
};
|
||||
|
||||
if (domain) append("", undefined, 0);
|
||||
append(token, domain, token ? AUTH_COOKIE_MAX_AGE : 0);
|
||||
}
|
||||
@@ -4,4 +4,8 @@ import { createEnv, env } from "@kri/common/config";
|
||||
export const serverEnv = createEnv({
|
||||
ENV: env.required("ENV", process.env.ENV),
|
||||
API_SERVER: env.required("API_SERVER", process.env.API_SERVER),
|
||||
AUTH_COOKIE_DOMAIN: env.optional(
|
||||
"AUTH_COOKIE_DOMAIN",
|
||||
process.env.AUTH_COOKIE_DOMAIN,
|
||||
),
|
||||
});
|
||||
|
||||
29
src/lib/external-auth.ts
Normal file
29
src/lib/external-auth.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import type { LoginUser } from "@kri/common";
|
||||
import { getSessionStorage } from "@/store/storage/secure-storage";
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import { isRecord } from "@/types/kart";
|
||||
import { isExternalSession, type ShareLink } from "@/types/share";
|
||||
|
||||
export type ExternalAuth = {
|
||||
mode: "external";
|
||||
user: LoginUser | null;
|
||||
external?: ShareLink;
|
||||
accessToken?: string;
|
||||
};
|
||||
|
||||
export function isExternalAuth(value: unknown): value is ExternalAuth {
|
||||
if (!isRecord(value) || value.mode !== "external") return false;
|
||||
if (value.user === null) return value.external === undefined && value.accessToken === undefined;
|
||||
return isExternalSession({ user: value.user, link: value.external }) &&
|
||||
(value.accessToken === undefined || typeof value.accessToken === "string");
|
||||
}
|
||||
|
||||
/** The mode survives missing/invalid token data so requests never fall back to the normal cookie. */
|
||||
export function readExternalAuth(): ExternalAuth | null {
|
||||
if (getSessionStorage(StorageKeys.AuthMode) !== "external") return null;
|
||||
const value = getSessionStorage(StorageKeys.ExternalAuth);
|
||||
if (isExternalAuth(value)) return value;
|
||||
return { mode: "external", user: null };
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { apiError, createHttpClient, redirectToLogout } from "@kri/common/http";
|
||||
import { apiError, createHttpClient, HttpError, redirectToLogout } from "@kri/common/http";
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
import { announceProjectAccess, projectFromRequest } from "@/lib/project-access";
|
||||
import { readExternalAuth } from "@/lib/external-auth";
|
||||
|
||||
const resolveBaseUrl = () =>
|
||||
typeof window === "undefined"
|
||||
@@ -7,8 +9,31 @@ const resolveBaseUrl = () =>
|
||||
: new URL(clientEnv.API_BASE, window.location.origin).toString();
|
||||
|
||||
export const nextApi = createHttpClient(resolveBaseUrl(), {
|
||||
getToken: () => {
|
||||
const external = readExternalAuth();
|
||||
if (!external) return null;
|
||||
if (!external.accessToken) {
|
||||
redirectToLogout();
|
||||
throw new HttpError(401, { message: "공유 링크 인증이 필요합니다." }, "");
|
||||
}
|
||||
return external.accessToken;
|
||||
},
|
||||
onForbidden: (error) => {
|
||||
if (apiError(error).code === "EXTERNAL_SCOPE_DENIED") redirectToLogout();
|
||||
const info = apiError(error);
|
||||
if (readExternalAuth() || info.code === "EXTERNAL_SCOPE_DENIED" || info.code === "PROJECT_IDENTITY_REQUIRED") {
|
||||
redirectToLogout();
|
||||
return;
|
||||
}
|
||||
const project = projectFromRequest(error.url);
|
||||
if (info.code === "PROJECT_ACCESS_DENIED" && project && !new URL(error.url).pathname.endsWith("/access"))
|
||||
announceProjectAccess({ project, allowed: false, message: info.message });
|
||||
},
|
||||
onResponseError: false,
|
||||
});
|
||||
|
||||
// Login/logout BFF operations must also work before an External JWT is available.
|
||||
export const authApi = createHttpClient(resolveBaseUrl(), {
|
||||
onUnauthorized: false,
|
||||
onForbidden: false,
|
||||
onResponseError: false,
|
||||
});
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import { createHttpClient } from "@kri/common/http";
|
||||
import { serverEnv } from "@/lib/env.server";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
|
||||
export async function getServerAccessToken(): Promise<string | null> {
|
||||
const authorization = (await headers()).get("authorization");
|
||||
// Explicit credentials take precedence even when malformed; never use the normal
|
||||
// cookie as a fallback for an External request. The backend verifies the JWT.
|
||||
if (authorization !== null) return /^Bearer ([^\s]+)$/i.exec(authorization)?.[1] ?? null;
|
||||
return (await cookies()).get(CookieKeys.AuthToken)?.value ?? null;
|
||||
}
|
||||
|
||||
export async function createServerApi(authenticated = true) {
|
||||
const cookieStore = await cookies();
|
||||
const accessToken = authenticated ? cookieStore.get(CookieKeys.AuthToken)?.value ?? null : null;
|
||||
let accessToken: string | null = null;
|
||||
if (authenticated) accessToken = await getServerAccessToken();
|
||||
return createHttpClient(serverEnv.API_SERVER, {
|
||||
getToken: () => accessToken,
|
||||
defaultHeaders: { "content-type": "application/json" },
|
||||
|
||||
47
src/lib/project-access.ts
Normal file
47
src/lib/project-access.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { apiError } from "@kri/common/http";
|
||||
import { isProjectRef, type ProjectRef } from "@/types/kart";
|
||||
|
||||
export const PROJECT_ACCESS_EVENT = "kart:project-access";
|
||||
export type ProjectAccessEvent = {
|
||||
project: ProjectRef;
|
||||
allowed: boolean;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
export function announceProjectAccess(detail: ProjectAccessEvent) {
|
||||
if (typeof window !== "undefined")
|
||||
window.dispatchEvent(new CustomEvent(PROJECT_ACCESS_EVENT, { detail }));
|
||||
}
|
||||
|
||||
/** Match the project in a BFF request, not whichever project is selected later. */
|
||||
export function projectFromRequest(url: string): ProjectRef | null {
|
||||
try {
|
||||
const path = new URL(url, "https://kart.invalid").pathname;
|
||||
const match = path.match(/\/(?:project|quota|derived|bookmark|export|import|share)\/([01])\/([^/]+)(?:\/|$)/);
|
||||
if (!match) return null;
|
||||
const project = { projectType: Number(match[1]), pkey: decodeURIComponent(match[2]) };
|
||||
return isProjectRef(project) ? project : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function projectAccessMessage(error: unknown): string {
|
||||
const info = apiError(error, { fallbackMessage: "프로젝트 접근 권한을 확인하지 못했습니다. 다시 시도해 주세요." });
|
||||
return info.code === "PROJECT_ACCESS_DENIED"
|
||||
? "프로젝트에 접근할 권한이 없습니다."
|
||||
: info.message;
|
||||
}
|
||||
|
||||
export function projectFromSearch(search: URLSearchParams): ProjectRef | null {
|
||||
const type = search.get("projectType");
|
||||
if (search.getAll("projectType").length !== 1 || search.getAll("pkey").length !== 1 ||
|
||||
(type !== "0" && type !== "1")) return null;
|
||||
const project = { projectType: Number(type), pkey: search.get("pkey") };
|
||||
return isProjectRef(project) ? project : null;
|
||||
}
|
||||
|
||||
export function projectPageUrl(pathname: string, project: ProjectRef): string {
|
||||
const search = new URLSearchParams({ projectType: String(project.projectType), pkey: project.pkey });
|
||||
return pathname + "?" + search;
|
||||
}
|
||||
@@ -2,6 +2,8 @@ const progress = new Set(["day", "type", "loi", "screen"]);
|
||||
/** Browser inputs select only these implemented read operations, never an arbitrary upstream URL. */
|
||||
export function isProjectReadPath(slug: string[]): boolean {
|
||||
if (slug.length === 1) return slug[0] === "list" || slug[0] === "summary";
|
||||
if (slug.length === 3 && slug[2] === "access")
|
||||
return isProjectReadPath([slug[0], slug[1], "question", "list"]);
|
||||
return (
|
||||
slug.length === 4 &&
|
||||
(slug[0] === "0" || slug[0] === "1") &&
|
||||
|
||||
@@ -12,8 +12,8 @@ export function isProjectPage(path: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* Project pages carry no project in the address (legacy KART kept it in client state); the
|
||||
* selected project lives in useSelectedProject. Other paths open the progress page.
|
||||
* ProjectEntry verifies and consumes incoming project parameters. Subsequent navigation
|
||||
* uses the tab's selected project; other paths open the progress page.
|
||||
*/
|
||||
export function projectPagePath(path: string): Route {
|
||||
return (isProjectPage(path) ? path : "/Report/Current") as Route;
|
||||
|
||||
@@ -5,15 +5,16 @@ import { useMutation } from "@tanstack/react-query";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useResetSession } from "@/hooks/useResetSession";
|
||||
import { notifyAuthChange } from "@/lib/auth-change";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { authApi } from "@/lib/http-client";
|
||||
import { isLoginUser } from "@/types/kart";
|
||||
import { readExternalAuth } from "@/lib/external-auth";
|
||||
|
||||
export function useLoginMutation() {
|
||||
const { setFromLoginResponse } = useAuth();
|
||||
const resetSession = useResetSession();
|
||||
return useMutation({
|
||||
mutationFn: async (request: LoginRequest) => {
|
||||
const user = await nextApi.post<unknown>("/login", request, {
|
||||
const user = await authApi.post<unknown>("/login", request, {
|
||||
skipUnauthorizedHandler: true,
|
||||
skipForbiddenHandler: true,
|
||||
skipResponseErrorHandler: true,
|
||||
@@ -32,17 +33,21 @@ export function useLoginMutation() {
|
||||
export function useLogoutMutation() {
|
||||
const { logout } = useAuth();
|
||||
const resetSession = useResetSession();
|
||||
const externalSession = () => !!readExternalAuth();
|
||||
return useMutation({
|
||||
mutationFn: () =>
|
||||
nextApi.post("/logout", null, {
|
||||
onMutate: () => ({ external: externalSession() }),
|
||||
mutationFn: async () => {
|
||||
if (externalSession()) return;
|
||||
await authApi.post("/logout", null, {
|
||||
skipUnauthorizedHandler: true,
|
||||
skipForbiddenHandler: true,
|
||||
skipResponseErrorHandler: true,
|
||||
}),
|
||||
onSettled: async () => {
|
||||
});
|
||||
},
|
||||
onSettled: async (_data, _error, _variables, context) => {
|
||||
await resetSession();
|
||||
logout();
|
||||
notifyAuthChange("/login");
|
||||
if (!context?.external) notifyAuthChange("/login");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useQuery, type QueryClient } from "@tanstack/react-query";
|
||||
import type { LoginUser } from "@kri/common";
|
||||
import type { SelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { HttpError } from "@kri/common/http";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { isExternalUser } from "@/types/share";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { queryKeys } from "@/query/key/keys";
|
||||
import {
|
||||
isRecord,
|
||||
isProject,
|
||||
isProjectSummary,
|
||||
isProgressDay,
|
||||
@@ -18,6 +21,37 @@ import {
|
||||
type DateRange,
|
||||
} from "@/types/kart";
|
||||
|
||||
export async function cancelPreviousProjectQueries(
|
||||
queryClient: QueryClient,
|
||||
user: LoginUser,
|
||||
selected: SelectedProject,
|
||||
next: ProjectRef,
|
||||
): Promise<void> {
|
||||
if (!selected || selected.userId !== user.userId) return;
|
||||
const previous = selected.project;
|
||||
if (previous.projectType === next.projectType && previous.pkey === next.pkey) return;
|
||||
|
||||
await queryClient.cancelQueries({
|
||||
predicate: ({ queryKey }) => {
|
||||
if (queryKey[0] !== "kart" || queryKey[1] !== user.userId ||
|
||||
queryKey[2] !== user.userRole || queryKey[3] !== user.userTeam) return false;
|
||||
// Project-scoped keys put type/pkey at positions 4/5 or 5/6.
|
||||
return (queryKey[4] === previous.projectType && queryKey[5] === previous.pkey) ||
|
||||
(queryKey[5] === previous.projectType && queryKey[6] === previous.pkey);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Always check the server; a cached permission is not an authorization decision. */
|
||||
export async function checkProjectAccess(project: ProjectRef): Promise<void> {
|
||||
const result = await nextApi.get<unknown>(
|
||||
"/project/" + project.projectType + "/" + encodeURIComponent(project.pkey) + "/access",
|
||||
{ cache: "no-store" },
|
||||
);
|
||||
if (!isRecord(result) || result.allowed !== true)
|
||||
throw new Error("프로젝트 접근 권한 응답을 확인해 주세요.");
|
||||
}
|
||||
|
||||
export function useProjectListQuery() {
|
||||
const { auth, hydrated } = useAuth();
|
||||
const user = auth.user;
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
export const StorageKeys = {
|
||||
AuthState: "kri:authState",
|
||||
AuthMode: "kart:authMode",
|
||||
ExternalAuth: "kart:externalAuth",
|
||||
SelectedProject: "kart:selectedProject",
|
||||
} as const;
|
||||
|
||||
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
|
||||
export const StorageType: Record<StorageKey, "local" | "session"> = {
|
||||
[StorageKeys.AuthState]: "local",
|
||||
[StorageKeys.SelectedProject]: "local",
|
||||
[StorageKeys.AuthMode]: "session",
|
||||
[StorageKeys.ExternalAuth]: "session",
|
||||
[StorageKeys.SelectedProject]: "session",
|
||||
};
|
||||
|
||||
@@ -15,6 +15,12 @@ export type ShareLink = ProjectRef & {
|
||||
pageOnly: boolean;
|
||||
};
|
||||
export type ExternalSession = { user: LoginUser; link: ShareLink };
|
||||
export type ExternalLoginResponse = ExternalSession & { accessToken: string };
|
||||
|
||||
export function isExternalLoginResponse(value: unknown): value is ExternalLoginResponse {
|
||||
return isRecord(value) && typeof value.accessToken === "string" &&
|
||||
value.accessToken.length > 0 && isExternalSession(value);
|
||||
}
|
||||
|
||||
export function isExternalUser(user: LoginUser | null | undefined): boolean {
|
||||
return !!user && (user.userRole === EXTERNAL_URL_COPY_ROLE ||
|
||||
|
||||
Reference in New Issue
Block a user