@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
58 lines (57 loc) • 1.88 kB
JavaScript
//#region src/route/visibility.ts
/**
* Why a visitor was denied.
*
* - `unauthenticated` — the route needs a signed-in visitor and there is none.
* - `forbidden` — signed in, but in none of the groups the route names.
* - `alreadyAuthenticated` — the route is for signed-out visitors only.
*/
const ACCESS_REASONS = [
"unauthenticated",
"forbidden",
"alreadyAuthenticated"
];
/** The decision and, when a visitor is denied, the reason. Throws nothing. */
function checkAccess(visibility, context) {
return checkRule(visibility, context);
}
/** {@link checkAccess} for a page's rule, which {@link defineVisibility} has not produced. */
function checkRule(rule, context) {
const { user } = context;
const audiences = rule.userGroupTypes;
if (user === null) return audiences.includes("NON_LOGGED_IN_USERS") ? { ok: true } : {
ok: false,
reason: "unauthenticated"
};
if (!audiences.includes("LOGGED_IN_USERS")) return {
ok: false,
reason: "alreadyAuthenticated"
};
const required = rule.customGroups ?? [];
if (required.length === 0) return { ok: true };
return required.some((id) => user.userGroupIds.includes(id)) ? { ok: true } : {
ok: false,
reason: "forbidden"
};
}
/**
* Declares who may see a region of the page. A route's own rule is the
* `visibility` of its `definePage`.
*
* @example
* const staffOnly = defineVisibility({ userGroupTypes: ["LOGGED_IN_USERS"], customGroups: ["…"] })
*
* <Audience visibility={staffOnly} fallback={null}>…</Audience>
*/
function defineVisibility(rule) {
return rule;
}
/**
* Whether the visitor passes the rule, narrowing `context.user` where the rule
* allows it. Throws nothing, so it is safe in a component.
*/
function isAuthorized(visibility, context) {
return checkAccess(visibility, context).ok;
}
//#endregion
export { ACCESS_REASONS, checkAccess, checkRule, defineVisibility, isAuthorized };