|
| 1 | +/** |
| 2 | + * Configure all routes for express app |
| 3 | + */ |
| 4 | + |
| 5 | +const _ = require('lodash') |
| 6 | +const config = require('config') |
| 7 | +const HttpStatus = require('http-status-codes') |
| 8 | +const helper = require('./src/common/helper') |
| 9 | +const errors = require('./src/common/errors') |
| 10 | +const routes = require('./src/routes') |
| 11 | +const authenticator = require('tc-core-library-js').middleware.jwtAuthenticator |
| 12 | + |
| 13 | +/** |
| 14 | + * Configure all routes for express app |
| 15 | + * @param app the express app |
| 16 | + */ |
| 17 | +module.exports = (app) => { |
| 18 | + // Load all routes |
| 19 | + _.each(routes, (verbs, path) => { |
| 20 | + _.each(verbs, (def, verb) => { |
| 21 | + const controllerPath = `./src/controllers/${def.controller}` |
| 22 | + const method = require(controllerPath)[def.method]; // eslint-disable-line |
| 23 | + if (!method) { |
| 24 | + throw new Error(`${def.method} is undefined`) |
| 25 | + } |
| 26 | + |
| 27 | + const actions = [] |
| 28 | + actions.push((req, res, next) => { |
| 29 | + req.signature = `${def.controller}#${def.method}` |
| 30 | + next() |
| 31 | + }) |
| 32 | + |
| 33 | + // add Authenticator check if route has auth |
| 34 | + if (def.auth) { |
| 35 | + actions.push((req, res, next) => { |
| 36 | + authenticator(_.pick(config, ['AUTH_SECRET', 'VALID_ISSUERS']))(req, res, next) |
| 37 | + }) |
| 38 | + |
| 39 | + actions.push((req, res, next) => { |
| 40 | + if (req.authUser.isMachine) { |
| 41 | + next(new errors.ForbiddenError('M2M is not supported.')) |
| 42 | + } else { |
| 43 | + req.authUser.userId = String(req.authUser.userId) |
| 44 | + // User |
| 45 | + if (req.authUser.roles) { |
| 46 | + if (!helper.checkIfExists(def.access, req.authUser.roles)) { |
| 47 | + next(new errors.ForbiddenError('You are not allowed to perform this action!')) |
| 48 | + } else { |
| 49 | + next() |
| 50 | + } |
| 51 | + } else { |
| 52 | + next(new errors.ForbiddenError('You are not authorized to perform this action')) |
| 53 | + } |
| 54 | + } |
| 55 | + }) |
| 56 | + } |
| 57 | + |
| 58 | + actions.push(method) |
| 59 | + app[verb](path, helper.autoWrapExpress(actions)) |
| 60 | + }) |
| 61 | + }) |
| 62 | + |
| 63 | + // Check if the route is not found or HTTP method is not supported |
| 64 | + app.use('*', (req, res) => { |
| 65 | + if (routes[req.baseUrl]) { |
| 66 | + res.status(HttpStatus.METHOD_NOT_ALLOWED).json({ |
| 67 | + message: 'The requested HTTP method is not supported.' |
| 68 | + }) |
| 69 | + } else { |
| 70 | + res.status(HttpStatus.NOT_FOUND).json({ |
| 71 | + message: 'The requested resource cannot be found.' |
| 72 | + }) |
| 73 | + } |
| 74 | + }) |
| 75 | +} |
0 commit comments