UNPKG

permix

Version:

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

70 lines (67 loc) 1.67 kB
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 Express routes. * * @link https://permix.letstri.dev/docs/integrations/express */ function createPermix({ onForbidden = ({ res }) => { res.status(403).json({ error: 'Forbidden' }); } } = {}) { function getPermix(req, res) { try { const permix = req[permixSymbol]; if (!permix) { throw new Error('Not found'); } return pick(permix, ['check', 'dehydrate']); } catch { res.status(500).json({ error: '[Permix]: Instance not found. Please use the `setupMiddleware` function.' }); return null; } } function setupMiddleware(callback) { return async (req, res, next) => { req[permixSymbol] = createPermix$1(await callback({ req, res })); return next(); }; } function checkMiddleware(...params) { return async (req, res, next) => { const permix = getPermix(req, res); if (!permix) return; const hasPermission = permix.check(...params); if (!hasPermission) { await onForbidden({ req, res, ...createCheckContext(...params) }); return; } return next(); }; } function template(...params) { return createTemplate(...params); } return { setupMiddleware, checkMiddleware, template, get: getPermix }; } export { createPermix };