develop #71
@@ -1,3 +1,4 @@
|
||||
import { AuthSessionGate } from "@/components/app-shell/AuthSessionGate";
|
||||
import AppMainLayout from "@/components/app-shell/AppMainLayout";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
@@ -31,8 +32,8 @@ export default async function MainLayoutWrapper({
|
||||
}
|
||||
|
||||
return (
|
||||
<AppMainLayout initialFontSize={initialFontSize}>
|
||||
<AuthSessionGate><AppMainLayout initialFontSize={initialFontSize}>
|
||||
{children}
|
||||
</AppMainLayout>
|
||||
</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 { createContactApi } from "@/lib/http-server";
|
||||
import {isLoginUser} from "@/lib/auth-user";
|
||||
|
||||
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 createContactApi();
|
||||
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;
|
||||
}
|
||||
}
|
||||
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>}
|
||||
</>;
|
||||
}
|
||||
77
src/hooks/useAuthSession.ts
Normal file
77
src/hooks/useAuthSession.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
"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, selectedProjectHydratedAtom } from "@/store/jotai/project";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { isLoginUser } from "@/lib/auth-user";
|
||||
|
||||
const SESSION_QUERY_KEY = ["auth-session"] as const;
|
||||
|
||||
export function useAuthSession() {
|
||||
const store = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const router = useRouter();
|
||||
const { setAuth } = useAuth();
|
||||
useAtomValue(selectedProjectAtom);
|
||||
const projectHydrated = useAtomValue(selectedProjectHydratedAtom);
|
||||
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: 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 nextApi.get<unknown>("/auth/my-info", {
|
||||
cache: "no-store",
|
||||
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
||||
});
|
||||
signal.throwIfAborted();
|
||||
if (!isLoginUser(user)) throw new Error("Invalid user response");
|
||||
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 (changed || before?.userName !== user.userName) setAuth({ 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("/login");
|
||||
}
|
||||
throw reason;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
10
src/lib/auth-user.ts
Normal file
10
src/lib/auth-user.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import {LoginUser} from "@kri/common";
|
||||
|
||||
export function isLoginUser(value: unknown): value is LoginUser {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
return "userId" in value && typeof value.userId === "string" && value.userId.length > 0 &&
|
||||
"userName" in value && typeof value.userName === "string" &&
|
||||
"userCmpn" in value && typeof value.userCmpn === "string" &&
|
||||
"userTeam" in value && typeof value.userTeam === "string" &&
|
||||
"userRole" in value && typeof value.userRole === "number" && Number.isSafeInteger(value.userRole);
|
||||
}
|
||||
@@ -15,14 +15,14 @@ export const Security = createSecurity({
|
||||
}
|
||||
|
||||
const target = window as Window & {
|
||||
__kfpaCryptoConfigAlerted?: boolean;
|
||||
__kriContactCryptoConfigAlerted?: boolean;
|
||||
};
|
||||
|
||||
if (target.__kfpaCryptoConfigAlerted) {
|
||||
if (target.__kriContactCryptoConfigAlerted) {
|
||||
return;
|
||||
}
|
||||
|
||||
target.__kfpaCryptoConfigAlerted = true;
|
||||
target.__kriContactCryptoConfigAlerted = true;
|
||||
window.alert(message);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export const CookieKeys = {
|
||||
FontSize: "kri_fontSize",
|
||||
AuthToken: "kri_authToken",
|
||||
AuthToken: "kri_internal_authToken",
|
||||
// 필요하면 여기 계속 추가 (예: Theme: "kri_theme", ...)
|
||||
} as const;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user