Files
KART-FRONT-NEXT/src/lib/auth-change.ts

37 lines
1.2 KiB
TypeScript

import { readExternalAuth } from "@/lib/external-auth";
// Set false to disable only cross-tab notifications and their listener.
const AUTH_CHANGE_SYNC_ENABLED = true;
const CHANNEL = "kart:internal-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: "/" | "/login") {
authChannel()?.postMessage(path);
}
export function subscribeToAuthChanges() {
const listener = authChannel();
if (!listener) return;
listener.onmessage = (event: MessageEvent<unknown>) => {
// A normal-login change must not navigate an independently authenticated link tab.
if (readExternalAuth()) return;
if (event.data !== "/" && event.data !== "/login") return;
// A full navigation discards this tab's cache/state without clearing the new cookie.
window.location.replace(event.data);
};
return () => {
listener.close();
channel = undefined;
};
}