This repository was archived by the owner on Mar 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp-routes.js
144 lines (127 loc) · 4.37 KB
/
app-routes.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
/**
* Configure all routes for express app
*/
const express = require('express')
const _ = require('lodash')
const config = require('config')
const HttpStatus = require('http-status-codes')
const fs = require('fs')
const path = require('path')
const swaggerUi = require('swagger-ui-express')
const jsyaml = require('js-yaml')
const helper = require('./src/common/helper')
const errors = require('./src/common/errors')
const routes = require('./src/routes')
const authenticator = require('tc-core-library-js').middleware.jwtAuthenticator
/**
* Checks if the source matches the term.
*
* @param {Array} source the array in which to search for the term
* @param {Array | String} term the term to search
*/
function checkIfExists (source, term) {
let terms
if (!_.isArray(source)) {
throw new Error('Source argument should be an array')
}
source = source.map(s => s.toLowerCase())
if (_.isString(term)) {
terms = term.split(' ')
} else if (_.isArray(term)) {
terms = term.map(t => t.toLowerCase())
} else {
throw new Error('Term argument should be either a string or an array')
}
for (let i = 0; i < terms.length; i++) {
if (source.includes(terms[i])) {
return true
}
}
return false
}
/**
* 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()
})
// Authentication and Authorization
if (def.auth === 'jwt') {
actions.push((req, res, next) => {
authenticator(_.pick(config, ['AUTH_SECRET', 'VALID_ISSUERS']))(req, res, next)
})
actions.push((req, res, next) => {
if (!req.authUser) {
return next(new errors.UnauthorizedError('Action is not allowed for invalid token'))
}
if (req.authUser.roles) {
// user
if (def.access && !checkIfExists(def.access, req.authUser.roles)) {
res.forbidden = true
next(new errors.ForbiddenError('You are not allowed to perform this action!'))
} else {
next()
}
} else if (req.authUser.scopes) {
// M2M
if (def.scopes && !checkIfExists(def.scopes, req.authUser.scopes)) {
res.forbidden = true
next(new errors.ForbiddenError('You are not allowed to perform this action!'))
} else {
next()
}
} else if ((_.isArray(def.access) && def.access.length > 0) ||
(_.isArray(def.scopes) && def.scopes.length > 0)) {
next(new errors.UnauthorizedError('You are not authorized to perform this action'))
} else {
next()
}
})
}
actions.push(method)
if (def.upload) {
app[verb](`${config.API_VERSION}${path}`, def.upload, helper.autoWrapExpress(actions))
} else {
app[verb](`${config.API_VERSION}${path}`, helper.autoWrapExpress(actions))
}
})
})
const spec = fs.readFileSync(path.join(__dirname, 'docs/swagger.yaml'), 'utf8')
const swaggerDoc = jsyaml.safeLoad(spec)
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDoc))
// Static file server
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'development') {
// Serve any static files
app.use(express.static(path.join(__dirname, 'client/build')))
// Handle React routing, return all requests to React app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'))
})
}
// Check if the route is not found or HTTP method is not supported
app.use('*', (req, res) => {
const route = routes[req.baseUrl]
let status
let message
if (route) {
status = HttpStatus.METHOD_NOT_ALLOWED
message = 'The requested HTTP method is not supported.'
} else {
status = HttpStatus.NOT_FOUND
message = 'The requested resource cannot be found.'
}
res.status(status).json({ message })
})
}