261030_01_FIX: 인증 전환 시 상태 정리 및 탭 동기화, 외부 링크 권한 오류 시 로그아웃 처리 #4
@@ -4,9 +4,10 @@ import { useEffect, useRef, useState } from "react";
|
|||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import type { Route } from "next";
|
import type { Route } from "next";
|
||||||
import { useSetAtom } from "jotai";
|
import { useSetAtom } from "jotai";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { apiError } from "@kri/common/http";
|
import { apiError } from "@kri/common/http";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
|
import { useResetSession } from "@/hooks/useResetSession";
|
||||||
|
import { notifyAuthChange } from "@/lib/auth-change";
|
||||||
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
||||||
import { nextApi } from "@/lib/http-client";
|
import { nextApi } from "@/lib/http-client";
|
||||||
import { isExternalSession, reportUrl, type ExternalSession } from "@/types/share";
|
import { isExternalSession, reportUrl, type ExternalSession } from "@/types/share";
|
||||||
@@ -16,7 +17,7 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { hydrated, setAuth, logout } = useAuth();
|
const { hydrated, setAuth, logout } = useAuth();
|
||||||
const setProject = useSetAtom(selectedProjectAtom);
|
const setProject = useSetAtom(selectedProjectAtom);
|
||||||
const queryClient = useQueryClient();
|
const resetSession = useResetSession();
|
||||||
const pending = useRef<Promise<ExternalSession> | null>(null);
|
const pending = useRef<Promise<ExternalSession> | null>(null);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -24,9 +25,7 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
|||||||
let active = true;
|
let active = true;
|
||||||
const enter = async () => {
|
const enter = async () => {
|
||||||
logout();
|
logout();
|
||||||
setProject(null);
|
await resetSession();
|
||||||
await queryClient.cancelQueries();
|
|
||||||
queryClient.clear();
|
|
||||||
const result = await nextApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
|
const result = await nextApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
|
||||||
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
||||||
});
|
});
|
||||||
@@ -39,12 +38,16 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
|||||||
if (!active) return;
|
if (!active) return;
|
||||||
setProject({ userId: result.user.userId, project: { projectType: result.link.projectType, pkey: result.link.pkey } });
|
setProject({ userId: result.user.userId, project: { projectType: result.link.projectType, pkey: result.link.pkey } });
|
||||||
setAuth({ user: result.user, external: result.link });
|
setAuth({ user: result.user, external: result.link });
|
||||||
|
notifyAuthChange(result.link.realUrl);
|
||||||
router.replace(reportUrl(result.link.realUrl) as Route);
|
router.replace(reportUrl(result.link.realUrl) as Route);
|
||||||
}).catch((reason: unknown) => {
|
}).catch((reason: unknown) => {
|
||||||
if (active) setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
|
if (active) {
|
||||||
|
notifyAuthChange("/login");
|
||||||
|
setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
return () => { active = false; };
|
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>;
|
if (error) return <p role="alert" className="p-8 text-center text-sm">{error}</p>;
|
||||||
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
|
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
import { Provider as JotaiProvider } from "jotai";
|
import { Provider as JotaiProvider } from "jotai";
|
||||||
import { QueryProvider } from "@kri/common/query";
|
import { QueryProvider } from "@kri/common/query";
|
||||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
import { QueryLoadingSync } from "./QueryLoadingSync";
|
import { QueryLoadingSync } from "./QueryLoadingSync";
|
||||||
|
import { subscribeToAuthChanges } from "@/lib/auth-change";
|
||||||
|
|
||||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
useEffect(() => subscribeToAuthChanges(), []);
|
||||||
return (
|
return (
|
||||||
<JotaiProvider>
|
<JotaiProvider>
|
||||||
<QueryProvider>
|
<QueryProvider>
|
||||||
|
|||||||
17
src/hooks/useResetSession.ts
Normal file
17
src/hooks/useResetSession.ts
Normal 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
35
src/lib/auth-change.ts
Normal 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;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { createHttpClient } from "@kri/common/http";
|
import { apiError, createHttpClient, redirectToLogout } from "@kri/common/http";
|
||||||
import { clientEnv } from "@/lib/env.client";
|
import { clientEnv } from "@/lib/env.client";
|
||||||
|
|
||||||
const resolveBaseUrl = () =>
|
const resolveBaseUrl = () =>
|
||||||
@@ -7,6 +7,8 @@ const resolveBaseUrl = () =>
|
|||||||
: new URL(clientEnv.API_BASE, window.location.origin).toString();
|
: new URL(clientEnv.API_BASE, window.location.origin).toString();
|
||||||
|
|
||||||
export const nextApi = createHttpClient(resolveBaseUrl(), {
|
export const nextApi = createHttpClient(resolveBaseUrl(), {
|
||||||
onForbidden: false,
|
onForbidden: (error) => {
|
||||||
|
if (apiError(error).code === "EXTERNAL_SCOPE_DENIED") redirectToLogout();
|
||||||
|
},
|
||||||
onResponseError: false,
|
onResponseError: false,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,17 +1,16 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { LoginRequest } from "@kri/common";
|
import type { LoginRequest } from "@kri/common";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation } from "@tanstack/react-query";
|
||||||
import { useSetAtom } from "jotai";
|
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
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 { nextApi } from "@/lib/http-client";
|
||||||
import { isLoginUser } from "@/types/kart";
|
import { isLoginUser } from "@/types/kart";
|
||||||
|
|
||||||
export function useLoginMutation() {
|
export function useLoginMutation() {
|
||||||
const { setFromLoginResponse } = useAuth();
|
const { setFromLoginResponse } = useAuth();
|
||||||
const setSelectedProject = useSetAtom(selectedProjectAtom);
|
const resetSession = useResetSession();
|
||||||
const queryClient = useQueryClient();
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (request: LoginRequest) => {
|
mutationFn: async (request: LoginRequest) => {
|
||||||
const user = await nextApi.post<unknown>("/login", request, {
|
const user = await nextApi.post<unknown>("/login", request, {
|
||||||
@@ -22,18 +21,17 @@ export function useLoginMutation() {
|
|||||||
if (!isLoginUser(user)) throw new Error("로그인 응답을 확인해 주세요.");
|
if (!isLoginUser(user)) throw new Error("로그인 응답을 확인해 주세요.");
|
||||||
return user;
|
return user;
|
||||||
},
|
},
|
||||||
onSuccess: (user) => {
|
onSuccess: async (user) => {
|
||||||
queryClient.clear();
|
|
||||||
// Legacy Login.js starts every session without a selected project.
|
// Legacy Login.js starts every session without a selected project.
|
||||||
setSelectedProject(null);
|
await resetSession();
|
||||||
setFromLoginResponse(user);
|
setFromLoginResponse(user);
|
||||||
|
notifyAuthChange("/");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
export function useLogoutMutation() {
|
export function useLogoutMutation() {
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const { logout } = useAuth();
|
const { logout } = useAuth();
|
||||||
const setSelectedProject = useSetAtom(selectedProjectAtom);
|
const resetSession = useResetSession();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: () =>
|
mutationFn: () =>
|
||||||
nextApi.post("/logout", null, {
|
nextApi.post("/logout", null, {
|
||||||
@@ -41,10 +39,10 @@ export function useLogoutMutation() {
|
|||||||
skipForbiddenHandler: true,
|
skipForbiddenHandler: true,
|
||||||
skipResponseErrorHandler: true,
|
skipResponseErrorHandler: true,
|
||||||
}),
|
}),
|
||||||
onSettled: () => {
|
onSettled: async () => {
|
||||||
|
await resetSession();
|
||||||
logout();
|
logout();
|
||||||
setSelectedProject(null);
|
notifyAuthChange("/login");
|
||||||
queryClient.clear();
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user