-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (73 loc) · 2.49 KB
/
index.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
const debug = require('debug')('sails-hook-rbac:index');
const RBAC = require('@luislobo/rbac2');
const {get} = require('lodash');
const flaverr = require('flaverr');
const defaults = require('./lib/defaults');
const initialize = require('./lib/initialize');
const getRbacRulesAndBeforeRoutes = require(
'./lib/getRbacRulesAndBeforeRoutes');
/**
* Sails Hook RBAC2
*
* @param {object} sails - Sails object
*/
module.exports = function(sails) {
let rbacInstance;
const {rbacRules, before} = getRbacRulesAndBeforeRoutes(sails);
return {
defaults,
configure: function() {
const hookConfig = sails.config[this.configKey];
// augment rules using the configuration in the hook as well as
// the ones that come from the routes
hookConfig.rbacRules = [
...hookConfig.rbacRules,
...rbacRules];
console.log(sails.config[this.configKey]);
},
initialize: (next) => {
sails.log.info('Initializing rbac hook...');
// Configure RBAC, check full path, cache trees
rbacInstance = new RBAC(
[...sails.config.rbac.rbacRules, ...rbacRules],
true,
true);
initialize(sails.hooks.rbac, sails, next);
},
routes: {
before,
},
rbacCheck(can, req, res, next) {
debug('rbacCheck', can);
const hookConfig = sails.config[this.configKey];
// Do we have a session object?
if (req[hookConfig.sessionObject]) {
// Set params for when
const whenParams = req.allParams();
whenParams[hookConfig.sessionObject] = req[hookConfig.sessionObject];
whenParams.body = req.body;
whenParams.req = req;
const role = get(req[hookConfig.sessionObject],
hookConfig.sessionObjectRolePath, 'role');
debug('rbacCheck:check', role, can,
req.method.toUpperCase(), req.route.path, whenParams);
rbacInstance.check(role, can, whenParams, (err, result) => {
if (err) {
debug('rbacCheck:err', 'evalAccess Error', err);
return next(flaverr('RBAC_ERROR', err));
} else if (result) {
debug('rbacCheck:passed');
return next(null, result);
}
debug('rbacCheck:resultEmpty', result);
return next(flaverr('FORBIDDEN',
new Error('Forbidden')));
});
} else {
debug('rbacCheck:noSessionObject');
return next(flaverr('RBAC_NO_SESSION', new Error('No session')));
}
},
};
};