86 lines
3.7 KiB
TypeScript
86 lines
3.7 KiB
TypeScript
"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;
|
|
}
|
|
},
|
|
});
|
|
}
|