redwood-clerk
Version:
Unofficial Clerk integration for RedwoodSDK
50 lines (48 loc) • 2.01 kB
JavaScript
import { auth } from "./auth.js";
import { Fragment, jsx } from "react/jsx-runtime";
import "react";
//#region src/server/control-components.tsx
async function SignedIn(props) {
const { children } = props;
const { userId } = await auth();
return userId ? /* @__PURE__ */ jsx(Fragment, { children }) : null;
}
async function SignedOut(props) {
const { children } = props;
const { userId } = await auth();
return userId ? null : /* @__PURE__ */ jsx(Fragment, { children });
}
/**
* Use `<Protect/>` in order to prevent unauthenticated or unauthorized users from accessing the children passed to the component.
*
* Examples:
* ```
* <Protect permission="a_permission_key" />
* <Protect role="a_role_key" />
* <Protect condition={(has) => has({permission:"a_permission_key"})} />
* <Protect condition={(has) => has({role:"a_role_key"})} />
* <Protect fallback={<p>Unauthorized</p>} />
* ```
*/
async function Protect(props) {
const { children, fallback,...restAuthorizedParams } = props;
const { has, userId } = await auth({ treatPendingAsSignedOut: restAuthorizedParams.treatPendingAsSignedOut });
/**
* Fallback to UI provided by user or `null` if authorization checks failed
*/
const unauthorized = fallback ? /* @__PURE__ */ jsx(Fragment, { children: fallback }) : null;
const authorized = /* @__PURE__ */ jsx(Fragment, { children });
if (!userId) return unauthorized;
/**
* Check against the results of `has` called inside the callback
*/
if (typeof restAuthorizedParams.condition === "function") return restAuthorizedParams.condition(has) ? authorized : unauthorized;
if (restAuthorizedParams.role || restAuthorizedParams.permission || restAuthorizedParams.feature || restAuthorizedParams.plan) return has(restAuthorizedParams) ? authorized : unauthorized;
/**
* If neither of the authorization params are passed behave as the `<SignedIn/>`.
* If fallback is present render that instead of rendering nothing.
*/
return authorized;
}
//#endregion
export { Protect, SignedIn, SignedOut };