Recipes
Things the library leaves to your app, each as code to copy. Each one is a few lines in your codebase, not an export of @blocks/policy, so you can change it to fit.
Organization and membership
In a multi-tenant app, a user acts inside one organization at a time, and their role comes from their membership there. Build the user for the organization the request is for, and give the policies for that organization's resources one base class:
import { CurrentUser, type CurrentUserData, Policy } from '@blocks/policy'
export type MembershipRole = 'owner' | 'admin' | 'member' | 'viewer'
/**
* The user as a member of the organization the request is for. `role` is
* their role in that organization. Someone with no membership is not a
* Member: turn them away before any policy runs.
*/
export class Member extends CurrentUser<MembershipRole> {
readonly organizationId: string
constructor(data: CurrentUserData<MembershipRole> & { organizationId: string }) {
super(data)
this.organizationId = data.organizationId
}
}
/** For every resource that belongs to an organization. */
export abstract class OrganizationPolicy<TResource extends { organizationId: string }> extends Policy<TResource, Member> {
protected inOrganization() {
return this.resource.organizationId === this.user.organizationId
}
protected isAdmin() {
return this.inOrganization() && this.user.hasRole('owner', 'admin')
}
protected canWrite() {
return this.inOrganization() && this.user.hasRole('owner', 'admin', 'member')
}
}
export interface Invoice {
id: string
organizationId: string
createdBy: string
paid: boolean
}
export class InvoicePolicy extends OrganizationPolicy<Invoice> {
view() {
return this.inOrganization()
}
update() {
if (this.resource.paid) return false
return this.isAdmin() || (this.canWrite() && this.user.isOwner(this.resource.createdBy))
}
refund() {
if (!this.resource.paid) return false
return this.isAdmin()
}
}Memberis aCurrentUserwhoseroleis the membership role and which knows itsorganizationId. Build it after you have looked up the membership. A user with no membership in the organization has noMember; turn the request away before any policy runs.OrganizationPolicyholds the checks every organization resource shares.inOrganizationis the first deny condition: a member of one organization gets nothing on another organization's resources, whatever their role. The helpers are protected, so code outside the policy cannot call them.InvoicePolicyreads like any other policy, with its own deny conditions first.
If your app already has user, organization and membership models and would rather pass them as they are, use your own user type instead. The current user shows that shape.
Several roles per user
CurrentUser has one role. When a user can hold several at once, such as editor and billing, write a small user class of your own and use it as the policies' user type:
import { Policy } from '@blocks/policy'
export type Role = 'writer' | 'editor' | 'billing' | 'admin'
/** A user who can hold several roles at once. It replaces CurrentUser as the policies' user. */
export class User {
readonly id: string
readonly roles: ReadonlySet<Role>
constructor(data: { id: string; roles: readonly Role[] }) {
this.id = data.id
this.roles = new Set(data.roles)
}
/** Whether the user holds any of these roles. False with none. */
hasRole(...roles: Role[]) {
return roles.some((role) => this.roles.has(role))
}
/** Whether the user holds every one of these roles. False with none. */
hasEveryRole(...roles: Role[]) {
return roles.length > 0 && roles.every((role) => this.roles.has(role))
}
/** Whether the user's id is this owner's. Never true for a missing owner. */
isOwner(ownerId: string | null | undefined) {
return !!ownerId && ownerId === this.id
}
}
export abstract class AppPolicy<TResource> extends Policy<TResource, User> {}
export interface Article {
authorId: string
sponsored: boolean
}
export class ArticlePolicy extends AppPolicy<Article> {
update() {
return this.user.isOwner(this.resource.authorId) || this.user.hasRole('editor', 'admin')
}
publish() {
if (this.resource.sponsored) return this.user.hasEveryRole('editor', 'billing')
return this.user.hasRole('editor', 'admin')
}
}hasRole is true when the user holds any of the roles you pass, as with CurrentUser. hasEveryRole is for the actions that need all of them: publishing a sponsored article here needs both editor and billing. Both are false when called with no roles, and isOwner refuses a missing owner the same way CurrentUser.isOwner does.
Conditional rendering
@blocks/policy has no React dependency and ships no components, and a component needs none: an action returns a boolean, so render from it the way you render from any boolean.
import type { PostPolicy } from '../quickstart/post-policy'
export function PostActions({ policy }: { policy: PostPolicy }) {
return (
<div>
{policy.update() && <a href="edit">Edit</a>}
{policy.destroy() ? <button type="submit">Delete</button> : <span>Only an admin can delete a post.</span>}
</div>
)
}
/** The booleans a Client Component can take as props, computed where the policy is built. */
export function PostActionsFromProps({ canEdit, canDelete }: { canEdit: boolean; canDelete: boolean }) {
return (
<div>
{canEdit && <a href="edit">Edit</a>}
{canDelete && <button type="submit">Delete</button>}
</div>
)
}PostActions calls policy.update() and policy.destroy() where it renders, with && for a control that appears or not and a ternary for one with a fallback. PostActionsFromProps takes the booleans as props instead.
A policy is a class instance, so React cannot pass it from a Server Component to a Client Component as a prop. Call the actions where the policy is built and pass the booleans, as postPermissions in Enforcing does. Hiding a button does not protect anything on its own: the server still calls the action and refuses the request, as Enforcing shows.