Files
dashboards/lib/session-handoff.ts

101 lines
2.7 KiB
TypeScript

import {
getAccessToken,
getRefreshToken,
setTokens,
} from "@/lib/meshkee-api";
import {
getBusinessDashboardOrigin,
getCustomerDashboardOrigin,
} from "@/lib/host";
import {
clearManagedBusinessId,
setManagedBusinessId,
} from "@/lib/managed-business";
/**
* Superadmin “Manage business” — same origin as admin (no subdomain bounce).
* Example: /manage/{meshkeeBusinessId}/profile
*/
export function openBusinessDashboardAsAdmin(
meshkeeBusinessId: string,
nextPath = "/profile",
) {
const id = meshkeeBusinessId.trim();
if (!id) return;
setManagedBusinessId(id);
const path = nextPath.startsWith("/") ? nextPath : `/${nextPath}`;
const suffix = path === "/" ? "/profile" : path;
window.location.assign(`/manage/${encodeURIComponent(id)}${suffix}`);
}
/**
* Business owner / staff → business.* host from their account.
*/
export function openBusinessDashboardAsUser(nextPath = "/profile") {
const access = getAccessToken();
const refresh = getRefreshToken();
if (!access || !refresh) {
window.location.assign(`${getCustomerDashboardOrigin()}/login`);
return;
}
setTokens(access, refresh);
clearManagedBusinessId();
const next = nextPath.startsWith("/") ? nextPath : `/${nextPath}`;
const hash = new URLSearchParams({
access,
refresh,
next,
clearManaged: "1",
}).toString();
window.location.assign(
`${getBusinessDashboardOrigin()}/auth/handoff#${hash}`,
);
}
export function businessDashboardHrefForUser(nextPath = "/profile"): string {
const next = nextPath.startsWith("/") ? nextPath : `/${nextPath}`;
const access = getAccessToken();
const refresh = getRefreshToken();
if (!access || !refresh) {
return `${getCustomerDashboardOrigin()}/login`;
}
const hash = new URLSearchParams({
access,
refresh,
next,
clearManaged: "1",
}).toString();
return `${getBusinessDashboardOrigin()}/auth/handoff#${hash}`;
}
export function businessDashboardHrefForAdmin(
meshkeeBusinessId: string,
nextPath = "/profile",
): string {
const id = meshkeeBusinessId.trim();
if (!id) return "/businesses";
const path = nextPath.startsWith("/") ? nextPath : `/${nextPath}`;
const suffix = path === "/" ? "/profile" : path;
return `/manage/${encodeURIComponent(id)}${suffix}`;
}
export function customerDashboardHref(nextPath = "/"): string {
const next = nextPath.startsWith("/") ? nextPath : `/${nextPath}`;
const access = getAccessToken();
const refresh = getRefreshToken();
if (!access || !refresh) {
return `${getCustomerDashboardOrigin()}${next}`;
}
const hash = new URLSearchParams({
access,
refresh,
next,
}).toString();
return `${getCustomerDashboardOrigin()}/auth/handoff#${hash}`;
}