blob: 3c298557d2c770325bcd72e855a2bd405c98787b [file] [log] [blame]
Matteo Scandoloe3ed0162016-12-01 10:09:12 -08001(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 Scandolof05d8a62016-12-06 13:36:49 -080011 // debugging helper
12 if(!req.headers['x-csrftoken']){
Matteo Scandolob46bce72017-01-17 15:33:49 -080013 logger.log('warn', `csrftoken is missing and is required for authentication for ${req.url}`);
Matteo Scandolof05d8a62016-12-06 13:36:49 -080014 }
15 if(!req.headers['x-sessionid']){
Matteo Scandolob46bce72017-01-17 15:33:49 -080016 logger.log('warn', `Session id is missing and is required for authentication for ${req.url}`);
Matteo Scandolof05d8a62016-12-06 13:36:49 -080017 }
18
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080019 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 Scandolo2eca9892016-12-23 09:10:27 -080033 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 Scandoloe3ed0162016-12-01 10:09:12 -080038
39 // handle response
40 sentReq
41 .end((err, r) => {
42 if(err) {
Matteo Scandolo2eca9892016-12-23 09:10:27 -080043 logger.log('error', sentReq.method, sentReq.url, err);
Matteo Scandolo47964652016-12-22 09:23:50 -080044 return res.status(err.status).send(err.response.error);
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080045 }
Matteo Scandolo2eca9892016-12-23 09:10:27 -080046 logger.log('debug', sentReq.method, sentReq.url, r.status);
47 logger.log('silly', r.text)
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080048 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);
Matteo Scandolo81a09462017-02-16 17:52:27 -080054 app.all('/api/service', proxyRequest);
55 app.all('/api/service/*', proxyRequest);
Matteo Scandolo45182c52017-02-03 14:37:35 -080056 app.all('/api/tenant', proxyRequest);
57 app.all('/api/tenant/*', proxyRequest);
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080058 app.all('/api/utility', proxyRequest);
59 app.all('/api/utility/*', proxyRequest);
60 };
Matteo Scandolo81a09462017-02-16 17:52:27 -080061})();