Skip to content

@plinthjs/authorization ​

Plinth authorization: the Gate + Policies system.

Abilities ​

ts
import { Gate, Response } from '@plinthjs/authorization'

interface User {
  id: number
  isAdmin: boolean
}

const gate = new Gate<User>()

gate.define('edit-post', (user, post: { authorId: number }) =>
  user.id === post.authorId
    ? Response.allow()
    : Response.deny('You do not own this post.', 'NOT_OWNER'),
)

const user: User = { id: 1, isAdmin: false }

gate.allows('edit-post', user, { authorId: 1 }) // true
gate.denies('edit-post', user, { authorId: 2 }) // true
gate.inspect('edit-post', user, { authorId: 2 }).message() // 'You do not own this post.'

before / after hooks ​

ts
// Super-admins are granted everything before any ability runs.
gate.before((user) => (user?.isAdmin ? true : undefined))

// Supply a default verdict when nothing else decided.
gate.after(() => false)

authorize (throws) ​

ts
import { AuthorizationError } from '@plinthjs/authorization'

try {
  gate.authorize('edit-post', user, { authorId: 2 })
} catch (e) {
  if (e instanceof AuthorizationError) {
    e.message // 'You do not own this post.'
    e.code // 'NOT_OWNER'
  }
}

Policies ​

Register a policy keyed by a class constructor or a string tag. When an ability is not defined directly, the gate resolves (ability, user, resource) to policy[ability](user,%20resource,%20...args).

ts
class Post {
  constructor(public authorId: number) {}
}

gate.policy(Post, {
  update: (user, post: Post) => user.id === post.authorId,
  delete: (user) => user.isAdmin,
})

gate.allows('update', user, new Post(1)) // true (resolved via the Post policy)

any / none check several abilities at once; forUser(user) returns a gate bound to a default user so you can omit it on every call. Guests (null/undefined) are denied unless a before hook allows them.

Released under the MIT License.