forked from eddywashere/proxy-keystone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
199 lines (170 loc) · 5.05 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
'use strict';
var request = require('request');
var Url = require('url'),
util = require('util'),
EventEmitter = require('events').EventEmitter,
httpProxy = require('http-proxy'),
_ = require('lodash'),
proxy = new httpProxy.createProxyServer(),
ProxyKeystone = function(customOptions){
var self = this;
self.options = {
token: 'user.token',
userId: 'user.userId',
tenantId: 'user.tenantId',
catalog: 'user.serviceCatalog',
userAgent: ''
};
if(customOptions){
for(var i in customOptions){
self.options[i] = customOptions[i];
}
}
self.getValueByString = function (o, s) {
var a = s.split('.');
while (a.length) {
var n = a.shift();
if (n in o) {
o = o[n];
} else {
return false;
}
}
return o;
};
self.parseService = function (service) {
var segments = service.split(','),
data = {
name: segments[0]
};
if (segments.length === 2) {
data.region = segments[1];
}
self.emit('log:parseService', data);
return data;
};
self.getServiceByName = function (name, catalog) {
if (catalog instanceof Array) {
return _.find(catalog, function(item) {
return name === item.name;
});
} else {
return catalog[name];
}
};
self.findEndpoint = function (serviceInfo, service) {
if (serviceInfo.region){
return _.find(service.endpoints, function(endpoint) {
return serviceInfo.region === endpoint.region;
});
} else {
return service.endpoints[0];
}
};
self.middleware = function (req, res, next) {
var error, token, catalog, serviceParams, service,
endpoint, endpointInfo, target, serviceInfo, userId, tenantId,
proxyUrl = req.route.path.replace(/\*$/, '');
// Handle body parser issues
req.removeAllListeners('data');
req.removeAllListeners('end');
process.nextTick(function () {
if(req.body) {
req.emit('data', JSON.stringify(req.body));
}
req.emit('end');
});
// set token and serviceCatalog
token = self.getValueByString(req, self.options.token);
userId = self.getValueByString(req, self.options.userId);
tenantId = self.getValueByString(req, self.options.tenantId);
catalog = self.getValueByString(req, self.options.catalog);
if(!token && !userId){
error = new Error('Missing token/userId');
self.emit('proxyError', error);
return next(error);
}
if (!catalog) {
error = new Error('Missing Service Catalog');
self.emit('proxyError', error);
return next(error);
}
// begin req.url transformation
req.url = req.url.split(proxyUrl)[1]; // remove /proxy/
if (req.service) {
serviceParams = req.service;
}
else {
serviceParams = req.url.split('/')[0]; // grabs 'catalogItem,[region]'
req.url = req.url.split(serviceParams)[1]; // transform req.url
}
serviceInfo = self.parseService(serviceParams);
// grab service from catalog based on name
service = self.getServiceByName(serviceInfo.name, catalog);
// check if service exists
if (!service){
error = new Error('Service Catalog Item Not Found');
self.emit('proxyError', error);
return next(error);
}
endpoint = self.findEndpoint(serviceInfo, service);
if (!endpoint) {
error = new Error('Endpoint Not Found In ' + service.name);
self.emit('proxyError', error);
return next(error);
}
// url.parse creates an object
endpointInfo = Url.parse(endpoint.publicURL);
if (endpointInfo.path != '/') {
target = endpoint.publicURL.split(endpointInfo.path)[0];
}
else {
target = endpoint.publicURL;
}
req.url = endpointInfo.pathname + req.url;
// Set headers
req.headers = {};
req.headers['X-Auth-Token'] = token;
req.headers['X-Auth-User'] = userId;
req.headers['X-Auth-Tenant'] = tenantId;
req.headers['Accept'] = 'application/json';
req.headers['Content-Type'] = 'application/json';
if (self.options.userAgent){
req.headers['User-Agent'] = self.options.userAgent;
}
// dirty hacks for POST/PUT requests
if (req.method == 'POST' || req.method == 'PUT') {
request({
method: req.method,
url: target + req.url,
headers: req.headers,
json: req.body
}, function(error, response, body) {
if (error) {
next(error);
} else if ('x-redirect' in response.headers) {
res.redirect(response.headers['x-redirect']);
} else {
res.json(body);
}
});
}
else {
proxy.on('start', function(req, res, target){
self.emit('proxyStart', req, res, target);
});
proxy.on('end', function(req, res, proxyRes){
self.emit('proxyEnd', req, res, proxyRes);
});
proxy.on('error', function (err) {
self.emit('proxyError', err);
next(err);
});
proxy.web(req, res, {
target: target
});
}
};
};
util.inherits(ProxyKeystone, EventEmitter);
module.exports = ProxyKeystone;