Skip to content

Commit

Permalink
feat: make currentUser and currentUserGroups in optionsFromRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Kirkpatrick committed Jul 25, 2017
1 parent f2d2219 commit 75ad901
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
11 changes: 6 additions & 5 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,22 @@ module.exports = function loopbackComponentAccess(app, options) {
throw new Error('loopback-component-access-groups requires loopback 2.0 or newer')
}

// Initialize middleware
// Initialize middleware.
app.middleware('auth:after', userContext())
app.middleware('routes:before', accessLogger())

// Initialise helper class.
const accessUtils = new AccessUtils(app, options)
app.accessUtils = new AccessUtils(app, options)

app.accessUtils = accessUtils
// Initialize remoting phase.
app.accessUtils.setupRemotingPhase()

// Set up role resolvers.
accessUtils.setupRoleResolvers()
app.accessUtils.setupRoleResolvers()

// Set up model opertion hooks.
if (options.applyToStatic) {
accessUtils.setupFilters()
app.accessUtils.setupFilters()
}

// TODO: Create Group Access model automatically if one hasn't been specified
Expand Down
1 change: 0 additions & 1 deletion lib/middleware/user-context.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ module.exports = function userContextMiddleware() {
return next()
}

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

Expand Down
17 changes: 17 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ 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')

Expand Down Expand Up @@ -38,6 +39,22 @@ module.exports = class AccessUtils {
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.
*/
Expand Down

0 comments on commit 75ad901

Please sign in to comment.