261030_01_FIX: 인증 전환 시 상태 정리 및 탭 동기화, 외부 링크 권한 오류 시 로그아웃 처리 #4

Merged
gitadmin merged 1 commits from develop into master 2026-10-30 15:41:44 +09:00
6 changed files with 80 additions and 22 deletions
Showing only changes of commit 4bfa2af213 - Show all commits

View File

@@ -4,9 +4,10 @@ import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import type { Route } from "next";
import { useSetAtom } from "jotai";
import { useQueryClient } from "@tanstack/react-query";
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";
@@ -16,7 +17,7 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
const router = useRouter();
const { hydrated, setAuth, logout } = useAuth();
const setProject = useSetAtom(selectedProjectAtom);
const queryClient = useQueryClient();
const resetSession = useResetSession();
const pending = useRef<Promise<ExternalSession> | null>(null);
const [error, setError] = useState("");
useEffect(() => {
@@ -24,9 +25,7 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
let active = true;
const enter = async () => {
logout();
setProject(null);
await queryClient.cancelQueries();
queryClient.clear();
await resetSession();
const result = await nextApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
});
@@ -39,12 +38,16 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
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);
router.replace(reportUrl(result.link.realUrl) as Route);
}).catch((reason: unknown) => {
if (active) setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
if (active) {
notifyAuthChange("/login");
setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
}
});
return () => { active = false; };
}, [hydrated, logout, setAuth, setProject, queryClient, router, urlKey]);
}, [hydrated, logout, setAuth, setProject, resetSession, router, urlKey]);
if (error) return <p role="alert" className="p-8 text-center text-sm">{error}</p>;
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
}

View File

@@ -1,11 +1,14 @@
"use client";
import { useEffect } from "react";
import { Provider as JotaiProvider } from "jotai";
import { QueryProvider } from "@kri/common/query";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import { QueryLoadingSync } from "./QueryLoadingSync";
import { subscribeToAuthChanges } from "@/lib/auth-change";
export function AppProvider({ children }: { children: React.ReactNode }) {
useEffect(() => subscribeToAuthChanges(), []);
return (
<JotaiProvider>
<QueryProvider>

View File

@@ -0,0 +1,17 @@
"use client";
import { useCallback } from "react";
import { useSetAtom } from "jotai";
import { useQueryClient } from "@tanstack/react-query";
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
/** Clear cached queries and the selected project before applying a new identity. */
export function useResetSession() {
const queryClient = useQueryClient();
const setProject = useSetAtom(selectedProjectAtom);
return useCallback(async () => {
await queryClient.cancelQueries();
queryClient.clear();
setProject(null);
}, [queryClient, setProject]);
}

35
src/lib/auth-change.ts Normal file
View File

@@ -0,0 +1,35 @@
import { reportUrl } from "@/types/share";
// Set false to disable only cross-tab notifications and their listener.
const AUTH_CHANGE_SYNC_ENABLED = true;
const CHANNEL = "kart:auth-change";
let channel: BroadcastChannel | undefined;
function authChannel() {
if (!AUTH_CHANGE_SYNC_ENABLED || typeof BroadcastChannel === "undefined") return;
try {
return channel ??= new BroadcastChannel(CHANNEL);
} catch {
// Cross-tab sync is optional when the browser disallows messaging.
return undefined;
}
}
export function notifyAuthChange(path: string) {
authChannel()?.postMessage(path);
}
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 full navigation discards this tab's cache/state without clearing the new cookie.
if (path) window.location.replace(path);
};
return () => {
listener.close();
channel = undefined;
};
}

View File

@@ -1,4 +1,4 @@
import { createHttpClient } from "@kri/common/http";
import { apiError, createHttpClient, redirectToLogout } from "@kri/common/http";
import { clientEnv } from "@/lib/env.client";
const resolveBaseUrl = () =>
@@ -7,6 +7,8 @@ const resolveBaseUrl = () =>
: new URL(clientEnv.API_BASE, window.location.origin).toString();
export const nextApi = createHttpClient(resolveBaseUrl(), {
onForbidden: false,
onForbidden: (error) => {
if (apiError(error).code === "EXTERNAL_SCOPE_DENIED") redirectToLogout();
},
onResponseError: false,
});

View File

@@ -1,17 +1,16 @@
"use client";
import type { LoginRequest } from "@kri/common";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useSetAtom } from "jotai";
import { useMutation } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
import { useResetSession } from "@/hooks/useResetSession";
import { notifyAuthChange } from "@/lib/auth-change";
import { nextApi } from "@/lib/http-client";
import { isLoginUser } from "@/types/kart";
export function useLoginMutation() {
const { setFromLoginResponse } = useAuth();
const setSelectedProject = useSetAtom(selectedProjectAtom);
const queryClient = useQueryClient();
const resetSession = useResetSession();
return useMutation({
mutationFn: async (request: LoginRequest) => {
const user = await nextApi.post<unknown>("/login", request, {
@@ -22,18 +21,17 @@ export function useLoginMutation() {
if (!isLoginUser(user)) throw new Error("로그인 응답을 확인해 주세요.");
return user;
},
onSuccess: (user) => {
queryClient.clear();
onSuccess: async (user) => {
// Legacy Login.js starts every session without a selected project.
setSelectedProject(null);
await resetSession();
setFromLoginResponse(user);
notifyAuthChange("/");
},
});
}
export function useLogoutMutation() {
const queryClient = useQueryClient();
const { logout } = useAuth();
const setSelectedProject = useSetAtom(selectedProjectAtom);
const resetSession = useResetSession();
return useMutation({
mutationFn: () =>
nextApi.post("/logout", null, {
@@ -41,10 +39,10 @@ export function useLogoutMutation() {
skipForbiddenHandler: true,
skipResponseErrorHandler: true,
}),
onSettled: () => {
onSettled: async () => {
await resetSession();
logout();
setSelectedProject(null);
queryClient.clear();
notifyAuthChange("/login");
},
});
}