Follow this guide to protect your first functionality in 5 minutes.
Install Kilpi
Install the Kilpi core library.
npm install @kilpi/coreyarn add @kilpi/corepnpm add @kilpi/corebun add @kilpi/coreCreate your Kilpi authorization system
Copy and paste the code below and…
- Replace the
getSubjectimplementation with a call to your authentication provider which returns the current subject (≈ user). - Add your policies or test with the example policies.
import { createKilpi, Grant, Deny } from "@kilpi/core";
export const Kilpi = createKilpi({ // (1) Your subject adapter with optional `ctx` param. async getSubject(ctx?: MyContextType) { return await myAuthenticationProvider.getCurrentUser(ctx); },
// (2) Your policies policies: { posts: { // "All authenticated users can create posts" async create(subject) { if (!subject) return Deny(); return Grant(subject); }, // "Post can only be deleted by the author" async delete(subject, post: { authorId: string }) { if (!subject) return Deny(); if (subject.id !== post.authorId) return Deny(); return Grant(subject); }, }, },});Read more about the subject and policies.
Authorize your first function
Reference a policy e.g. Kilpi.posts.delete(myPost) and receive an authorization decision using .authorize(). If your getSubject adapter takes in a ctx parameter, pass it as shown below.
import { Kilpi } from "...";
async function deletePost(post: Post) { const { granted } = await Kilpi .posts // (Policy namespace) .delete(post) // Instantiate policy with object .authorize({ ctx }); // Run the authorization check
if (granted) await db.posts.delete(post.id);}Read more about the authorization APIs.