/
user-context.js
43 lines (36 loc) · 1.32 KB
/
user-context.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
'use strict'
const debug = require('debug')('loopback:component:access:context')
const Promise = require('bluebird')
const LoopBackContext = require('loopback-context')
module.exports = function userContextMiddleware() {
debug('initializing user context middleware')
// set current user to enable user access for remote methods
return function userContext(req, res, next) {
const loopbackContext = LoopBackContext.getCurrentContext({ bind: true })
next = loopbackContext.bind(next)
if (!loopbackContext) {
debug('No user context (loopback current context not found)')
return next()
}
if (!req.accessToken) {
debug('No user context (access token not found)')
return next()
}
const { app } = req
const UserModel = app.accessUtils.options.userModel || 'User'
return Promise.join(
app.models[UserModel].findById(req.accessToken.userId),
app.accessUtils.getUserGroups(req.accessToken.userId),
(user, groups) => {
if (!user) {
return next(new Error('No user with this access token was found.'))
}
loopbackContext.set('currentUser', user)
loopbackContext.set('currentUserGroups', groups)
debug('currentUser', user)
debug('currentUserGroups', groups)
return next()
})
.catch(next)
}
}