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 |
Matteo Scandolo | 2eca989 | 2016-12-23 09:10:27 -0800 | [diff] [blame] | 33 | if(req.headers['x-csrftoken'] && req.headers['x-sessionid']){ |
| 34 | sentReq = sentReq |
| 35 | .set('x-csrftoken', req.headers['x-csrftoken'] || null) |
| 36 | .set('cookie', `xoscsrftoken=${req.headers['x-csrftoken']}; xossessionid=${req.headers['x-sessionid']}` || null) |
| 37 | } |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 38 | |
| 39 | // handle response |
| 40 | sentReq |
| 41 | .end((err, r) => { |
| 42 | if(err) { |
Matteo Scandolo | 2eca989 | 2016-12-23 09:10:27 -0800 | [diff] [blame] | 43 | logger.log('error', sentReq.method, sentReq.url, err); |
Matteo Scandolo | 4796465 | 2016-12-22 09:23:50 -0800 | [diff] [blame] | 44 | return res.status(err.status).send(err.response.error); |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 45 | } |
Matteo Scandolo | 2eca989 | 2016-12-23 09:10:27 -0800 | [diff] [blame] | 46 | logger.log('debug', sentReq.method, sentReq.url, r.status); |
| 47 | logger.log('silly', r.text) |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 48 | return res.status(r.status).type('json').send(r.body); |
| 49 | }); |
| 50 | }; |
| 51 | |
| 52 | app.all('/api/core', proxyRequest); |
| 53 | app.all('/api/core/*', proxyRequest); |
| 54 | app.all('/api/services', proxyRequest); |
| 55 | app.all('/api/services/*', proxyRequest); |
| 56 | app.all('/api/utility', proxyRequest); |
| 57 | app.all('/api/utility/*', proxyRequest); |
| 58 | }; |
| 59 | })(); |