Hooks are callback functions registered via Kilpi.hooks.onSomeHook
. Registering a hook returns an unregister
function which can be used to remove the hook.
Hooks offer a flexible API for hooking into and extending the functionality of the core library, especially for plugins.
Types of hooks
This list contains the types of different hooks you can use to use with Kilpi or in your custom plugins.
onRequestScope
When there is no explicit scope available via Kilpi.runInScope
or Kilpi.scoped
, Kilpi attempts to resolve a scope from plugins using the onRequestScope
hook. The hook must return a scope object if one can be created for the current request.
const unregister = Kilpi.hooks.onRequestScope(() => { if (isCustomScopeAvailable) { return customScope; }});
Type reference
Receives no parameters. Returns a KilpiScope
object or undefined
.
onAfterAuthorization
Called after a policy is evaluated with the authorization result (from e.g. Kilpi.authorize()
or Kilpi.isAuthorized()
). Only used as a callback, for example for logging.
const unregister = Kilpi.hooks.onAfterAuthorization((event) => { console.log(`Authorization ${event.authorization.granted ? "passed" : "denied"}`); console.log(`> Policy: ${event.policy}`); console.log(`> Subject: ${event.subject.name}`); console.log(`> Source: ${event.source}`); console.log(`> Error: ${event.authorization.error}`);});
Type reference
Receives a KilpiOnAfterAuthorizationEvent
object as a parameter.
export type KilpiOnAfterAuthorizationEvent<T extends AnyKilpiCore> = { /** * Source (Where was the authorization triggered from) */ source: string;
/** * Policy key to authorize */ policy: string;
/** * Current subject */ subject: T["$$infer"]["subject"];
/** * The resulting authorization object */ authorization: Authorization<InferPolicySubject<T["$$infer"]["policies"]>>;
/** * The resource being authorized */ resource?: unknown;};