All files / node-user-accounts-boilerplate-nahid/helper access.js

100% Statements 16/16
100% Branches 13/13
100% Functions 3/3
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48    4x   4x         4x   11x   9x   2x               4x   35x   18x   16x   16x   10x   9x     7x 7x       2x        
"use strict";
 
const AUDIT_PERMISSION_ERROR = 'SESSION_PERMISSION_ERROR';
 
module.exports.AUDIT_PERMISSION_ERROR = AUDIT_PERMISSION_ERROR;
 
/**
 * Express middleware for blocking non-logged in users
 */
module.exports.LOGGEDIN = function (req, res, next)
{
  if (req.user)
  {
    return next();
  }
  res.error('Must be logged in', AUDIT_PERMISSION_ERROR);
};
 
/**
 * Express middleware generator for blocking non-logged in users or users that do not have one of the specified roles
 * @param {object} roles map of roles
 * @return {ExpressMiddlewareFunction}
 */
module.exports.ROLE_ONE_OF = function (roles)
{
  return function (req, res, next)
  {
    if (req.user)
    {
      let userRoles = req.user.roles || {};
 
      for (let role in userRoles)
      {
        if (userRoles[role] && roles[role])
        {
          return next();
        }
      }
      req.audit(AUDIT_PERMISSION_ERROR, 'MUST HAVE', JSON.stringify(roles), 'HAVE', JSON.stringify(req.user && req.user.roles || null));
      res.error('Must have access');
    }
    else
    {
      res.error('Must be logged in', AUDIT_PERMISSION_ERROR);
    }
  };
};