blob: 6da2eef2ae579229bda20cc1d364606bac17850f [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']){
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 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
33 sentReq = sentReq
34 .set('x-csrftoken', req.headers['x-csrftoken'] || null)
Matteo Scandolof05d8a62016-12-06 13:36:49 -080035 .set('cookie', `xossessionid=${req.headers['x-sessionid']}` || null)
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080036
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})();