UNPKG

@foal/core

Version:

Full-featured Node.js framework, with no complexity

42 lines (41 loc) 1.72 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, openapi?: boolean }} [options={}] - Hook options. * @param {string|undefined} options.redirect - Optional URL path to redirect users that * do not have the right permission. * @param {boolean|undefined} options.openapi - Add OpenAPI metadata. * @returns {HookDecorator} - The hook. */ function PermissionRequired(perm, options = {}) { function 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(); } } const openapi = [ options.redirect ? (0, core_1.ApiResponse)(302, { description: 'Unauthenticated request.' }) : (0, core_1.ApiResponse)(401, { description: 'Unauthenticated request.' }), (0, core_1.ApiResponse)(403, { description: 'Permission denied.' }) ]; return (0, core_1.Hook)(hook, openapi, { openapi: options.openapi }); }