283 lines
8.9 KiB
TypeScript
283 lines
8.9 KiB
TypeScript
import {
|
|
createContext,
|
|
useContext,
|
|
useCallback,
|
|
useEffect,
|
|
useRef,
|
|
useState,
|
|
type ReactNode,
|
|
} from "react";
|
|
import { useQueryClient } from "@tanstack/react-query";
|
|
import { z } from "zod";
|
|
import {
|
|
apiRequest,
|
|
apiPdf,
|
|
ApiError,
|
|
getPrincipal,
|
|
login,
|
|
organizationSchema,
|
|
parse,
|
|
type Principal,
|
|
type Session,
|
|
} from "./api";
|
|
|
|
type Options = { method?: string; body?: unknown; signal?: AbortSignal };
|
|
const PlatformContext = createContext<{
|
|
organization: string;
|
|
setOrganization: (value: string) => void;
|
|
principal: Principal | null;
|
|
scope: string;
|
|
signIn: (email: string, password: string) => Promise<void>;
|
|
signOut: () => Promise<void>;
|
|
notice: string;
|
|
clearSession: (notice?: string) => void;
|
|
getIntent: (key: string) => unknown;
|
|
saveIntent: (key: string, value: unknown) => void;
|
|
clearIntent: (key: string, idempotencyKey: string) => void;
|
|
can: (permission: string) => boolean;
|
|
downloadPdf: (versionId: string, size: number) => Promise<Blob>;
|
|
request: <T>(
|
|
path: string,
|
|
schema: z.ZodType<T>,
|
|
options?: Options,
|
|
) => Promise<T>;
|
|
} | null>(null);
|
|
function initialOrganization() {
|
|
let value = import.meta.env.VITE_ORGANIZATION_ID || "";
|
|
try {
|
|
value = localStorage.getItem("mani.organization") || value;
|
|
} catch {
|
|
/* Storage can be disabled. */
|
|
}
|
|
const parsed = organizationSchema.safeParse(value);
|
|
return parsed.success ? parsed.data : "";
|
|
}
|
|
export function PlatformProvider({ children }: { children: ReactNode }) {
|
|
const client = useQueryClient();
|
|
const [organization, updateOrganization] = useState(initialOrganization);
|
|
const [session, setSession] = useState<Session | null>(null);
|
|
const [principal, setPrincipal] = useState<Principal | null>(null);
|
|
const [notice, setNotice] = useState("");
|
|
const [accessRevision, setAccessRevision] = useState(0);
|
|
const revision = useRef(0),
|
|
intents = useRef(new Map<string, unknown>());
|
|
const current = useRef<Session | null>(null),
|
|
generation = useRef(0),
|
|
scopeAbort = useRef(new AbortController());
|
|
const clearSession = useCallback(
|
|
(message = "") => {
|
|
generation.current += 1;
|
|
current.current = null;
|
|
revision.current += 1;
|
|
setAccessRevision(revision.current);
|
|
intents.current.clear();
|
|
scopeAbort.current.abort();
|
|
scopeAbort.current = new AbortController();
|
|
void client.cancelQueries({ queryKey: ["private"] });
|
|
client.removeQueries({ queryKey: ["private"] });
|
|
client.getMutationCache().clear();
|
|
setSession(null);
|
|
setPrincipal(null);
|
|
setNotice(message);
|
|
},
|
|
[client],
|
|
);
|
|
useEffect(() => {
|
|
if (!session) return;
|
|
const timer = setTimeout(
|
|
() => clearSession("Your session expired. Sign in again."),
|
|
Math.max(0, Date.parse(session.expiresAt) - Date.now()),
|
|
);
|
|
return () => clearTimeout(timer);
|
|
}, [session, clearSession]);
|
|
useEffect(() => {
|
|
scopeAbort.current = new AbortController();
|
|
return () => {
|
|
generation.current += 1;
|
|
scopeAbort.current.abort();
|
|
};
|
|
}, []);
|
|
function setOrganization(value: string) {
|
|
const normalized = organizationSchema.parse(value);
|
|
if (normalized !== organization) clearSession();
|
|
updateOrganization(normalized);
|
|
setNotice("");
|
|
try {
|
|
localStorage.setItem("mani.organization", normalized);
|
|
} catch {
|
|
/* The in-memory setting still works. */
|
|
}
|
|
}
|
|
async function signIn(email: string, password: string) {
|
|
const version = ++generation.current;
|
|
const next = await login(organization, email, password);
|
|
try {
|
|
const me = await getPrincipal(next.accessToken);
|
|
if (
|
|
version !== generation.current ||
|
|
me.organizationId !== organization ||
|
|
Date.parse(next.expiresAt) <= Date.now()
|
|
)
|
|
throw new Error(
|
|
"The session changed during sign-in. Please try again.",
|
|
);
|
|
clearSession();
|
|
current.current = next;
|
|
setSession(next);
|
|
setPrincipal(me);
|
|
setNotice("");
|
|
} catch (error) {
|
|
await apiRequest("/auth/logout", {
|
|
method: "POST",
|
|
token: next.accessToken,
|
|
}).catch(() => {
|
|
/* Best-effort revoke; this token is never retained locally. */
|
|
});
|
|
throw error;
|
|
}
|
|
}
|
|
async function signOut() {
|
|
const previous = current.current;
|
|
clearSession();
|
|
if (!previous) return;
|
|
try {
|
|
await apiRequest("/auth/logout", {
|
|
method: "POST",
|
|
token: previous.accessToken,
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof ApiError && error.status === 401) return;
|
|
throw new Error(
|
|
"You are signed out locally, but server revocation could not be confirmed. The server session will expire automatically.",
|
|
);
|
|
}
|
|
}
|
|
async function withSession<T>(
|
|
perform: (token: string, signal: AbortSignal) => Promise<T>,
|
|
callerSignal?: AbortSignal,
|
|
) {
|
|
const active = session;
|
|
if (
|
|
!active ||
|
|
current.current !== active ||
|
|
revision.current !== accessRevision
|
|
)
|
|
throw new ApiError("Sign in to continue.", 401, "SESSION_CHANGED");
|
|
if (Date.parse(active.expiresAt) <= Date.now()) {
|
|
clearSession("Your session expired. Sign in again.");
|
|
throw new ApiError("Your session expired.", 401, "SESSION_EXPIRED");
|
|
}
|
|
const signal = callerSignal
|
|
? AbortSignal.any([scopeAbort.current.signal, callerSignal])
|
|
: scopeAbort.current.signal;
|
|
try {
|
|
const data = await perform(active.accessToken, signal);
|
|
if (current.current !== active || revision.current !== accessRevision)
|
|
throw new ApiError(
|
|
"Your session changed. Sign in again.",
|
|
401,
|
|
"SESSION_CHANGED",
|
|
);
|
|
return data;
|
|
} catch (error) {
|
|
if (
|
|
current.current === active &&
|
|
revision.current === accessRevision &&
|
|
error instanceof ApiError
|
|
) {
|
|
if (error.status === 401)
|
|
clearSession("Your session is no longer valid. Sign in again.");
|
|
else if (error.status === 403) {
|
|
try {
|
|
const me = await getPrincipal(active.accessToken);
|
|
if (
|
|
current.current === active &&
|
|
revision.current === accessRevision
|
|
) {
|
|
if (
|
|
me.permissions.length !== principal?.permissions.length ||
|
|
me.permissions.some(
|
|
(permission) => !principal?.permissions.includes(permission),
|
|
)
|
|
) {
|
|
scopeAbort.current.abort();
|
|
scopeAbort.current = new AbortController();
|
|
revision.current += 1;
|
|
setAccessRevision(revision.current);
|
|
void client.cancelQueries({ queryKey: ["private"] });
|
|
client.removeQueries({ queryKey: ["private"] });
|
|
client.getMutationCache().clear();
|
|
}
|
|
setPrincipal(me);
|
|
}
|
|
} catch (refresh) {
|
|
if (
|
|
current.current === active &&
|
|
refresh instanceof ApiError &&
|
|
refresh.status === 401
|
|
)
|
|
clearSession("Your session is no longer valid. Sign in again.");
|
|
}
|
|
}
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
async function request<T>(path: string, schema: z.ZodType<T>, options: Options = {}) {
|
|
const data = await withSession(
|
|
(token, signal) => apiRequest(path, { ...options, token, signal }),
|
|
options.signal,
|
|
);
|
|
return parse(schema, data);
|
|
}
|
|
function downloadPdf(versionId: string, size: number) {
|
|
const id = z.string().uuid().parse(versionId);
|
|
return withSession((token, signal) => apiPdf(`/supplier-document-versions/${id}/download`, size, token, signal));
|
|
}
|
|
return (
|
|
<PlatformContext.Provider
|
|
value={{
|
|
organization,
|
|
setOrganization,
|
|
principal,
|
|
scope: principal ? `${principal.sessionId}:${accessRevision}` : "",
|
|
signIn,
|
|
signOut,
|
|
notice,
|
|
clearSession,
|
|
getIntent: (key) =>
|
|
session && current.current === session
|
|
? intents.current.get(key)
|
|
: undefined,
|
|
saveIntent: (key, value) => {
|
|
if (session && current.current === session)
|
|
intents.current.set(key, value);
|
|
},
|
|
clearIntent: (key, idempotencyKey) => {
|
|
const stored = intents.current.get(key);
|
|
if (
|
|
session &&
|
|
current.current === session &&
|
|
typeof stored === "object" &&
|
|
stored !== null &&
|
|
"idempotencyKey" in stored &&
|
|
stored.idempotencyKey === idempotencyKey
|
|
)
|
|
intents.current.delete(key);
|
|
},
|
|
can: (permission) =>
|
|
Boolean(principal?.permissions.includes(permission)),
|
|
downloadPdf,
|
|
request,
|
|
}}
|
|
>
|
|
{children}
|
|
</PlatformContext.Provider>
|
|
);
|
|
}
|
|
export function usePlatform() {
|
|
const context = useContext(PlatformContext);
|
|
if (!context) throw new Error("PlatformProvider is missing");
|
|
return context;
|
|
}
|