permix
Version:
Permix is a lightweight, framework-agnostic, type-safe permissions management library for JavaScript applications on the client and server sides.
72 lines (69 loc) • 1.82 kB
JavaScript
import { createMiddleware } from 'hono/factory';
import { HTTPException } from 'hono/http-exception';
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 Hono routes.
*
* @link https://permix.letstri.dev/docs/integrations/hono
*/
function createPermix({
onForbidden = ({
c
}) => c.json({
error: 'Forbidden'
}, 403)
} = {}) {
function getPermix(c) {
try {
const permix = c.get(permixSymbol);
if (!permix) {
throw new Error('Not found');
}
return pick(permix, ['check', 'dehydrate']);
} catch {
throw new HTTPException(500, {
message: '[Permix] Instance not found. Please use the `setupMiddleware` function.'
});
}
}
function setupMiddleware(callback) {
return createMiddleware(async (c, next) => {
c.set(permixSymbol, createPermix$1(await callback({
c
})));
await next();
});
}
function checkMiddleware(...params) {
return createMiddleware(async (c, next) => {
try {
const permix = getPermix(c);
const hasPermission = permix.check(...params);
if (!hasPermission) {
return await onForbidden({
c,
...createCheckContext(...params)
});
}
await next();
} catch {
return await onForbidden({
c,
...createCheckContext(...params)
});
}
});
}
function template(...params) {
return createTemplate(...params);
}
return {
setupMiddleware,
checkMiddleware,
template,
get: getPermix
};
}
export { createPermix };