UNPKG

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