@cerbos/react
Version:
A collection of React hooks for interacting with Cerbos policy decision points
65 lines • 2.7 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.CerbosContext = void 0;
exports.CerbosProvider = CerbosProvider;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const use_deep_compare_effect_1 = require("use-deep-compare-effect");
exports.CerbosContext = (0, react_1.createContext)(undefined);
/**
* A component to provide a Cerbos client to your application's components.
*
* @remarks
* The provider should be placed close to the root of your application.
*
* You need to provide a principal, but it can describe an anonymous user so that you can perform permission checks for unauthenticated users.
* You could use a single hardcoded ID for all anonymous users, or store a unique identifier in the session.
*
* You can use whichever of the {@link https://github.com/cerbos/cerbos-sdk-javascript/blob/main/packages/http/README.md | HTTP} or
* {@link https://github.com/cerbos/cerbos-sdk-javascript/blob/main/packages/embedded/README.md | embedded} client libraries best fit your needs.
*
* @example
* ```typescript
* import { Embedded as Cerbos } from "@cerbos/embedded";
* * // or, import { HTTP as Cerbos } from "@cerbos/http";
* import { CerbosProvider } from "@cerbos/react";
*
* // Initialize the Cerbos client using any of the client libraries
* // that fit the needs of your application. In this example we are
* // using the client from `@cerbos/embedded`.
* const client = new Cerbos();
*
* function MyApp({ children }) {
* const user = useYourAuthenticationLogic(...);
*
* return (
* <CerbosProvider
* client={client}
* principal={
* user
* ? {
* id: user.id,
* roles: user.roles,
* }
* : {
* // Define an arbitrary ID for unauthenticated users.
* id: "###ANONYMOUS_USER###",
* // Define a role that represents unauthenticated users (at least one is required).
* roles: ["anonymous"],
* }
* }
* >
* {children}
* </CerbosProvider>
* );
* }
* ```
* @public
*/
function CerbosProvider({ children, client, principal, auxData, }) {
const principalMemo = (0, use_deep_compare_effect_1.useDeepCompareMemoize)(principal);
const auxDataMemo = (0, use_deep_compare_effect_1.useDeepCompareMemoize)(auxData);
const value = (0, react_1.useMemo)(() => client.withPrincipal(principalMemo, auxDataMemo), [client, principalMemo, auxDataMemo]);
return ((0, jsx_runtime_1.jsx)(exports.CerbosContext.Provider, { value: value, children: children }));
}
//# sourceMappingURL=cerbos-provider.js.map
;