Blocks Policy

The current user

Every policy is asked about a user. By default that user is a CurrentUser: an id, one role, and the feature flags already resolved for them. This page covers using it as it is, typing its role and flag names, adding fields, and replacing it with your own type.

CurrentUser out of the box

Build a CurrentUser from what your session or auth provider already knows. It takes an object with id, role and, optionally, flags.

current-user/session-user.ts
import { CurrentUser } from '@blocks/policy'

/** What your session or auth provider already knows about the request. */
export interface Session {
  userId: string
  role: string
  /** Feature flags, resolved for this user before any policy runs. */
  flags: Record<string, boolean>
}

export function currentUser(session: Session) {
  return new CurrentUser({ id: session.userId, role: session.role, flags: session.flags })
}

export const user = currentUser({ userId: 'u1', role: 'editor', flags: { 'bulk-export': true, 'new-editor': false } })

export const answers = {
  isEditor: user.hasRole('editor', 'admin'), // true: the role is one of these
  noRoles: user.hasRole(), // false: no roles, no match
  ownsHers: user.isOwner('u1'), // true
  ownsNobodys: user.isOwner(null), // false: a resource with no owner is nobody's
  bulkExport: user.hasFlag('bulk-export'), // true
  newEditor: user.hasFlag('new-editor'), // false: resolved to false
  unknownFlag: user.hasFlag('dark-mode'), // false: a missing flag is off
}

It has three methods, and each one says no unless the answer is clearly yes:

  • hasRole(...roles) is true when the user's role is one of the roles you pass. With no arguments it is false.
  • isOwner(ownerId) is true when ownerId is the user's id. It is false for null, undefined and the empty string, so a resource with no owner is never owned by anyone, even a user whose own id is empty.
  • hasFlag(name) is true only when the flag was resolved to exactly true. A missing flag, a flag set to false or any other value, and a user built without flags all give false.

Resolve flags before you build the user, with whatever flag service you use, and pass the results in. CurrentUser never looks a flag up. flags is an empty object when you pass none.

Typing role and flag names

With no type parameters, CurrentUser accepts any string as a role or a flag, so a misspelled name compiles and quietly returns false. Give it your app's names as CurrentUser<Role, Flag> and TypeScript checks them everywhere: in the data you construct it with, in hasRole and in hasFlag.

current-user/typed-names.ts
import { CurrentUser } from '@blocks/policy'

export type Role = 'viewer' | 'editor' | 'admin'
export type Flag = 'bulk-export' | 'new-editor'

export const user = new CurrentUser<Role, Flag>({ id: 'u1', role: 'editor', flags: { 'bulk-export': true } })

export const isEditor = user.hasRole('editor', 'admin')

// @ts-expect-error 'edtior' is not a Role
user.hasRole('edtior')

// @ts-expect-error 'bulk-exports' is not a Flag
user.hasFlag('bulk-exports')

// @ts-expect-error 'owner' is not a Role, so the data is refused too
new CurrentUser<Role, Flag>({ id: 'u2', role: 'owner' })

// Without type parameters, any role and flag name is accepted.
const untyped = new CurrentUser({ id: 'u3', role: 'editor' })
export const anyName = untyped.hasRole('edtior')

Each line under @ts-expect-error is one TypeScript refuses. The type parameters are not inferred from the data you pass: new CurrentUser({ id, role: 'editor' }) is a CurrentUser<string, string>, whose hasRole still takes any string. Write the parameters out, or extend the class once as in the next section.

Adding fields

Policies often need more than an id and a role: the user's team, region or plan. Extend CurrentUser with those fields, and declare your app's base policy once with that user type:

current-user/app-user.ts
import { CurrentUser, type CurrentUserData, Policy } from '@blocks/policy'

export type Role = 'viewer' | 'editor' | 'admin'
export type Flag = 'bulk-export'

export interface AppUserData extends CurrentUserData<Role, Flag> {
  teamId: string
}

export class AppUser extends CurrentUser<Role, Flag> {
  readonly teamId: string

  constructor(data: AppUserData) {
    super(data)
    this.teamId = data.teamId
  }
}

/** Every policy in the app extends this, so `this.user` is an AppUser. */
export abstract class AppPolicy<TResource> extends Policy<TResource, AppUser> {}

export interface Project {
  id: string
  teamId: string
}

export class ProjectPolicy extends AppPolicy<Project> {
  view() {
    return this.user.teamId === this.resource.teamId
  }

  download() {
    if (!this.view()) return false
    return this.user.hasFlag('bulk-export') && this.user.hasRole('editor', 'admin')
  }
}

AppUser keeps hasRole, isOwner and hasFlag, with its role and flag names checked. AppPolicy<TResource> is Policy<TResource, AppUser>, so every policy that extends it sees this.user.teamId without repeating the user type. Constructing a policy that extends AppPolicy with a plain CurrentUser is a compile error, because it lacks teamId.

An AppUser is still a CurrentUser, so a policy declared with the default user accepts one too.

Using a different user type

Policy's second type parameter is the user type, and it can be anything. If your app models the actor as something other than one user with one role, such as a user, the organization they are acting in, and their membership there, pass that type instead:

current-user/own-actor.ts
import { Policy } from '@blocks/policy'

/** Who is acting, as this app models it: not a CurrentUser at all. */
export interface Actor {
  user: { id: string; email: string }
  organization: { id: string }
  membership: { role: 'owner' | 'member' } | null
}

export interface Workspace {
  id: string
  organizationId: string
}

export class WorkspacePolicy extends Policy<Workspace, Actor> {
  view() {
    return this.inOrganization() && this.user.membership !== null
  }

  rename() {
    return this.inOrganization() && this.user.membership?.role === 'owner'
  }

  private inOrganization() {
    return this.user.organization.id === this.resource.organizationId
  }
}

this.user is whatever you pass as the first constructor argument. Here it is the Actor object, so the policy reads this.user.membership and this.user.organization. CurrentUser and its methods are not involved at all. Recipes has two more shapes: membership in an organization built on CurrentUser, and a user with several roles.