UNPKG

permix

Version:

Permix is a lightweight, framework-agnostic, type-safe permissions management library for JavaScript applications on the client and server sides.

74 lines (71 loc) 1.86 kB
import fp from 'fastify-plugin'; import { c as createTemplate, a as createPermix$1 } from '../shared/permix.Q-O041RP.mjs'; import { p as pick, c as createCheckContext } from '../shared/permix.q13nxITM.mjs'; const permixSymbol = Symbol('permix'); /** * Create a middleware function that checks permissions for Fastify routes. * * @link https://permix.letstri.dev/docs/integrations/fastify */ function createPermix({ onForbidden = ({ reply }) => { reply.status(403).send({ error: 'Forbidden' }); } } = {}) { function getPermix(request, reply) { try { const permix = request.getDecorator(permixSymbol); if (!permix) { throw new Error('Not found'); } return pick(permix, ['check', 'dehydrate']); } catch { reply.status(500).send({ error: '[Permix]: Instance not found. Please register the `plugin` function.' }); return null; } } function plugin(callback) { return fp(async fastify => { fastify.decorateRequest(permixSymbol, null); fastify.addHook('onRequest', async (request, reply) => { const permix = createPermix$1(await callback({ request, reply })); request.setDecorator(permixSymbol, permix); }); }, { fastify: '5.x', name: 'permix' }); } function checkHandler(...params) { return async (request, reply) => { const permix = getPermix(request, reply); const hasPermission = permix.check(...params); if (!hasPermission) { await onForbidden({ request, reply, ...createCheckContext(...params) }); } }; } function template(...params) { return createTemplate(...params); } return { plugin, checkHandler, template, get: getPermix }; } export { createPermix };