54 lines
2.5 KiB
TypeScript
54 lines
2.5 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import type { Route } from "next";
|
|
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 { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
|
|
|
export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
|
const router = useRouter();
|
|
const { hydrated, setAuth, logout } = useAuth();
|
|
const setProject = useSetAtom(selectedProjectAtom);
|
|
const resetSession = useResetSession();
|
|
const pending = useRef<Promise<ExternalSession> | null>(null);
|
|
const [error, setError] = useState("");
|
|
useEffect(() => {
|
|
if (!hydrated) return;
|
|
let active = true;
|
|
const enter = async () => {
|
|
logout();
|
|
await resetSession();
|
|
const result = await nextApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
|
|
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
|
});
|
|
if (!isExternalSession(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
|
|
return result;
|
|
};
|
|
// Reuse the request during StrictMode effect replay; each entry records one landing.
|
|
pending.current ??= enter();
|
|
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);
|
|
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]);
|
|
if (error) return <p role="alert" className="p-8 text-center text-sm">{error}</p>;
|
|
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
|
|
}
|