Newer
Older
const http = require('http');
const httpProxy = require('http-proxy');
const axios = require('axios');
const URL = require('url');
const Redis = require("ioredis");
// CONFIG
const redisSentinelHost = process.env.REDIS_SENTINEL_HOST;
const redisSentinelPort = process.env.REDIS_SENTINEL_PORT;
const redisGroupName = process.env.REDIS_GROUP_NAME;
const redisAuthorizedTTL = process.env.REDIS_AUTHORIZED_TTL; // In seconds
const redisUnauthorizedTTL = process.env.REDIS_UNAUTHORIZED_TTL; // In seconds
const elasticsearchUrl = process.env.ELASTICSEARCH_URL;
const technicalAccountUsername = process.env.TECHNICAL_ACCOUNT_USERNAME;
const technicalAccountPassword = process.env.TECHNICAL_ACCOUNT_PASSWORD;
const proxyHostTarget = process.env.PROXY_HOST_TARGET;
// Configuring the different proxy server
// Proxy IGN Ortho
var ingProxy = httpProxy.createProxyServer({
changeOrigin: true,
target: 'https://wxs.ign.fr/q7kc4me8vbbf4iw7epsfoiy7/geoportail/r/wms/',
});
// Configuring the different proxy server
// Proxy WMS
var wmsProxy = httpProxy.createProxyServer({
changeOrigin: true,
target: proxyHostTarget,
auth: `${technicalAccountUsername}:${technicalAccountPassword}`,
});
// Configure and create an HTTP proxy server
var mvtProxy = httpProxy.createProxyServer({
changeOrigin: true,
target: proxyHostTarget,
auth: `${technicalAccountUsername}:${technicalAccountPassword}`,
});
var mvtUnauthProxy = httpProxy.createProxyServer({
changeOrigin: true,
target: proxyHostTarget,
});
ingProxy.on('proxyReq', function (proxyReq, req) {
req._proxyReq = proxyReq;
});
FORESTIER Fabien
committed
// keep a referece of the proxyRequest in the req object
wmsProxy.on('proxyReq', function (proxyReq, req) {
req._proxyReq = proxyReq;
});
mvtProxy.on('proxyReq', function (proxyReq, req) {
req._proxyReq = proxyReq;
});
mvtUnauthProxy.on('proxyReq', function (proxyReq, req) {
req._proxyReq = proxyReq;
});
ingProxy.on('error', function (err, req, res) {
// If the client cancelled the request, abort the request to the upstream server
if (req.socket.destroyed && err.code === 'ECONNRESET') {
req._proxyReq.abort();
}
return console.log(`ING Error, req.socket.destroyed: ${req.socket.destroyed}, ${err}`);
});
FORESTIER Fabien
committed
wmsProxy.on('error', function (err, req, res) {
// If the client cancelled the request, abort the request to the upstream server
if (req.socket.destroyed && err.code === 'ECONNRESET') {
req._proxyReq.abort();
}
return console.log(`WMS Error, req.socket.destroyed: ${req.socket.destroyed}, ${err}`);
});
mvtProxy.on('error', function (err, req, res) {
// If the client cancelled the request, abort the request to the upstream server
if (req.socket.destroyed && err.code === 'ECONNRESET') {
req._proxyReq.abort();
}
return console.log(`MVT Error, req.socket.destroyed: ${req.socket.destroyed}, ${err}`);
});
mvtUnauthProxy.on('error', function (err, req, res) {
// If the client cancelled the request, abort the request to the upstream server
if (req.socket.destroyed && err.code === 'ECONNRESET') {
req._proxyReq.abort();
}
return console.log(`MVT Unauthenticated Error, req.socket.destroyed: ${req.socket.destroyed}, ${err}`);
});
// Create an HTTP server
http.createServer(async function (req, res) {
/******* IGN */
if (req.url.includes('/ign')) {
req.headers['referer'] = 'grandlyon.com';
ingProxy.web(req, res, {});
return;
}
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
200
201
202
203
204
205
206
207
208
209
210
211
/******************* WMS *****************************/
if (req.url.includes('/wms')) {
wmsProxy.web(req, res, {});
return;
}
/******************* MVT *****************************/
if (req.url.includes('/mvt')) {
// If no cookies then then we can't identify a user and directly proxy the request without credentials
if (req.headers["x-anonymous-consumer"]) {
mvtUnauthProxy.web(req, res, {});
return;
}
// Read the requested layer from the url
const layer = getParameterValueFromUrl(req.url, 'LAYERS');
if (!layer) {
res.statusCode = 400;
res.end();
return;
}
const userRightsOnTheLayer = await getRedisValue(`${layer}-${req.headers['x-consumer-username']}`);
if (userRightsOnTheLayer === 'true') {
mvtProxy.web(req, res, {});
return;
}
if (userRightsOnTheLayer === 'false') {
res.statusCode = 401;
res.end();
return;
}
const options = {
method: 'POST',
url: `${elasticsearchUrl}/_search?&request_cache=false`,
data: {
"from": 0,
"size": 1,
"_source": [
"editorial-metadata.isSample",
"editorial-metadata.isOpenAccess"
],
"query": {
"term": {
"metadata-fr.link.name": layer
}
}
},
headers: {
cookie: req.headers.cookie,
}
};
let response;
try {
response = await axios(options)
} catch (err) {
printError('Request to ES failed', err);
res.statusCode = 500;
res.end();
return;
}
// If no results are found it means the specified dataset mvt layer doesn't exists
if (response.data.hits.hits < 1) {
printError('Request to ES', 'MVT not found');
res.statusCode = 404;
res.end();
return;
}
const editorialMetadata = response.data.hits.hits[0]._source['editorial-metadata'];
if (!editorialMetadata.isOpenAccess && editorialMetadata.isSample) {
setRedisValue(`${layer}-${req.headers['x-consumer-username']}`, false, redisUnauthorizedTTL);
res.statusCode = 401;
res.end();
return;
}
await setRedisValue(`${layer}-${req.headers['x-consumer-username']}`, true, redisAuthorizedTTL);
mvtProxy.web(req, res, {});
}
}).listen(9000);
// HELPERS
function getParameterValueFromUrl(url, paramName) {
const queryParams = URL.parse(url, true).query;
return queryParams && queryParams[paramName] ? queryParams[paramName] : null;
}
async function setRedisValue(key, value, ttl) {
const redisClient = new Redis({
sentinels: [{
host: redisSentinelHost,
port: redisSentinelPort
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
name: redisGroupName,
});
redisClient.on('error', (error) => {
printError('Redis client', error);
redisClient.disconnect();
});
// Set key value with expiration time in seconds
const res = await redisClient.set(key, value, 'EX', ttl).catch((error) => {
redisClient.disconnect();
printError('Redis client', 'Couldn\'t set redis key/value (with ttl).');
printError('Redis client', error);
return false;
});
printLog('Redis client', 'Done setting key/value pair');
redisClient.disconnect();
return res ? true : false;
}
async function getRedisValue(key) {
const redisClient = new Redis({
sentinels: [{
host: redisSentinelHost,
port: redisSentinelPort
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
name: redisGroupName,
});
redisClient.on('error', (error) => {
printError('Redis client', error);
redisClient.disconnect();
});
const res = await redisClient.get(key).catch((error) => {
redisClient.disconnect();
printError('Redis client', 'Couldn\'t get redis value.');
printError('Redis client', error);
return false;
});
printLog(`Redis client`, `Value found ${res}`);
redisClient.disconnect();
return res ? res : null;
}
function printLog(context, value) {
console.log(`${new Date().toLocaleString("fr-FR")} [${context}] [log] `, value);
}
function printError(context, error) {
console.error(`${new Date().toLocaleString("fr-FR")} [${context}] [error] `, error);
}