UNPKG

@apolitical/server

Version:

Node.js module to encapsulate Apolitical's express server setup

39 lines (37 loc) 1.43 kB
'use strict'; module.exports = ({ serverError: { Forbidden }, config }) => { const { ADMIN_ROLE, MYSELF_SLUG } = config.MIDDLEWARES.PERMISSIONS; // Define external options return ({ myselfSource = null, myselfTarget = null, allowNonAdmin = false } = {}) => { // Return middleware handler return function handler(req, res, next) { let isNotAdmin = false; let isNotMyselfSlug = false; // Check user role (from JWT) if (!allowNonAdmin) { isNotAdmin = req.user && req.user.role !== ADMIN_ROLE; } // Check myself param if (myselfSource) { isNotMyselfSlug = req.params[myselfSource] !== MYSELF_SLUG; } // Check permissions and prevent unauthorised requests let unauthorised = false; if (!allowNonAdmin && !req.user) { unauthorised = true; } else if (!allowNonAdmin && isNotAdmin && isNotMyselfSlug) { unauthorised = true; } else if (!allowNonAdmin && isNotAdmin && !myselfSource) { unauthorised = true; } if (unauthorised) { return next(new Forbidden('Cannot authorise action', ['cookie-jwt', 'non-admin'])); } // Update myself slug with real slug (from JWT) if (myselfSource && myselfTarget && req.params[myselfSource] === MYSELF_SLUG) { Object.assign(req.params, { [myselfSource]: req.user[myselfTarget] }); } return next(); }; }; };