Authorization
Introduction
Authentication tells you who the user is. Authorization decides what they may do. @plinthjs/authorization gives you a Gate: a registry of named abilities and resource policies that you query with allows, denies, and authorize. It has no dependency on the HTTP layer, so you can use the same gate in controllers, jobs, and views.
pnpm add @plinthjs/authorizationA gate is generic over your user type. Anything works, including the Authenticatable objects from Authentication:
import { Gate } from '@plinthjs/authorization'
interface User {
id: number
role: 'admin' | 'editor' | 'reader'
}
const gate = new Gate<User>()Defining abilities
An ability is a named callback. It receives the user first, followed by whatever extra arguments the caller passes, and returns a boolean or a Response object (covered below):
import { Gate, Response } from '@plinthjs/authorization'
class Post {
id: number
authorId: number
published: boolean
constructor(id: number, authorId: number, published = true) {
this.id = id
this.authorId = authorId
this.published = published
}
}
gate.define('manage-users', (user) => user.role === 'admin')
gate.define('edit-post', (user, post: Post) =>
user.id === post.authorId
? Response.allow()
: Response.deny('You do not own this post.', 'NOT_OWNER'),
)Defining an ability again replaces the earlier callback. gate.has('edit-post') reports whether an ability is defined (it accepts an array and requires all of them), and gate.abilities() lists the defined names:
gate.has('edit-post') // => true
gate.has(['edit-post', 'nope']) // => false
gate.abilities() // => ['manage-users', 'edit-post']INFO
has() and abilities() only see abilities registered with define() or resource(). Policy methods that you resolve by passing a resource are not listed.
Checking abilities
Pass the ability name, the user, and any arguments the callback expects:
const ada: User = { id: 1, role: 'editor' }
const post = new Post(10, 1)
gate.allows('edit-post', ada, post) // => true
gate.denies('edit-post', ada, new Post(11, 2)) // => true
gate.check('edit-post', ada, post) // => true (an alias of allows)
gate.any(['manage-users', 'edit-post'], ada, post) // => true
gate.none(['manage-users'], ada) // => trueany() is true when at least one ability allows, and none() is true when none do. An ability that has not been defined (and has no policy) is denied, so a typo fails closed. Guests are denied too: a null or undefined user is refused for every defined ability unless a before hook allows it (see below).
gate.allows('manage-users', null) // => false
gate.allows('does-not-exist', ada) // => falseThrowing on denial
authorize() returns the allowing response, and throws an AuthorizationError when the ability is denied. Use it in controllers so a denial stops the request:
import { AuthorizationError } from '@plinthjs/authorization'
try {
gate.authorize('edit-post', ada, new Post(11, 2))
} catch (error) {
if (error instanceof AuthorizationError) {
error.message // => 'You do not own this post.'
error.code // => 'NOT_OWNER'
error.status // => 403
error.response.denied() // => true
}
}When the HTTP kernel catches an AuthorizationError, it renders it with the error's status: a 403 by default, or the status carried by the denying response. JSON clients get {"message":"This action is unauthorized.","status":403} and browsers get an HTML error page. See Errors.
Binding a user
Passing the user to every call gets repetitive. forUser() returns a gate bound to a default user. It shares the abilities, policies, and hooks of the original, so later registrations are visible to it:
const forAda = gate.forUser(ada)
forAda.allows('edit-post', undefined, post) // => true
forAda.authorize('manage-users') // throws AuthorizationErrorPass undefined in the user position to use the bound user. A typical request handler builds a bound gate once from the signed-in user.
Responses
A bare boolean is enough for most checks. When you want a message, an error code, or a specific HTTP status, return a Response instead. Do not confuse it with the HTTP Response from @plinthjs/http; the two are unrelated, so import one of them under an alias if you need both.
import { Response } from '@plinthjs/authorization'
Response.allow() // allow
Response.allow('Welcome back.', 'OK_RETURNING') // allow with a message and code
Response.deny() // deny
Response.deny('Archived posts are read only.', 'ARCHIVED') // deny with a reason
Response.denyWithStatus(402, 'Upgrade your plan.') // deny and render as 402
Response.denyAsNotFound() // deny and render as 404denyAsNotFound() is how you hide that a resource exists from people who should not know about it. Inspect the full result of a check with inspect():
const result = gate.inspect('edit-post', ada, new Post(11, 2))
result.allowed() // => false
result.denied() // => true
result.message() // => 'You do not own this post.'
result.code() // => 'NOT_OWNER'
result.status() // => null (the HTTP layer falls back to 403)Calling result.authorize() throws an AuthorizationError carrying the response. A status set with denyWithStatus() or denyAsNotFound() becomes error.status, so the kernel renders it:
gate.define('delete-comment', (user, authorId: number) =>
user.id === authorId ? true : Response.denyAsNotFound(),
)
gate.authorize('delete-comment', ada, 99) // throws an AuthorizationError with status 404Policies
When abilities revolve around a model, group them in a policy. A policy is a plain object (or a class instance) whose methods are ability callbacks. Register it against a class or a string tag, then check by passing the resource as the first argument:
gate.policy(Post, {
view: (user: User, post: Post) => post.published || user.id === post.authorId,
update: (user: User, post: Post) => user.id === post.authorId,
delete: (user: User, post: Post) =>
user.id === post.authorId ? true : Response.denyAsNotFound(),
})
gate.allows('update', ada, new Post(10, 1)) // => true
gate.allows('update', ada, new Post(10, 2)) // => falseThe gate takes the first argument after the user, finds its policy, and calls the method named after the ability. Abilities you define directly with define() always win over a policy method of the same name.
You can register a policy for a string tag, which suits abilities that are not tied to an instance, such as creating a record:
gate.policy('comment', {
create: (user: User) => user.role !== 'reader',
})
gate.allows('create', ada, 'comment') // => truePolicy lookup
getPolicyFor() returns the policy for a class, an instance (by its constructor), or a string tag, or undefined when none is registered:
gate.getPolicyFor(Post) !== undefined // => true
gate.getPolicyFor(new Post(1, 1)) !== undefined // => true
gate.getPolicyFor('unknown') // => undefinedResource abilities
resource() registers a policy's standard methods as named abilities, prefixed with a name you choose. By default it looks for viewAny, view, create, update, and delete and skips the ones your policy does not have:
gate.resource('posts', {
viewAny: () => true,
view: (user: User, post: Post) => post.published,
update: (user: User, post: Post) => user.id === post.authorId,
})
gate.abilities() // => [..., 'posts.viewAny', 'posts.view', 'posts.update']
gate.allows('posts.update', ada, new Post(10, 1)) // => true
gate.allows('posts.delete', ada, new Post(10, 1)) // => false (not defined)Pass a third argument to choose which methods to register: gate.resource('posts', policy, ['view', 'publish']).
Before and after hooks
A before hook runs ahead of every check, including checks for guests. Return true or false (or a Response) to decide immediately, or undefined to defer to the normal ability. The classic use is a super-admin who may do everything:
gate.before((user) => (user?.role === 'admin' ? true : undefined))
gate.allows('posts.update', { id: 9, role: 'admin' }, new Post(10, 1)) // => trueHooks run in registration order and the first one that returns something wins. Because before hooks run for guests, user may be null or undefined inside them.
An after hook runs only when nothing else produced a decision, which makes it a place for default verdicts:
gate.after((user, ability) => (ability === 'ping' ? true : undefined))
gate.allows('ping', ada) // => trueNote that an after hook runs when no ability or policy method exists for the check. It does not override an ability that exists and returned a verdict.
Ad hoc checks
allowIf() and denyIf() authorize a condition on the spot, without defining a named ability. They return the allowing response, or throw an AuthorizationError with the message and code you give them. The condition can be a boolean, a Response, or a callback that receives the gate's bound user:
const forEditor = gate.forUser(ada)
forEditor.allowIf(true) // passes
forEditor.allowIf((user) => user?.role === 'admin', 'Admins only.', 'ADMIN_ONLY')
// throws AuthorizationError: message 'Admins only.', code 'ADMIN_ONLY', status 403
forEditor.denyIf((user) => user?.role === 'editor', 'Editors are blocked.')
// throws AuthorizationError
gate.allowIf(Response.denyWithStatus(418, 'I am a teapot')) // throws, status 418denyIf is the inverse of allowIf: a truthy condition throws.
Authorizing in routes
The package does not ship an HTTP middleware, because the user and the resource depend on your application. Writing one is a few lines. This can() factory authorizes a named ability against a model your own code loads:
import { Response } from '@plinthjs/http'
import type { Middleware, Request } from '@plinthjs/http'
function can(
ability: string,
resolve: (request: Request) => Promise<unknown> | unknown,
): Middleware {
return async (request, next) => {
const user = currentUser(request) // however your app reads the signed-in user
gate.authorize(ability, user, await resolve(request))
return next(request)
}
}
router.get('/posts/{id}/edit', editPost).middleware(
authenticate(),
can('update', (request) => findPost(request.param('id'))),
)An unauthorized request throws AuthorizationError, which the kernel renders as a 403 (or whatever status the denying Response carries). Put your authentication middleware first so guests receive a 401 or a redirect before the ability check runs. Inside controllers, call gate.authorize() directly when the check depends on data you loaded in the handler.
Testing
Gates are plain objects. Build one in the test, define the abilities, and assert on the booleans and the thrown error:
import { expect, it } from 'vitest'
it("hides other people's posts", () => {
expect(() => gate.authorize('delete', ada, new Post(1, 2))).toThrow(AuthorizationError)
})Related
- Authentication provides the signed-in user you pass to the gate.
- Middleware explains how to attach checks like
can()to routes.