Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 1 | (function () { |
| 2 | 'use strict'; |
| 3 | |
| 4 | const request = require('superagent'); |
| 5 | const logger = require('../config/logger.js'); |
| 6 | |
| 7 | module.exports = function(app) { |
| 8 | |
| 9 | const proxyRequest = (req, res) => { |
| 10 | |
Matteo Scandolo | f05d8a6 | 2016-12-06 13:36:49 -0800 | [diff] [blame^] | 11 | // debugging helper |
| 12 | if(!req.headers['x-csrftoken']){ |
| 13 | logger.log('warn', `csrftoken is missing and is required for authentication`); |
| 14 | } |
| 15 | if(!req.headers['x-sessionid']){ |
| 16 | logger.log('warn', `Session id is missing and is required for authentication`); |
| 17 | } |
| 18 | |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 19 | const config = require('../config/config.js').xos; |
| 20 | // pick the correct method from superAgent |
| 21 | const makeReq = request[req.method.toLowerCase()]; |
| 22 | |
| 23 | // start the request |
| 24 | let sentReq = makeReq(`${config.host}:${config.port}${req.url}`); |
| 25 | |
| 26 | // if needed add a body to the request |
| 27 | if(req.method === 'POST' || req.method === 'PUT') { |
| 28 | sentReq = sentReq |
| 29 | .send(req.body) |
| 30 | } |
| 31 | |
| 32 | // extend with auth info |
| 33 | sentReq = sentReq |
| 34 | .set('x-csrftoken', req.headers['x-csrftoken'] || null) |
Matteo Scandolo | f05d8a6 | 2016-12-06 13:36:49 -0800 | [diff] [blame^] | 35 | .set('cookie', `xossessionid=${req.headers['x-sessionid']}` || null) |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 36 | |
| 37 | // handle response |
| 38 | sentReq |
| 39 | .end((err, r) => { |
| 40 | if(err) { |
| 41 | logger.log('error', err); |
| 42 | return res.status(500).send(err); |
| 43 | } |
| 44 | logger.log('debug', r.status, r.body); |
| 45 | return res.status(r.status).type('json').send(r.body); |
| 46 | }); |
| 47 | }; |
| 48 | |
| 49 | app.all('/api/core', proxyRequest); |
| 50 | app.all('/api/core/*', proxyRequest); |
| 51 | app.all('/api/services', proxyRequest); |
| 52 | app.all('/api/services/*', proxyRequest); |
| 53 | app.all('/api/utility', proxyRequest); |
| 54 | app.all('/api/utility/*', proxyRequest); |
| 55 | }; |
| 56 | })(); |