wcz-layout
Version:
219 lines (218 loc) • 6.35 kB
JavaScript
import { permissions, scopes } from "virtual:wcz-layout";
import { z } from "zod";
import { BrowserAuthError, EventType, InteractionRequiredAuthError, NavigationClient, PublicClientApplication } from "@azure/msal-browser";
import { createEnv } from "@t3-oss/env-core";
import { createClientOnlyFn, createIsomorphicFn } from "@tanstack/react-start";
//#region src/env.ts
const clientEnv = createEnv({
clientPrefix: "VITE_",
client: {
VITE_ENTRA_CLIENT_ID: z.string(),
VITE_ENTRA_TENANT_ID: z.string(),
VITE_APP_TITLE: z.string(),
VITE_MUI_LICENSE_KEY: z.string()
},
runtimeEnv: import.meta.env,
emptyStringAsUndefined: true
});
const serverEnv = createEnv({
server: {
ENTRA_CLIENT_ID: z.string(),
ENTRA_TENANT_ID: z.string(),
ENTRA_CLIENT_SECRET: z.string()
},
runtimeEnv: process.env,
emptyStringAsUndefined: true
});
//#endregion
//#region src/lib/auth/msalClient.ts
const pca = new PublicClientApplication({
auth: {
clientId: clientEnv.VITE_ENTRA_CLIENT_ID,
authority: `https://login.microsoftonline.com/${clientEnv.VITE_ENTRA_TENANT_ID}`,
redirectUri: "/"
},
cache: { cacheLocation: "localStorage" }
});
const restoreActiveAccount = () => {
if (pca.getActiveAccount()) return;
const [firstAccount] = pca.getAllAccounts();
if (firstAccount) pca.setActiveAccount(firstAccount);
};
const initializeMsal = async () => {
if (globalThis.window === void 0) return;
await pca.initialize();
pca.addEventCallback((event) => {
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
const payload = event.payload;
pca.setActiveAccount(payload.account);
}
});
const response = await pca.handleRedirectPromise();
if (response?.account) {
pca.setActiveAccount(response.account);
return;
}
restoreActiveAccount();
};
const initializationPromise = initializeMsal();
await initializationPromise;
var TanStackNavigationClient = class extends NavigationClient {
constructor(navigate) {
super();
this.navigate = navigate;
}
async navigateInternal(url, options) {
const relative = url.replace(location.origin, "");
this.navigate({
to: relative,
replace: options.noHistory
});
return false;
}
};
const getUser = createIsomorphicFn().server(() => null).client(async () => {
await initializationPromise;
restoreActiveAccount();
const account = pca.getActiveAccount();
if (!account?.idToken) return null;
return buildUser(decodeJwt(account.idToken));
});
/**
* Token Acquisition: Get authenticated access token.
* Use when: Making API calls from the browser to secured endpoints.
*/
const getAccessToken = createClientOnlyFn(async (scopeKey) => {
await initializationPromise;
restoreActiveAccount();
const account = pca.getActiveAccount();
if (!account) throw new Error("No active account. User not signed in.");
const scopes$1 = [...scopes[scopeKey]];
try {
const { accessToken } = await pca.acquireTokenSilent({
scopes: scopes$1,
account
});
return accessToken;
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
try {
await pca.acquireTokenRedirect({
scopes: scopes$1,
account
});
} catch (redirectError) {
if (!(redirectError instanceof BrowserAuthError) || redirectError.errorCode !== "interaction_in_progress") throw redirectError;
}
await new Promise(() => {});
}
throw error;
}
});
//#endregion
//#region src/lib/utils.ts
const WISTRON_PRIMARY_COLOR = "#00506E";
const WISTRON_SECONDARY_COLOR = "#64DC00";
var Platform = class {
static get isAndroid() {
return /android/i.test(this.userAgent);
}
static get isIOS() {
return /iPad|iPhone|iPod/.test(this.userAgent);
}
static get isWindows() {
return /windows/i.test(this.userAgent);
}
static get isMacOS() {
return /Macintosh|MacIntel|MacPPC|Mac68K/.test(this.userAgent);
}
static get userAgent() {
return typeof navigator === "undefined" ? "" : navigator.userAgent;
}
};
const rootRouteHead = (options) => ({
meta: [
{ charSet: "utf-8" },
{
name: "viewport",
content: "width=device-width, initial-scale=1"
},
{ title: clientEnv.VITE_APP_TITLE },
{
name: "og:type",
content: "website"
},
{
name: "og:title",
content: clientEnv.VITE_APP_TITLE
},
{
name: "og:image",
content: "/favicon-32x32.png"
}
],
links: [
{
rel: "apple-touch-icon",
sizes: "180x180",
href: "/apple-touch-icon.png"
},
{
rel: "icon",
type: "image/png",
sizes: "32x32",
href: "/favicon-32x32.png"
},
{
rel: "icon",
type: "image/png",
sizes: "16x16",
href: "/favicon-16x16.png"
},
{
rel: "manifest",
href: options?.manifest || "/manifest.json"
},
{
rel: "icon",
href: "/favicon.ico"
}
]
});
const requirePermission = (permissionKey) => {
return async () => {
const user = await getUser();
if (!user?.hasPermission(permissionKey)) throw new Error("You do not have permission to access this page.");
return { user };
};
};
const getFieldStatus = (field) => {
const { meta } = field.state;
return {
isTouched: meta.isTouched,
hasError: !!meta.errors.length,
helperText: meta.errors[0]?.message
};
};
const toKebabCase = (str) => {
return str.replaceAll(/([a-z])([A-Z])/g, "$1-$2").replaceAll(/[\s_]+/g, "-").replaceAll(/[^a-zA-Z0-9-]/g, "").toLowerCase().replaceAll(/-+/g, "-").replaceAll(/(^-|-$)/g, "");
};
const decodeJwt = (token) => {
const base64 = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
const payload = decodeURIComponent(atob(base64).split("").map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)).join(""));
return JSON.parse(payload);
};
const buildUser = (payload) => ({
id: payload.sub,
name: payload.name?.split("/")[0],
email: payload.preferred_username?.toLowerCase(),
department: payload.department?.toUpperCase() || "",
employeeId: payload.employeeId?.toUpperCase() || "",
companyName: payload.companyName || "",
hasPermission: (key) => {
return permissions[key].some((k) => (payload.groups ?? []).includes(k));
}
});
//#endregion
export { getFieldStatus as a, toKebabCase as c, getUser as d, pca as f, buildUser as i, TanStackNavigationClient as l, serverEnv as m, WISTRON_PRIMARY_COLOR as n, requirePermission as o, clientEnv as p, WISTRON_SECONDARY_COLOR as r, rootRouteHead as s, Platform as t, getAccessToken as u };
//# sourceMappingURL=utils-CqQKSaSs.js.map