-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
329 lines (300 loc) · 9.52 KB
/
index.js
File metadata and controls
329 lines (300 loc) · 9.52 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
'use strict';
var http = require('http');
var castArray = require('lodash/castArray');
var defaults = require('lodash/defaults');
var extend = require('lodash/extend');
var forOwn = require('lodash/forOwn');
var result = require('lodash/result');
var zipObject = require('lodash/zipObject');
var createError = require('http-errors');
// options = {
// defaultRoleName: string
// }
var RolePlay = module.exports = function RolePlay( options ) {
this.options = options = defaults(options, {
defaultError : 'Not authorized',
defaultRoleName : 'default'
});
this.roles = {};
this.defaultRole = new this.constructor.Role(this, options.defaultRoleName);
this.roles[this.defaultRole.name] = this.defaultRole;
};
RolePlay.Role = Role;
RolePlay.Play = Play;
extend(RolePlay.prototype, {
options : undefined,
defaultRole : undefined,
roles : undefined,
// Express middleware
// ------------------
// Checks permission for the current user, and produces a 403 error when
// access is denied. Passing multiple action is possible; by default only
// the first action is required to be allowed for the request to succeed.
// All consecutive actions are optional. Passing `true` as the last argument
// makes all actions optional.
//
// `req.user` must be set before this middleware runs. For permissions that
// require a resource, `req.resource` must be set as well.
//
// Adds `res.locals.can` as `function(actionName)` to check for the passed
// permissions in template views.
can: function( /* actionName [, actionName...] [, allOptional] */ ) {
var self = this;
var actionNames_raw = Array.from(arguments);
var lastArg = actionNames_raw[actionNames_raw.length-1];
var allOptional = typeof lastArg === 'boolean' ?
actionNames_raw.pop() :
false;
var actionNames = this._getCanonicalActionNames(actionNames_raw);
return function( req, res, next ) {
var user = self._createUserObject(req.user);
var allowed = actionNames.map(function( actionName ) {
return user.can(actionName, req);
});
// Add `can(actionName)` function to locals, so the passed
// permission can be checked in the template as well.
var actions = zipObject(actionNames, allowed);
self._addHelperFunction(req, res, actions);
if( allOptional || allowed[0] ) {
next();
} else {
var action = user.get(actionNames[0]);
var errorMessage = result(action, 'message') || self.options.defaultError;
var error = self._createError(user, errorMessage);
next(error);
}
}
},
role: function( roleName ) {
var role;
if( roleName instanceof Role ) {
role = roleName;
roleName = role.name;
}
if( this.roles[roleName] ) {
if( role && this.roles[roleName] !== role ) {
throw createError(500, 'Duplicate role: '+roleName);
}
return this.roles[roleName];
} else {
if( !role ) {
role = this.defaultRole.role(roleName);
} else if( role.mgr != this ) {
throw createError(500, 'Role already in use');
}
return this.roles[roleName] = role;
}
},
gatherAction: function( actionName, roleName ) {
var result = undefined;
var role = this.roles[roleName];
var action;
if( !role ) {
throw createError(500, 'Role not found: '+roleName);
} else if( !this.defaultRole.action(actionName) ) {
throw createError(500, 'Action not defined on default role: '+actionName);
}
while( role ) {
if( action = role.action(actionName) ) {
result = defaults(result || {}, action);
}
role = role.inherits;
}
return result;
},
// Used by `can` to assign a helper function to `req.can` and `res.locals.can`.
_addHelperFunction: function( req, res, actions ) {
var locals = res.locals;
if( locals.can ) {
extend(locals.can.actions, actions);
} else {
// Passing multiple action names means `OR`.
req.can = locals.can = function can( actionName /* [, actionName...] */ ) {
if( !(actionName in can.actions) ) {
throw createError(500, 'RolePlay action not available for this route: '+actionName);
}
var len = arguments.length;
for( var i=0; i<len; i++ ) {
if( can.actions[arguments[i]] ) return true;
}
return false;
};
locals.can.actions = actions;
}
},
_createError: function( user, errorMessage ) {
return user.user ?
createError(403, errorMessage) :
createError(401, this.options.defaultError);
},
_createUserObject: function( user ) {
return new this.constructor.Play(this, user);
},
// Used by `can` to expand action names like `entity:*` to a list of fully
// qualified action names (e.g.: `entity:edit`, `entity:create` etc);
_getCanonicalActionNames: function( actionNames ) {
var role = this.defaultRole;
var canonical = new Set;
for( let actionName of actionNames ) {
if( ~String(actionName).indexOf('*') ) {
let sourceName = actionName.split(':');
for( let actionName of Object.keys(role.actions) ) {
let targetName = actionName.split(':');
let i = 0, part;
while( part = targetName.shift() ) {
if( sourceName[i] != '*' && sourceName[i] != part ) {
break;
}
i++;
}
if( i == sourceName.length ) {
canonical.add(actionName);
}
}
} else {
canonical.add(actionName);
}
}
return Array.from(canonical);
}
});
function Role( mgr, roleName ) {
this.mgr = mgr;
this.name = roleName;
this.actions = {};
}
extend(Role.prototype, {
mgr : undefined,
name : undefined,
actions : undefined,
inherits : undefined,
role: function( roleName ) {
var role = new this.constructor(this.mgr, roleName);
role.inherits = this;
return this.mgr.role(role);
},
// def = boolean || allowFunction || {
// allow : boolean || function(user[, resource], actionName) { return boolean },
// [resource : name || [name, ...] || function( mixed ) { return resource }],
// [message : string]
// }
//
// If `resource` is an array of strings, the `allow` function will receive
// a resource object where the string values from the array are properties
// on the object with the corresponding resource as value.
action: function( actionName, def ) {
var action;
// This call is a getter, or it's an object of action definitions.
if( arguments.length === 1 ) {
if( typeof actionName === 'object' ) {
forOwn(actionName, function( def, actionName ) {
this.action(actionName, def);
}.bind(this));
return this;
} else {
// Get action.
if( typeof actionName !== 'string' ) {
throw createError(500, 'Incorrect action name: '+actionName);
}
action = this.actions[actionName];
if( !action ) {
var parts = actionName.split(':');
while( !action && parts.pop() ) {
action = this.actions[parts.join(':')+':*'];
}
}
return action || this.actions['*'];
}
}
var resource, allow, message;
if( def instanceof Object && def.constructor === Object ) {
resource = def.resource;
allow = def.allow;
message = def.message;
} else {
allow = def;
}
if( this.actions[actionName] ) {
throw createError(500, 'Action already defined: '+actionName);
}
if( typeof allow !== 'function' ) {
allow = this._createAllowFunction(allow);
}
if( resource && typeof resource !== 'function' ) {
resource = this._createResourceFunction(resource);
}
action = this.actions[actionName] = {
name : actionName,
resource : resource,
allow : allow,
message : message
};
return this;
},
_createAllowFunction: function( allowValue ) {
return function() { return !!allowValue };
},
_createResourceFunction: function( resourceDef ) {
function get( input, resourceName ) {
var resource = arguments.length > 1 ?
input && input[resourceName] :
input;
if( resource == undefined ) {
resourceName = resourceName ? '\''+resourceName+'\'' : '';
throw createError(500, 'Action \''+this.name+'\' missing resource '+resourceName);
}
return resource;
}
return function( input /* [, input...] */ ) {
var len = arguments.length;
if( len > 1 ) {
if( !Array.isArray(resourceDef) || len != resourceDef.length ) {
throw createError(500, 'Action \''+this.name+'\' missing resource');
}
var resources = [];
for( let i=0; i<len; i++ ) {
resources.push(arguments[i]);
}
return resources;
} else if(
input instanceof http.IncomingMessage ||
Array.isArray(resourceDef)
) {
return castArray(resourceDef).map(get.bind(this, input));
} else {
return [get.call(this, input)];
}
};
}
});
function Play( mgr, user ) {
this.mgr = mgr;
this.user = user;
this.roleName = this._getUserRoleName(user);
}
extend(Play.prototype, {
mgr : undefined,
user : undefined,
role : undefined,
resource : undefined,
can: function( actionName /* [, resource...] */ ) {
var action = this.get(actionName);
if( !action ) {
throw createError(500, 'Action not found: '+actionName);
}
if( action.resource ) {
var resourceArgs = Array.prototype.slice.call(arguments, 1);
var resources = action.resource.apply(action, resourceArgs);
var allowArgs = [this.user].concat(resources, actionName);
return action.allow.apply(action, allowArgs);
} else {
return action.allow(this.user, actionName);
}
},
get: function( actionName ) {
return this.mgr.gatherAction(actionName, this.roleName);
},
_getUserRoleName: function( user ) {
return (user && user.role) || this.mgr.options.defaultRoleName;
}
});