forked from strongloop/loopback
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrole.js
393 lines (350 loc) · 11.6 KB
/
role.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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
var loopback = require('../../lib/loopback');
var debug = require('debug')('loopback:security:role');
var assert = require('assert');
var async = require('async');
var AccessContext = require('../../lib/access-context').AccessContext;
var RoleMapping = loopback.RoleMapping;
assert(RoleMapping, 'RoleMapping model must be defined before Role model');
/**
* The Role Model
* @class Role
*/
module.exports = function(Role) {
// Workaround for https://github.com/strongloop/loopback/issues/292
Role.definition.rawProperties.created.default =
Role.definition.properties.created.default = function() {
return new Date();
};
// Workaround for https://github.com/strongloop/loopback/issues/292
Role.definition.rawProperties.modified.default =
Role.definition.properties.modified.default = function() {
return new Date();
};
// Set up the connection to users/applications/roles once the model
Role.once('dataSourceAttached', function() {
var roleMappingModel = this.RoleMapping || loopback.getModelByType(RoleMapping);
Role.prototype.users = function(callback) {
roleMappingModel.find({where: {roleId: this.id,
principalType: RoleMapping.USER}}, function(err, mappings) {
if (err) {
if (callback) callback(err);
return;
}
return mappings.map(function(m) {
return m.principalId;
});
});
};
Role.prototype.applications = function(callback) {
roleMappingModel.find({where: {roleId: this.id,
principalType: RoleMapping.APPLICATION}}, function(err, mappings) {
if (err) {
if (callback) callback(err);
return;
}
return mappings.map(function(m) {
return m.principalId;
});
});
};
Role.prototype.roles = function(callback) {
roleMappingModel.find({where: {roleId: this.id,
principalType: RoleMapping.ROLE}}, function(err, mappings) {
if (err) {
if (callback) callback(err);
return;
}
return mappings.map(function(m) {
return m.principalId;
});
});
};
});
// Special roles
Role.OWNER = '$owner'; // owner of the object
Role.RELATED = '$related'; // any User with a relationship to the object
Role.AUTHENTICATED = '$authenticated'; // authenticated user
Role.UNAUTHENTICATED = '$unauthenticated'; // authenticated user
Role.EVERYONE = '$everyone'; // everyone
/**
* Add custom handler for roles.
* @param {String} role Name of role.
* @param {Function} resolver Function that determines if a principal is in the specified role.
* Signature must be `function(role, context, callback)`
*/
Role.registerResolver = function(role, resolver) {
if (!Role.resolvers) {
Role.resolvers = {};
}
Role.resolvers[role] = resolver;
};
Role.registerResolver(Role.OWNER, function(role, context, callback) {
if (!context || !context.model || !context.modelId) {
process.nextTick(function() {
if (callback) callback(null, false);
});
return;
}
var modelClass = context.model;
var modelId = context.modelId;
var userId = context.getUserId();
Role.isOwner(modelClass, modelId, userId, callback);
});
function isUserClass(modelClass) {
return modelClass === loopback.User ||
modelClass.prototype instanceof loopback.User;
}
/*!
* Check if two user ids matches
* @param {*} id1
* @param {*} id2
* @returns {boolean}
*/
function matches(id1, id2) {
if (id1 === undefined || id1 === null || id1 === ''
|| id2 === undefined || id2 === null || id2 === '') {
return false;
}
// The id can be a MongoDB ObjectID
return id1 === id2 || id1.toString() === id2.toString();
}
/**
* Check if a given user ID is the owner the model instance.
* @param {Function} modelClass The model class
* @param {*} modelId The model ID
* @param {*} userId The user ID
* @param {Function} callback Callback function
*/
Role.isOwner = function isOwner(modelClass, modelId, userId, callback) {
assert(modelClass, 'Model class is required');
debug('isOwner(): %s %s userId: %s', modelClass && modelClass.modelName, modelId, userId);
// No userId is present
if (!userId) {
process.nextTick(function() {
callback(null, false);
});
return;
}
// Is the modelClass User or a subclass of User?
if (isUserClass(modelClass)) {
process.nextTick(function() {
callback(null, matches(modelId, userId));
});
return;
}
modelClass.findById(modelId, function(err, inst) {
if (err || !inst) {
debug('Model not found for id %j', modelId);
if (callback) callback(err, false);
return;
}
debug('Model found: %j', inst);
var ownerId = inst.userId || inst.owner;
if (ownerId) {
if (callback) callback(null, matches(ownerId, userId));
return;
} else {
// Try to follow belongsTo
for (var r in modelClass.relations) {
var rel = modelClass.relations[r];
if (rel.type === 'belongsTo' && isUserClass(rel.modelTo)) {
debug('Checking relation %s to %s: %j', r, rel.modelTo.modelName, rel);
inst[r](processRelatedUser);
return;
}
}
debug('No matching belongsTo relation found for model %j and user: %j', modelId, userId);
if (callback) callback(null, false);
}
function processRelatedUser(err, user) {
if (!err && user) {
debug('User found: %j', user.id);
if (callback) callback(null, matches(user.id, userId));
} else {
if (callback) callback(err, false);
}
}
});
};
Role.registerResolver(Role.AUTHENTICATED, function(role, context, callback) {
if (!context) {
process.nextTick(function() {
if (callback) callback(null, false);
});
return;
}
Role.isAuthenticated(context, callback);
});
/**
* Check if the user id is authenticated
* @param {Object} context The security context
* @callback {Function} callback
* @param {Error} err
* @param {Boolean} isAuthenticated
*/
Role.isAuthenticated = function isAuthenticated(context, callback) {
process.nextTick(function() {
if (callback) callback(null, context.isAuthenticated());
});
};
Role.registerResolver(Role.UNAUTHENTICATED, function(role, context, callback) {
process.nextTick(function() {
if (callback) callback(null, !context || !context.isAuthenticated());
});
});
Role.registerResolver(Role.EVERYONE, function(role, context, callback) {
process.nextTick(function() {
if (callback) callback(null, true); // Always true
});
});
/**
* Check if a given principal is in the role
*
* @param {String} role The role name
* @param {Object} context The context object
* @callback {Function} callback
* @param {Error} err
* @param {Boolean} isInRole
*/
Role.isInRole = function(role, context, callback) {
if (!(context instanceof AccessContext)) {
context = new AccessContext(context);
}
debug('isInRole(): %s', role);
context.debug();
var resolver = Role.resolvers[role];
if (resolver) {
debug('Custom resolver found for role %s', role);
resolver(role, context, callback);
return;
}
if (context.principals.length === 0) {
debug('isInRole() returns: false');
process.nextTick(function() {
if (callback) callback(null, false);
});
return;
}
var inRole = context.principals.some(function(p) {
var principalType = p.type || undefined;
var principalId = p.id || undefined;
// Check if it's the same role
return principalType === RoleMapping.ROLE && principalId === role;
});
if (inRole) {
debug('isInRole() returns: %j', inRole);
process.nextTick(function() {
if (callback) callback(null, true);
});
return;
}
var roleMappingModel = this.RoleMapping || loopback.getModelByType(RoleMapping);
this.findOne({where: {name: role}}, function(err, result) {
if (err) {
if (callback) callback(err);
return;
}
if (!result) {
if (callback) callback(null, false);
return;
}
debug('Role found: %j', result);
// Iterate through the list of principals
async.some(context.principals, function(p, done) {
var principalType = p.type || undefined;
var principalId = p.id || undefined;
var roleId = result.id.toString();
if (principalId !== null && principalId !== undefined && (typeof principalId !== 'string')) {
principalId = principalId.toString();
}
if (principalType && principalId) {
roleMappingModel.findOne({where: {roleId: roleId,
principalType: principalType, principalId: principalId}},
function(err, result) {
debug('Role mapping found: %j', result);
done(!err && result); // The only arg is the result
});
} else {
process.nextTick(function() {
done(false);
});
}
}, function(inRole) {
debug('isInRole() returns: %j', inRole);
if (callback) callback(null, inRole);
});
});
};
/**
* List roles for a given principal
* @param {Object} context The security context
* @param {Function} callback
*
* @callback {Function} callback
* @param {Error=} err
* @param {String[]} roles An array of role ids
*/
Role.getRoles = function(context, callback) {
if (!(context instanceof AccessContext)) {
context = new AccessContext(context);
}
var roles = [];
var addRole = function(role) {
if (role && roles.indexOf(role) === -1) {
roles.push(role);
}
};
var self = this;
// Check against the smart roles
var inRoleTasks = [];
Object.keys(Role.resolvers).forEach(function(role) {
inRoleTasks.push(function(done) {
self.isInRole(role, context, function(err, inRole) {
if (debug.enabled) {
debug('In role %j: %j', role, inRole);
}
if (!err && inRole) {
addRole(role);
done();
} else {
done(err, null);
}
});
});
});
var roleMappingModel = this.RoleMapping || loopback.getModelByType(RoleMapping);
context.principals.forEach(function(p) {
// Check against the role mappings
var principalType = p.type || undefined;
var principalId = p.id == null ? undefined : p.id;
if (typeof principalId !== 'string' && principalId != null) {
principalId = principalId.toString();
}
// Add the role itself
if (principalType === RoleMapping.ROLE && principalId) {
addRole(principalId);
}
if (principalType && principalId) {
// Please find() treat undefined matches all values
inRoleTasks.push(function(done) {
roleMappingModel.find({where: {principalType: principalType,
principalId: principalId}}, function(err, mappings) {
debug('Role mappings found: %s %j', err, mappings);
if (err) {
if (done) done(err);
return;
}
mappings.forEach(function(m) {
addRole(m.roleId);
});
if (done) done();
});
});
}
});
async.parallel(inRoleTasks, function(err, results) {
debug('getRoles() returns: %j %j', err, roles);
if (callback) callback(err, roles);
});
};
};