-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp-routes.js
More file actions
154 lines (144 loc) · 5.49 KB
/
Copy pathapp-routes.js
File metadata and controls
154 lines (144 loc) · 5.49 KB
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
/**
* Configure all routes for express app
*/
const _ = require('lodash')
const config = require('config')
const HttpStatus = require('http-status-codes')
const helper = require('./src/common/helper')
const errors = require('./src/common/errors')
const logger = require('./src/common/logger')
const routes = require('./src/routes')
const authenticator = require('tc-core-library-js').middleware.jwtAuthenticator
/**
* Configure all routes for express app
* @param app the express app
*/
module.exports = (app) => {
// Load all routes
_.each(routes, (verbs, path) => {
_.each(verbs, (def, verb) => {
const controllerPath = `./src/controllers/${def.controller}`
const method = require(controllerPath)[def.method]; // eslint-disable-line
if (!method) {
throw new Error(`${def.method} is undefined`)
}
const actions = []
actions.push((req, res, next) => {
req.signature = `${def.controller}#${def.method}`
next()
})
actions.push((req, res, next) => {
if (_.get(req, 'query.authToken')) {
_.set(req, 'headers.authorization', `Bearer ${_.trim(req.query.authToken)}`)
}
next()
})
if (def.auth) {
// add Authenticator/Authorization check if route has auth
actions.push((req, res, next) => {
// When authorization token is not provided and allow no token is enabled then bypass
if (!_.get(req, 'headers.authorization') && def.allowNoToken) {
next()
} else {
authenticator(_.pick(config, ['AUTH_SECRET', 'VALID_ISSUERS']))(req, res, next)
}
})
actions.push((req, res, next) => {
// When authorization token is not provided and allow no token is enabled then bypass
if (!_.get(req, 'headers.authorization') && def.allowNoToken) {
next()
} else {
if (req.authUser.isMachine) {
// M2M
if (!req.authUser.scopes || (def.scopes && !helper.checkIfExists(def.scopes, req.authUser.scopes))) {
next(new errors.ForbiddenError('You are not allowed to perform this action!'))
} else {
next()
}
} else {
req.authUser.userId = String(req.authUser.userId)
// User roles authorization
if (req.authUser.roles) {
if (def.access && !helper.checkIfExists(def.access, req.authUser.roles)) {
next(new errors.ForbiddenError('You are not allowed to perform this action!'))
} else {
next()
}
} else {
next(new errors.ForbiddenError('You are not authorized to perform this action'))
}
}
}
})
} else {
// public API, but still try to authenticate token if provided, but allow missing/invalid token
// Skip authentication entirely for health check endpoint
if (path === '/members/health') {
// Health check doesn't need authentication - skip it entirely
actions.push((req, res, next) => {
next()
})
} else {
actions.push((req, res, next) => {
if (!_.get(req, 'headers.authorization')) {
next()
return
}
const interceptRes = {}
interceptRes.status = () => interceptRes
interceptRes.json = () => next()
interceptRes.send = () => next()
authenticator(_.pick(config, ['AUTH_SECRET', 'VALID_ISSUERS']))(req, interceptRes, next)
})
}
// Skip post-auth middleware for health check since we skipped auth
if (path !== '/members/health') {
actions.push((req, res, next) => {
if (!req.authUser) {
next()
} else if (req.authUser.isMachine) {
// M2M
if (!req.authUser.scopes || (def.scopes && !helper.checkIfExists(def.scopes, req.authUser.scopes))) {
next(new errors.ForbiddenError('You are not allowed to perform this action!'))
} else {
next()
}
} else {
req.authUser.userId = String(req.authUser.userId)
// User roles authorization
if (req.authUser.roles) {
if (def.access && !helper.checkIfExists(def.access, req.authUser.roles)) {
next(new errors.ForbiddenError('You are not allowed to perform this action!'))
} else {
next()
}
} else {
next(new errors.ForbiddenError('You are not authorized to perform this action'))
}
}
})
} else {
// For health check, just proceed directly to controller
actions.push((req, res, next) => {
next()
})
}
}
actions.push(method)
logger.debug(`Registering path ${verb} /${config.API_VERSION}${path}`)
app[verb](`/${config.API_VERSION}${path}`, helper.autoWrapExpress(actions))
})
})
// Check if the route is not found or HTTP method is not supported
app.use('*', (req, res) => {
if (routes[req.baseUrl]) {
res.status(HttpStatus.METHOD_NOT_ALLOWED).json({
message: 'The requested HTTP method is not supported.'
})
} else {
res.status(HttpStatus.NOT_FOUND).json({
message: 'The requested resource cannot be found.'
})
}
})
}