-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathrole.js
666 lines (599 loc) · 22.7 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
// Copyright IBM Corp. 2014,2019. All Rights Reserved.
// Node module: loopback
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
const loopback = require('../../lib/loopback');
const debug = require('debug')('loopback:security:role');
const assert = require('assert');
const async = require('async');
const utils = require('../../lib/utils');
const ctx = require('../../lib/access-context');
const AccessContext = ctx.AccessContext;
const Principal = ctx.Principal;
const RoleMapping = loopback.RoleMapping;
assert(RoleMapping, 'RoleMapping model must be defined before Role model');
/**
* The Role model
* @class Role
* @header Role object
*/
module.exports = function(Role) {
Role.resolveRelatedModels = function() {
if (!this.userModel) {
const reg = this.registry;
this.roleMappingModel = reg.getModelByType('RoleMapping');
this.userModel = reg.getModelByType('User');
this.applicationModel = reg.getModelByType('Application');
}
};
// Set up the connection to users/applications/roles once the model
Role.once('dataSourceAttached', function(roleModel) {
['users', 'applications', 'roles'].forEach(function(rel) {
/**
* Fetch all users assigned to this role
* @function Role.prototype#users
* @param {object} [query] query object passed to model find call
* @callback {Function} [callback] The callback function
* @param {String|Error} err The error string or object
* @param {Array} list The list of users.
* @promise
*/
/**
* Fetch all applications assigned to this role
* @function Role.prototype#applications
* @param {object} [query] query object passed to model find call
* @callback {Function} [callback] The callback function
* @param {String|Error} err The error string or object
* @param {Array} list The list of applications.
* @promise
*/
/**
* Fetch all roles assigned to this role
* @function Role.prototype#roles
* @param {object} [query] query object passed to model find call
* @callback {Function} [callback] The callback function
* @param {String|Error} err The error string or object
* @param {Array} list The list of roles.
* @promise
*/
Role.prototype[rel] = function(query, callback) {
if (!callback) {
if (typeof query === 'function') {
callback = query;
query = {};
} else {
callback = utils.createPromiseCallback();
}
}
query = query || {};
query.where = query.where || {};
roleModel.resolveRelatedModels();
const relsToModels = {
users: roleModel.userModel,
applications: roleModel.applicationModel,
roles: roleModel,
};
const ACL = loopback.ACL;
const relsToTypes = {
users: ACL.USER,
applications: ACL.APP,
roles: ACL.ROLE,
};
let principalModel = relsToModels[rel];
let principalType = relsToTypes[rel];
// redefine user model and user type if user principalType is custom (available and not "USER")
const isCustomUserPrincipalType = rel === 'users' &&
query.where.principalType &&
query.where.principalType !== RoleMapping.USER;
if (isCustomUserPrincipalType) {
const registry = this.constructor.registry;
principalModel = registry.findModel(query.where.principalType);
principalType = query.where.principalType;
}
// make sure we don't keep principalType in userModel query
delete query.where.principalType;
if (principalModel) {
listByPrincipalType(this, principalModel, principalType, query, callback);
} else {
process.nextTick(function() {
callback(null, []);
});
}
return callback.promise;
};
});
/**
* Fetch all models assigned to this role
* @private
* @param {object} Context role context
* @param {*} model model type to fetch
* @param {String} [principalType] principalType used in the rolemapping for model
* @param {object} [query] query object passed to model find call
* @param {Function} [callback] callback function called with `(err, models)` arguments.
*/
function listByPrincipalType(context, model, principalType, query, callback) {
if (callback === undefined && typeof query === 'function') {
callback = query;
query = {};
}
query = query || {};
roleModel.roleMappingModel.find({
where: {roleId: context.id, principalType: principalType},
}, function(err, mappings) {
if (err) {
return callback(err);
}
const ids = mappings.map(function(m) {
return m.principalId;
});
query.where = query.where || {};
query.where.id = {inq: ids};
model.find(query, function(err, models) {
callback(err, models);
});
});
}
});
// 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.
* Should provide a callback or return a promise.
*/
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;
}
const modelClass = context.model;
const modelId = context.modelId;
const user = context.getUser();
const userId = user && user.id;
const principalType = user && user.principalType;
const opts = {accessToken: context.accessToken};
Role.isOwner(modelClass, modelId, userId, principalType, opts, callback);
});
function isUserClass(modelClass) {
if (!modelClass) return false;
const User = modelClass.modelBuilder.models.User;
if (!User) return false;
return modelClass == User || modelClass.prototype instanceof 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 {String} principalType The user principalType (optional)
* @options {Object} options
* @property {accessToken} The access token used to authorize the current user.
* @callback {Function} [callback] The callback function
* @param {String|Error} err The error string or object
* @param {Boolean} isOwner True if the user is an owner.
* @promise
*/
Role.isOwner = function isOwner(modelClass, modelId, userId, principalType, options, callback) {
const _this = this;
if (!callback && typeof options === 'function') {
callback = options;
options = {};
} else if (!callback && typeof principalType === 'function') {
callback = principalType;
principalType = undefined;
options = {};
}
principalType = principalType || Principal.USER;
assert(modelClass, 'Model class is required');
if (!callback) callback = utils.createPromiseCallback();
debug('isOwner(): %s %s userId: %s principalType: %s',
modelClass && modelClass.modelName, modelId, userId, principalType);
// Resolve isOwner false if userId is missing
if (!userId) {
debug('isOwner(): no user id was set, returning false');
process.nextTick(function() {
callback(null, false);
});
return callback.promise;
}
// At this stage, principalType is valid in one of 2 following condition:
// 1. the app has a single user model and principalType is 'USER'
// 2. the app has multiple user models and principalType is not 'USER'
// multiple user models
const isMultipleUsers = _isMultipleUsers();
const isPrincipalTypeValid =
(!isMultipleUsers && principalType === Principal.USER) ||
(isMultipleUsers && principalType !== Principal.USER);
debug('isOwner(): isMultipleUsers?', isMultipleUsers,
'isPrincipalTypeValid?', isPrincipalTypeValid);
// Resolve isOwner false if principalType is invalid
if (!isPrincipalTypeValid) {
process.nextTick(function() {
callback(null, false);
});
return callback.promise;
}
// Is the modelClass User or a subclass of User?
if (isUserClass(modelClass)) {
const userModelName = modelClass.modelName;
// matching ids is enough if principalType is USER or matches given user model name
if (principalType === Principal.USER || principalType === userModelName) {
process.nextTick(function() {
callback(null, matches(modelId, userId));
});
return callback.promise;
}
// otherwise continue with the regular owner resolution
}
modelClass.findById(modelId, options, function(err, inst) {
if (err || !inst) {
debug('Model not found for id %j', modelId);
return callback(err, false);
}
debug('Model found: %j', inst);
const ownerRelations = modelClass.settings.ownerRelations;
if (!ownerRelations) {
return legacyOwnershipCheck(inst);
} else {
return checkOwnership(inst);
}
});
return callback.promise;
// NOTE Historically, for principalType USER, we were resolving isOwner()
// as true if the model has "userId" or "owner" property matching
// id of the current user (principalId), even though there was no
// belongsTo relation set up.
// Additionaly, the original implementation did not support the
// possibility for a model to have multiple related users: when
// testing belongsTo relations, the first related user failing the
// ownership check induced the whole isOwner() to resolve as false.
// This behaviour will be pruned at next LoopBack major release.
function legacyOwnershipCheck(inst) {
const ownerId = inst.userId || inst.owner;
if (principalType === Principal.USER && ownerId && 'function' !== typeof ownerId) {
return callback(null, matches(ownerId, userId));
}
// Try to follow belongsTo
for (const r in modelClass.relations) {
const rel = modelClass.relations[r];
// relation should be belongsTo and target a User based class
const belongsToUser = rel.type === 'belongsTo' && isUserClass(rel.modelTo);
if (!belongsToUser) {
continue;
}
// checking related user
const relatedUser = rel.modelTo;
const userModelName = relatedUser.modelName;
const isMultipleUsers = _isMultipleUsers(relatedUser);
// a relation can be considered for isOwner resolution if:
// 1. the app has a single user model and principalType is 'USER'
// 2. the app has multiple user models and principalType is the related user model name
if ((!isMultipleUsers && principalType === Principal.USER) ||
(isMultipleUsers && principalType === userModelName)) {
debug('Checking relation %s to %s: %j', r, userModelName, rel);
inst[r](processRelatedUser);
return;
}
}
debug('No matching belongsTo relation found for model %j - user %j principalType %j',
modelId, userId, principalType);
callback(null, false);
function processRelatedUser(err, user) {
if (err || !user) return callback(err, false);
debug('User found: %j', user.id);
callback(null, matches(user.id, userId));
}
}
function checkOwnership(inst) {
const ownerRelations = inst.constructor.settings.ownerRelations;
// collecting related users
const relWithUsers = [];
for (const r in modelClass.relations) {
const rel = modelClass.relations[r];
// relation should be belongsTo and target a User based class
if (rel.type !== 'belongsTo' || !isUserClass(rel.modelTo)) {
continue;
}
// checking related user
const relatedUser = rel.modelTo;
const userModelName = relatedUser.modelName;
const isMultipleUsers = _isMultipleUsers(relatedUser);
// a relation can be considered for isOwner resolution if:
// 1. the app has a single user model and principalType is 'USER'
// 2. the app has multiple user models and principalType is the related user model name
// In addition, if an array of relations if provided with the ownerRelations option,
// then the given relation name is further checked against this array
if ((!isMultipleUsers && principalType === Principal.USER) ||
(isMultipleUsers && principalType === userModelName)) {
debug('Checking relation %s to %s: %j', r, userModelName, rel);
if (ownerRelations === true) {
relWithUsers.push(r);
} else if (Array.isArray(ownerRelations) && ownerRelations.indexOf(r) !== -1) {
relWithUsers.push(r);
}
}
}
if (relWithUsers.length === 0) {
debug('No matching belongsTo relation found for model %j and user: %j principalType: %j',
modelId, userId, principalType);
return callback(null, false);
}
// check related users: someSeries is used to avoid spamming the db
async.someSeries(relWithUsers, processRelation, callback);
function processRelation(r, cb) {
inst[r](function processRelatedUser(err, user) {
if (err || !user) return cb(err, false);
debug('User found: %j (through %j)', user.id, r);
cb(null, matches(user.id, userId));
});
}
}
// A helper function to check if the app user config is multiple users or
// single user. It can be used with or without a reference user model.
// In case no user model is provided, we use the registry to get any of the
// user model by type. The relation with AccessToken is used to check
// if polymorphism is used, and thus if multiple users.
function _isMultipleUsers(userModel) {
const oneOfUserModels = userModel || _this.registry.getModelByType('User');
const accessTokensRel = oneOfUserModels.relations.accessTokens;
return !!(accessTokensRel && accessTokensRel.polymorphic);
}
};
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 Callback function.
* @param {Error} err Error object.
* @param {Boolean} isAuthenticated True if the user is authenticated.
* @promise
*/
Role.isAuthenticated = function isAuthenticated(context, callback) {
if (!callback) callback = utils.createPromiseCallback();
process.nextTick(function() {
if (callback) callback(null, context.isAuthenticated());
});
return callback.promise;
};
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 specified role.
*
* @param {String} role The role name.
* @param {Object} context The context object.
*
* @callback {Function} callback Callback function.
* @param {Error} err Error object.
* @param {Boolean} isInRole True if the principal is in the specified role.
* @promise
*/
Role.isInRole = function(role, context, callback) {
context.registry = this.registry;
if (!(context instanceof AccessContext)) {
context = new AccessContext(context);
}
if (!callback) {
callback = utils.createPromiseCallback();
// historically, isInRole is returning the Role instance instead of true
// we are preserving that behaviour for callback-based invocation,
// but fixing it when invoked in Promise mode
callback.promise = callback.promise.then(function(isInRole) {
return !!isInRole;
});
}
this.resolveRelatedModels();
debug('isInRole(): %s', role);
context.debug();
const resolver = Role.resolvers[role];
if (resolver) {
debug('Custom resolver found for role %s', role);
const promise = resolver(role, context, callback);
if (promise && typeof promise.then === 'function') {
promise.then(
function(result) { callback(null, result); },
callback,
);
}
return callback.promise;
}
if (context.principals.length === 0) {
debug('isInRole() returns: false');
process.nextTick(function() {
if (callback) callback(null, false);
});
return callback.promise;
}
const inRole = context.principals.some(function(p) {
const principalType = p.type || undefined;
const 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 callback.promise;
}
const roleMappingModel = this.roleMappingModel;
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) {
const principalType = p.type || undefined;
let principalId = p.id || undefined;
const roleId = result.id.toString();
const principalIdIsString = typeof principalId === 'string';
if (principalId !== null && principalId !== undefined && !principalIdIsString) {
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);
});
});
return callback.promise;
};
/**
* List roles for a given principal.
* @param {Object} context The security context.
*
* @callback {Function} callback Callback function.
* @param {Error} err Error object.
* @param {String[]} roles An array of role IDs
* @promise
*/
Role.getRoles = function(context, options, callback) {
if (!callback) {
if (typeof options === 'function') {
callback = options;
options = {};
} else {
callback = utils.createPromiseCallback();
}
}
if (!options) options = {};
context.registry = this.registry;
if (!(context instanceof AccessContext)) {
context = new AccessContext(context);
}
const roles = [];
this.resolveRelatedModels();
const addRole = function(role) {
if (role && roles.indexOf(role) === -1) {
roles.push(role);
}
};
const self = this;
// Check against the smart roles
const 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);
}
});
});
});
const roleMappingModel = this.roleMappingModel;
context.principals.forEach(function(p) {
// Check against the role mappings
const principalType = p.type || undefined;
let 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) {
const filter = {where: {principalType: principalType, principalId: principalId}};
if (options.returnOnlyRoleNames === true) {
filter.include = ['role'];
}
roleMappingModel.find(filter, function(err, mappings) {
debug('Role mappings found: %s %j', err, mappings);
if (err) {
if (done) done(err);
return;
}
mappings.forEach(function(m) {
let role;
if (options.returnOnlyRoleNames === true) {
role = m.toJSON().role.name;
} else {
role = m.roleId;
}
addRole(role);
});
if (done) done();
});
});
}
});
async.parallel(inRoleTasks, function(err, results) {
debug('getRoles() returns: %j %j', err, roles);
if (callback) callback(err, roles);
});
return callback.promise;
};
Role.validatesUniquenessOf('name', {message: 'already exists'});
};