Newer
Older
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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 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,
});
// Create an HTTP server
http.createServer(async function (req, res) {
/******************* WMS *****************************/
if (req.url.includes('/wms')) {
printLog('Request received', 'WMS');
wmsProxy.web(req, res, {});
printLog('WMS request', 'proxified');
return;
}
/******************* MVT *****************************/
if (req.url.includes('/mvt')) {
printLog('Request received', '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"]) {
printLog('Request received', `Unauthenticated - proxying the request`);
mvtUnauthProxy.web(req, res, {});
return;
}
// Read the requested layer from the url
const layer = getParameterValueFromUrl(req.url, 'LAYERS');
if (!layer) {
printError('Request received', 'No layer provided');
res.statusCode = 400;
res.end();
return;
}
printLog('Request received', `Layer found: ${layer}`);
const userRightsOnTheLayer = await getRedisValue(`${layer}-${req.headers['x-consumer-username']}`);
if (userRightsOnTheLayer === 'true') {
printLog('Request received', 'Authorized (value read from Redis)');
mvtProxy.web(req, res, {});
return;
}
if (userRightsOnTheLayer === 'false') {
printLog('Request received', 'Unauthorized (value read from Redis)');
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,
}
};
printLog('Request received', options);
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;
}
printLog('Request to ES', 'MVT found');
const editorialMetadata = response.data.hits.hits[0]._source['editorial-metadata'];
printLog('Request to ES', editorialMetadata);
if (!editorialMetadata.isOpenAccess && editorialMetadata.isSample) {
printError('Proxy', 'Unauthorized');
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);
printLog('Proxy', 'Authorized');
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
}, ],
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
}, ],
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);
}