blob: 75d284052a1f18af6e067ee9e36204213cf680cf [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 Scandolo3e40ef42017-02-17 14:46:19 -080044 let errRes;
45 try {
46 errRes = err.response.error;
47 }
48 catch(e) {
49 errRes = err;
50 }
51 return res.status(err.status).send(errRes);
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080052 }
Matteo Scandolo2eca9892016-12-23 09:10:27 -080053 logger.log('debug', sentReq.method, sentReq.url, r.status);
54 logger.log('silly', r.text)
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080055 return res.status(r.status).type('json').send(r.body);
56 });
57 };
58
59 app.all('/api/core', proxyRequest);
60 app.all('/api/core/*', proxyRequest);
Matteo Scandolo81a09462017-02-16 17:52:27 -080061 app.all('/api/service', proxyRequest);
62 app.all('/api/service/*', proxyRequest);
Matteo Scandolo45182c52017-02-03 14:37:35 -080063 app.all('/api/tenant', proxyRequest);
64 app.all('/api/tenant/*', proxyRequest);
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080065 app.all('/api/utility', proxyRequest);
66 app.all('/api/utility/*', proxyRequest);
67 };
Matteo Scandolo81a09462017-02-16 17:52:27 -080068})();