-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathutils.js
558 lines (481 loc) · 18.5 KB
/
utils.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
'use strict'
const debug = require('debug')('loopback:component:access')
const { createPromiseCallback } = require('loopback-datasource-juggler/lib/utils')
const _defaults = require('lodash').defaults
const _get = require('lodash').get
const _set = require('lodash').set
const Promise = require('bluebird')
const LoopBackContext = require('loopback-context')
module.exports = class AccessUtils {
constructor(app, options) {
this.app = app
this.options = _defaults({ }, options, {
userModel: 'User',
roleModel: 'Role',
groupAccessModel: 'GroupAccess',
groupModel: 'Group',
foreignKey: 'groupId',
groupRoles: [
'$group:admin',
'$group:member',
],
applyToStatic: false,
})
// Default the foreignKey to the group model name + Id.
this.options.foreignKey = this.options.foreignKey || `${this.options.groupModel.toLowerCase()}Id`
// Validate the format of options.groupRoles ($group:[role]).
this.options.groupRoles.forEach(name => {
if (!this.isValidPrincipalId(name)) {
throw new Error('$name is an invalid access group name.')
}
})
// Save the component config for easy reference.
app.set('loopback-component-access-groups', options)
debug('options: %o', options)
}
/**
* Register a custom remoting phase to make the current user details available from remoting contexts.
*/
setupRemotingPhase() {
this.app.remotes().phases
.addBefore('invoke', 'options-from-request')
.use((ctx, next) => {
if (!_get(ctx, 'args.options.accessToken')) {
return next()
}
_set(ctx, 'args.options.currentUser', this.getCurrentUser())
_set(ctx, 'args.options.currentUserGroups', this.getCurrentUserGroups())
return next()
})
}
/**
* Register a dynamic role resolver for each defined access group.
*/
setupRoleResolvers() {
this.options.groupRoles.forEach(accessGroup => {
this.setupRoleResolver(accessGroup)
})
}
/**
* Add operation hooks to limit access.
*/
setupFilters() {
const models = [ this.options.groupModel ].concat(this.getGroupContentModels())
models.forEach(modelName => {
const Model = this.app.models[modelName]
if (typeof Model.observe === 'function') {
debug('Attaching access observer to %s', modelName)
Model.observe('access', (ctx, next) => {
const currentUser = this.getCurrentUser()
if (currentUser) {
// Do not filter if options.skipAccess has been set.
if (ctx.options.skipAccess) {
debug('skipAccess: true - skipping access filters')
return next()
}
// Do not filter if the request is being made against a single model instance.
if (_get(ctx.query, 'where.id')) {
debug('looking up by Id - skipping access filters')
return next()
}
// Do not apply filters if no group access acls were applied.
const loopbackContext = LoopBackContext.getCurrentContext({ bind: true })
const groupAccessApplied = Boolean(loopbackContext && loopbackContext.get('groupAccessApplied'))
if (!groupAccessApplied) {
debug('acls not appled - skipping access filters')
return next()
}
debug('%s observe access: query=%s, options=%o, hookState=%o',
Model.modelName, JSON.stringify(ctx.query, null, 4), ctx.options, ctx.hookState)
return this.buildFilter(currentUser.getId(), ctx.Model)
.then(filter => {
debug('original query: %o', JSON.stringify(ctx.query, null, 4))
const where = ctx.query.where ? {
and: [ ctx.query.where, filter ],
} : filter
ctx.query.where = where
debug('modified query: %s', JSON.stringify(ctx.query, null, 4))
})
}
return next()
})
}
})
}
/**
* Build a where filter to restrict search results to a users group
*
* @param {String} userId UserId to build filter for.
* @param {Object} Model Model to build filter for,
* @returns {Object} A where filter.
*/
buildFilter(userId, Model) {
const filter = { }
const key = this.isGroupModel(Model) ? Model.getIdName() : this.options.foreignKey
// TODO: Support key determination based on the belongsTo relationship.
return this.getUserGroups(userId)
.then(userGroups => {
userGroups = Array.from(userGroups, group => group[this.options.foreignKey])
filter[key] = { inq: userGroups }
return filter
})
}
/**
* Check if a model class is the configured group model.
*
* @param {String|Object} modelClass Model class to check.
* @returns {Boolean} Returns true if the principalId is on the expected format.
*/
isGroupModel(modelClass) {
if (modelClass) {
const groupModel = this.app.models[this.options.groupModel]
return modelClass === groupModel ||
modelClass.prototype instanceof groupModel ||
modelClass === this.options.groupModel
}
return false
}
/**
* Check if a model class is the configured group access model.
*
* @param {String|Object} modelClass Model class to check.
* @returns {Boolean} Returns true if the principalId is on the expected format.
*/
isGroupAccessModel(modelClass) {
if (modelClass) {
const groupAccessModel = this.app.models[this.options.groupAccessModel]
return modelClass === groupAccessModel ||
modelClass.prototype instanceof groupAccessModel ||
modelClass === this.options.groupAccessModel
}
return false
}
/**
* Get a list of group content models (models that have a belongs to relationship to the group model)
*
* @returns {Array} Returns a list of group content models.
*/
getGroupContentModels() {
const models = [ ]
Object.keys(this.app.models).forEach(modelName => {
const modelClass = this.app.models[modelName]
// Mark the group itself as a group or the group access model.
if (this.isGroupModel(modelClass) || this.isGroupAccessModel(modelClass)) {
return
}
// Try to follow belongsTo
for (let rel in modelClass.relations) {
rel = _get(modelClass, `relations.${rel}`)
// debug('Checking relation %s to %s: %j', r, rel.modelTo.modelName, rel);
if (rel.type === 'belongsTo' && this.isGroupModel(rel.modelTo)) {
models.push(modelName)
}
}
})
debug('Got group content models: %o', models)
return models
}
/**
* Get the access groups for a given user.
*
* @param {String} userId UserId to fetch access groups for.
* @param {Boolean} force Boolean indicating wether to bypass the cache if it exists.
* @param {Function} [cb] A callback function.
* @returns {Boolean} Returns true if the principalId is on the expected format.
*/
getUserGroups(userId, force, cb) {
force = force || false
cb = cb || createPromiseCallback()
const currentUser = this.getCurrentUser()
const currentUserGroups = this.getCurrentUserGroups()
// Return from the context cache if exists.
if (!force && currentUser && currentUser.getId() === userId) {
debug('getUserGroups returning from cache: %o', currentUserGroups)
process.nextTick(() => cb(null, currentUserGroups))
return cb.promise
}
// Otherwise lookup from the datastore.
this.app.models[this.options.groupAccessModel].find({
where: {
userId,
},
})
.then(groups => {
debug('getUserGroups returning from datastore: %o', currentUserGroups)
cb(null, groups)
})
.catch(cb)
return cb.promise
}
/**
* Get the currently logged in user.
*
* @returns {Object} Returns the currently logged in user.
*/
getCurrentUser() {
const ctx = LoopBackContext.getCurrentContext({ bind: true })
const currentUser = (ctx && ctx.get('currentUser')) || null
return currentUser
}
/**
* Get the currently logged in user's access groups from the current request cache.
*
* @returns {Array} Returnds a list of access groups the user is a member of.
*/
getCurrentUserGroups() {
const ctx = LoopBackContext.getCurrentContext({ bind: true })
const currentUserGroups = (ctx && ctx.get('currentUserGroups')) || []
return currentUserGroups
}
/**
* Valid that a principalId conforms to the expected format.
*
* @param {String} principalId A principalId.
* @returns {Boolean} Returns true if the principalId is on the expected format.
*/
isValidPrincipalId(principalId) {
return Boolean(this.extractRoleName(principalId))
}
/**
* Extract the role name from a principalId (eg, for '$group:admin' the role name is 'admin').
*
* @param {String} principalId A principalId.
* @returns {Boolean} Returns true if the principalId is on the expected format.
*/
extractRoleName(principalId) {
return principalId.split(':')[1]
}
/**
* Register a dynamic role resolver for an access group.
*
* @param {String} accessGroup Name of the access group to be setup.
*/
setupRoleResolver(accessGroup) {
debug(`Registering role resolver for ${accessGroup}`)
const Role = this.app.models[this.options.roleModel]
Role.registerResolver(accessGroup, (role, context, cb) => {
cb = cb || createPromiseCallback()
const modelClass = context.model
const { modelId } = context
const userId = context.getUserId()
const roleName = this.extractRoleName(role)
const GroupAccess = this.app.models[this.options.groupAccessModel]
const scope = { }
debug(`Role resolver for ${role}: evaluate ${modelClass.modelName} with id: ${modelId} for user: ${userId}`)
// No userId is present
if (!userId) {
process.nextTick(() => {
debug('Deny access for anonymous user')
cb(null, false)
})
return cb.promise
}
LoopBackContext.getCurrentContext({ bind: true }).set('groupAccessApplied', true)
/**
* Basic application that does not cover static methods. Similar to $owner. (RECOMMENDED)
*/
if (!this.options.applyToStatic) {
if (!context || !modelClass || !modelId) {
process.nextTick(() => {
debug('Deny access (context: %s, context.model: %s, context.modelId: %s)',
Boolean(context), Boolean(modelClass), Boolean(modelId))
cb(null, false)
})
return cb.promise
}
this.isGroupMemberWithRole(modelClass, modelId, userId, roleName)
.then(res => cb(null, res))
.catch(cb)
return cb.promise
}
/**
* More complex application that also covers static methods. (EXPERIMENTAL)
*/
Promise.join(this.getCurrentGroupId(context), this.getTargetGroupId(context),
(currentGroupId, targetGroupId) => {
if (!currentGroupId) {
// TODO: Use promise cancellation to abort the chain early.
// Causes the access check to be bypassed (see below).
return [ false ]
}
scope.currentGroupId = currentGroupId
scope.targetGroupId = targetGroupId
const actions = [ ]
const conditions = { userId, role: roleName }
conditions[this.options.foreignKey] = currentGroupId
actions.push(GroupAccess.count(conditions))
// If this is an attempt to save the item into a new group, check the user has access to the target group.
if (targetGroupId && targetGroupId !== currentGroupId) {
conditions[this.options.foreignKey] = targetGroupId
actions.push(GroupAccess.count(conditions))
}
return actions
})
.spread((currentGroupCount, targetGroupCount) => {
let res = false
if (currentGroupCount === false) {
// No group context was determined, so allow passthrough access.
res = true
}
else {
// Determine grant based on the current/target group context.
res = currentGroupCount > 0
debug(`user ${userId} ${res ? 'is a' : 'is not a'} ${roleName} of group ${scope.currentGroupId}`)
// If it's an attempt to save into a new group, also ensure the user has access to the target group.
if (scope.targetGroupId && scope.targetGroupId !== scope.currentGroupId) {
const tMember = targetGroupCount > 0
debug(`user ${userId} ${tMember ? 'is a' : 'is not a'} ${roleName} of group ${scope.targetGroupId}`)
res = res && tMember
}
}
// Note the fact that we are allowing access due to passing an ACL.
if (res) {
LoopBackContext.getCurrentContext({ bind: true }).set('groupAccessApplied', true)
}
return cb(null, res)
})
.catch(cb)
return cb.promise
})
}
/**
* Check if a given user ID has a given role in the model instances group.
* @param {Function} modelClass The model class
* @param {*} modelId The model ID
* @param {*} userId The user ID
* @param {*} roleId The role ID
* @param {Function} callback Callback function
*/
isGroupMemberWithRole(modelClass, modelId, userId, roleId, cb) {
cb = cb || createPromiseCallback()
debug('isGroupMemberWithRole: modelClass: %o, modelId: %o, userId: %o, roleId: %o',
modelClass && modelClass.modelName, modelId, userId, roleId)
// No userId is present
if (!userId) {
process.nextTick(() => {
cb(null, false)
})
return cb.promise
}
// Is the modelClass GroupModel or a subclass of GroupModel?
if (this.isGroupModel(modelClass)) {
debug('Access to Group Model %s attempted', modelId)
this.hasRoleInGroup(userId, roleId, modelId)
.then(res => cb(null, res))
return cb.promise
}
modelClass.findById(modelId, (err, inst) => {
if (err || !inst) {
debug('Model not found for id %j', modelId)
return cb(err, false)
}
debug('Model found: %j', inst)
const groupId = inst[this.options.foreignKey]
// Ensure groupId exists and is not a function/relation
if (groupId && typeof groupId !== 'function') {
return this.hasRoleInGroup(userId, roleId, groupId)
.then(res => cb(null, res))
}
// Try to follow belongsTo
for (const relName in modelClass.relations) {
const rel = modelClass.relations[relName]
if (rel.type === 'belongsTo' && this.isGroupModel(rel.modelTo)) {
debug('Checking relation %s to %s: %j', relName, rel.modelTo.modelName, rel)
return inst[relName](function processRelatedGroup(error, group) {
if (!error && group) {
debug('Group found: %j', group.getId())
return cb(null, this.hasRoleInGroup(userId, roleId, group.getId()))
}
return cb(error, false)
})
}
}
debug('No matching belongsTo relation found for model %j and group: %j', modelId, groupId)
return cb(null, false)
})
return cb.promise
}
hasRoleInGroup(userId, role, group, cb) {
debug('hasRoleInGroup: role: %o, group: %o, userId: %o', role, group, userId)
cb = cb || createPromiseCallback()
const GroupAccess = this.app.models[this.options.groupAccessModel]
const conditions = { userId, role }
conditions[this.options.foreignKey] = group
GroupAccess.count(conditions)
.then(count => {
const res = count > 0
debug(`User ${userId} ${res ? 'HAS' : 'DOESNT HAVE'} ${role} role in group ${group}`)
cb(null, res)
})
return cb.promise
}
/**
* Determine the current Group Id based on the current security context.
*
* @param {Object} context The security context.
* @param {function} [cb] A callback function.
* @returns {Object} Returns the determined Group ID.
*/
getCurrentGroupId(context, cb) {
cb = cb || createPromiseCallback()
debug('getCurrentGroupId context.remotingContext.args: %o', context.remotingContext.args)
let groupId = null
// If we are accessing the group model directly, the group id is the model id.
if (this.isGroupModel(context.model)) {
process.nextTick(() => cb(null, context.modelId))
return cb.promise
}
// If we are accessing an existing model, get the group id from the existing model instance.
// TODO: Cache this result so that it can be reused across each ACL lookup attempt.
if (context.modelId) {
debug(`fetching group id for existing model with id: ${context.modelId}`)
context.model.findById(context.modelId, { }, {
skipAccess: true,
})
.then(item => {
// TODO: Attempt to follow relationships in addition to the foreign key.
if (item) {
debug(`determined group id ${item[this.options.foreignKey]} from existing model ${context.modelId}`)
groupId = item[this.options.foreignKey]
}
cb(null, groupId)
})
.catch(cb)
}
// If we are creating a new model, get the foreignKey from the incoming data.
else if (_get(context, `remotingContext.args.data[${this.options.foreignKey}]`)) {
debug(`determined current group id ${groupId} from incoming data`)
groupId = context.remotingContext.args.data[this.options.foreignKey]
process.nextTick(() => cb(null, groupId))
}
// Otherwise, return null.
else {
debug('unable to determine current group context')
process.nextTick(() => cb(null, groupId))
}
return cb.promise
}
/**
* Determine the target Group Id based on the current security context.
*
* @param {Object} context The security context.
* @param {function} [cb] A callback function.
* @returns {Object} Returns the determined Group ID.
*/
getTargetGroupId(context, cb) {
cb = cb || createPromiseCallback()
debug('getTargetGroupId context.remotingContext.args: %o', context.remotingContext.args)
let groupId = null
// Get the target group id from the incoming data.
if (_get(context, `remotingContext.args.data[${this.options.foreignKey}]`)) {
debug(`determined target group id ${groupId} from incoming data`)
groupId = context.remotingContext.args.data[this.options.foreignKey]
}
// Otherwise, return null.
else {
debug('unable to determine target group context')
}
process.nextTick(() => cb(null, groupId))
return cb.promise
}
}