Skip to content

Commit 75ad901

Browse files
author
Tom Kirkpatrick
committed
feat: make currentUser and currentUserGroups in optionsFromRequest
1 parent f2d2219 commit 75ad901

File tree

3 files changed

+23
-6
lines changed

3 files changed

+23
-6
lines changed

lib/index.js

+6-5
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,22 @@ module.exports = function loopbackComponentAccess(app, options) {
1414
throw new Error('loopback-component-access-groups requires loopback 2.0 or newer')
1515
}
1616

17-
// Initialize middleware
17+
// Initialize middleware.
1818
app.middleware('auth:after', userContext())
1919
app.middleware('routes:before', accessLogger())
2020

2121
// Initialise helper class.
22-
const accessUtils = new AccessUtils(app, options)
22+
app.accessUtils = new AccessUtils(app, options)
2323

24-
app.accessUtils = accessUtils
24+
// Initialize remoting phase.
25+
app.accessUtils.setupRemotingPhase()
2526

2627
// Set up role resolvers.
27-
accessUtils.setupRoleResolvers()
28+
app.accessUtils.setupRoleResolvers()
2829

2930
// Set up model opertion hooks.
3031
if (options.applyToStatic) {
31-
accessUtils.setupFilters()
32+
app.accessUtils.setupFilters()
3233
}
3334

3435
// TODO: Create Group Access model automatically if one hasn't been specified

lib/middleware/user-context.js

-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ module.exports = function userContextMiddleware() {
2222
return next()
2323
}
2424

25-
loopbackContext.set('accessToken', req.accessToken.id)
2625
const { app } = req
2726
const UserModel = app.accessUtils.options.userModel || 'User'
2827

lib/utils.js

+17
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const debug = require('debug')('loopback:component:access')
44
const { createPromiseCallback } = require('loopback-datasource-juggler/lib/utils')
55
const _defaults = require('lodash').defaults
66
const _get = require('lodash').get
7+
const _set = require('lodash').set
78
const Promise = require('bluebird')
89
const LoopBackContext = require('loopback-context')
910

@@ -38,6 +39,22 @@ module.exports = class AccessUtils {
3839
debug('options: %o', options)
3940
}
4041

42+
/**
43+
* Register a custom remoting phase to make the current user details available from remoting contexts.
44+
*/
45+
setupRemotingPhase() {
46+
this.app.remotes().phases
47+
.addBefore('invoke', 'options-from-request')
48+
.use((ctx, next) => {
49+
if (!_get(ctx, 'args.options.accessToken')) {
50+
return next()
51+
}
52+
_set(ctx, 'args.options.currentUser', this.getCurrentUser())
53+
_set(ctx, 'args.options.currentUserGroups', this.getCurrentUserGroups())
54+
return next()
55+
})
56+
}
57+
4158
/**
4259
* Register a dynamic role resolver for each defined access group.
4360
*/

0 commit comments

Comments
 (0)