UNPKG

@foal/core

Version:

Full-featured Node.js framework, with no complexity

34 lines (33 loc) 1.26 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PermissionRequired = PermissionRequired; // 3p const core_1 = require("../../../core"); /** * Hook factory to check if a user can access a route based on their permissions. * * The `ctx.user` object must implement the `IUserWithPermissions` interface. * * @export * @param {string} perm - The name of the permission. * @param {{ redirect?: string }} [options={}] - Hook options. * @param {string|undefined} options.redirect - Optional URL path to redirect users that * do not have the right permission. * @returns {HookDecorator} - The hook. */ function PermissionRequired(perm, options = {}) { return (0, core_1.Hook)((ctx) => { if (!ctx.user) { if (options.redirect) { return new core_1.HttpResponseRedirect(options.redirect); } return new core_1.HttpResponseUnauthorized(); } if (typeof ctx.user.hasPerm !== 'function') { throw new Error('ctx.user does not have a "hasPerm" method. Are you sure it implements the IUserWithPermissions interface?'); } if (!ctx.user.hasPerm(perm)) { return new core_1.HttpResponseForbidden(); } }); }