identity.ts 1.5 KB
/**
 * 当前身份。没有登录体系:界面右上角切换「以谁的身份操作」,
 * 通过请求头 X-User-Id 带给后端 —— 审计、审批(四眼原则)、数据范围都按它算。
 *
 * 在这里给全局 fetch 打一层补丁,而不是逐个调用点传头:SSE、下载、老页面的请求都自动带上。
 */
const KEY = "onto.user";
const listeners = new Set<(id: string) => void>();

export function currentUserId(): string {
  try {
    return localStorage.getItem(KEY) || "admin";
  } catch {
    return "admin";
  }
}

export function setCurrentUserId(id: string) {
  try { localStorage.setItem(KEY, id); } catch { /* 隐私模式 */ }
  listeners.forEach((fn) => fn(id));
}

export function onUserChange(fn: (id: string) => void): () => void {
  listeners.add(fn);
  return () => listeners.delete(fn);
}

let installed = false;

export function installIdentityFetch() {
  if (installed) return;
  installed = true;
  const orig = window.fetch.bind(window);
  window.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
    const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
    const sameOrigin = url.startsWith("/") || url.startsWith(window.location.origin);
    if (!sameOrigin) return orig(input, init);
    const headers = new Headers(init?.headers || (input instanceof Request ? input.headers : undefined));
    if (!headers.has("X-User-Id")) headers.set("X-User-Id", currentUserId());
    return orig(input, { ...init, headers });
  };
}