-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathborga-data-int-elastic.js
447 lines (423 loc) · 12.2 KB
/
borga-data-int-elastic.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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
"use strict";
const errors = require("./borga-errors");
const crypto = require("crypto");
const fetch = require("node-fetch");
const RandExp = require("randexp");
module.exports = function (es_spec, guest) {
const baseUrl = `${es_spec.url}`;
const usersURL = `${baseUrl}${es_spec.prefix}_users`;
const tokensURL = `${baseUrl}${es_spec.prefix}_tokens`;
const groupsURL = (username) =>
`${baseUrl}${es_spec.prefix}_${username}_groups`;
function createToken() {
return Buffer.from(crypto.randomUUID().replace(/-/g, ""), "hex")
.toString("base64")
.replace(/=/g, "");
}
function createId() {
return new RandExp(/^[a-zA-Z0-9]{16}$/).gen();
}
const assertDefined = (param, paramName) => {
if (!param) {
throw errors.MISSING_PARAM(`'${paramName}' is missing`);
}
return param;
};
function encode(string) {
return string.replace(/\//g, "%2F");
}
async function tokenToUsername(token) {
assertDefined(token, "token");
try {
const encodedToken = encode(token);
const response = await fetch(`${tokensURL}/_doc/${encodedToken}`);
const answer = await response.json();
return answer._source.username;
} catch (err) {
throw errors.FAILURE(err);
}
}
async function usernameToToken(username) {
assertDefined(username, "username");
if (!(await hasUser(username))) {
throw errors.NOT_FOUND(`user '${username}' was not found`);
}
try {
const size = 10;
let count = 0;
let from = 0;
let totalHits;
do {
const response = await fetch(
`${tokensURL}/_search?from=${from}&size=${size}`
);
const answer = await response.json();
for (const hit of answer.hits.hits) {
if (hit._source.username === username) {
return hit._id;
}
}
totalHits = answer.hits.total.value;
from += size;
} while (count < totalHits);
} catch (err) {
throw errors.FAILURE(err);
}
// Should never reach this code
throw errors.FAILURE(`Failed to find token for '${username}'`);
}
const hasUser = async (username) => {
assertDefined(username, "username");
try {
const response = await fetch(`${usersURL}/_doc/${username}`);
return response.status === 200;
} catch (err) {
throw errors.FAILURE(err);
}
};
async function hasGroup(username, groupId) {
assertDefined(username, "username");
assertDefined(groupId, "groupId");
if (!(await hasUser(username))) {
throw errors.NOT_FOUND(`user '${username}' was not found`);
}
try {
const response = await fetch(`${groupsURL(username)}/_doc/${groupId}`);
return response.status === 200;
} catch (err) {
throw errors.FAILURE(err);
}
}
async function hasGame(username, groupId, gameId) {
assertDefined(username, "username");
assertDefined(groupId, "groupId");
assertDefined(gameId, "gameId");
if (!(await hasUser(username))) {
throw errors.NOT_FOUND(`user '${username}' was not found`);
}
if (!(await hasGroup(username, groupId))) {
throw errors.NOT_FOUND(`group '${groupId}' was not found`);
}
try {
const response = await fetch(`${groupsURL(username)}/_doc/${groupId}`);
const answer = await response.json();
return answer._source.gameIds.includes(gameId);
} catch (err) {
throw errors.FAILURE(err);
}
}
async function listAllGroups(username) {
assertDefined(username, "username");
if (!(await hasUser(username))) {
throw errors.NOT_FOUND(`user '${username}' was not found`);
}
try {
const groups = [];
const size = 10;
let from = 0;
let totalHits;
do {
const response = await fetch(
`${groupsURL(username)}/_search?from=${from}&size=${size}`
);
const answer = await response.json();
answer.hits.hits.forEach((hit) => {
groups.push(Object.assign({ id: hit._id }, hit._source));
});
totalHits = answer.hits.total.value;
from += size;
} while (groups.length < totalHits);
return groups;
} catch (err) {
throw errors.FAILURE(err);
}
}
async function createUser(name, username, password) {
assertDefined(name, "name");
assertDefined(password, "password");
if (await hasUser(username)) {
throw errors.ALREADY_EXISTS(`user '${username}' already exists`);
}
const user = { name, password };
const token = createToken();
try {
const encodedToken = encode(token);
// Create groups index
let response = await fetch(`${groupsURL(username)}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
});
if (response.status === 200) {
// Add token
response = await fetch(
`${tokensURL}/_doc/${encodedToken}?refresh=wait_for`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username }),
}
);
if (response.status === 201) {
// Create user
response = await fetch(
`${usersURL}/_doc/${username}?refresh=wait_for`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(user),
}
);
if (response.status === 201) {
return token;
}
}
}
} catch (err) {
throw errors.FAILURE(err);
}
throw errors.EXT_SVC_FAILURE(`failed to create user '${username}'`);
}
async function getUser(username) {
assertDefined(username, "username");
try {
const response = await fetch(`${usersURL}/_doc/${username}`);
if (response.status === 200) {
const answer = await response.json();
return Object.assign({ username: answer._id }, answer._source);
}
} catch (err) {
throw errors.FAILURE(err);
}
throw errors.NOT_FOUND(`user '${username}' was not found`);
}
async function loadGroup(username, groupId) {
assertDefined(groupId, "groupId");
if (!(await hasUser(username))) {
throw errors.NOT_FOUND(`user '${username}' was not found`);
}
try {
const response = await fetch(`${groupsURL(username)}/_doc/${groupId}`);
if (response.status === 200) {
const answer = await response.json();
return answer._source;
}
} catch (err) {
throw errors.FAILURE(err);
}
throw errors.NOT_FOUND(`group '${groupId}' was not found`);
}
async function editGroup(username, groupId, newName, newDescription) {
assertDefined(newName, "newName");
assertDefined(newDescription, "newDescription");
if (!(await hasGroup(username, groupId))) {
throw errors.NOT_FOUND(`group '${groupId}' was not found`);
}
const updateObj = {
doc: {
name: newName,
description: newDescription,
},
};
try {
const response = await fetch(
`${groupsURL(username)}/_update/${groupId}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updateObj),
}
);
if (response.status === 200) {
return groupId;
}
} catch (err) {
throw errors.FAILURE(err);
}
throw errors.EXT_SVC_FAILURE(`failed to edit group '${groupId}'`);
}
async function deleteGroup(username, groupId) {
if (!(await hasGroup(username, groupId))) {
throw errors.NOT_FOUND(`group '${groupId}' was not found`);
}
try {
const response = await fetch(
`${groupsURL(username)}/_doc/${groupId}?refresh=wait_for`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
}
);
if (response.status === 200) {
return groupId;
}
} catch (err) {
throw errors.FAILURE(err);
}
throw errors.EXT_SVC_FAILURE(`failed to delete group '${groupId}'`);
}
async function createGroup(username, name, description) {
assertDefined(name, "name");
assertDefined(description, "description");
if (!(await hasUser(username))) {
throw errors.NOT_FOUND(`user '${username}' was not found`);
}
const groupObj = {
name: name,
description: description,
gameIds: [],
};
const groupId = createId();
try {
const response = await fetch(
`${groupsURL(username)}/_doc/${groupId}?refresh=wait_for`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(groupObj),
}
);
if (response.status === 201) {
return groupId;
}
} catch (err) {
throw errors.FAILURE(err);
}
throw errors.EXT_SVC_FAILURE(`failed to create group '${name}'`);
}
async function addGame(username, groupId, gameId) {
if (await hasGame(username, groupId, gameId)) {
throw errors.ALREADY_EXISTS(`game '${gameId}' already exists`);
}
const updateObj = {
script: {
source: `ctx._source.gameIds.add('${gameId}')`,
lang: "painless",
},
};
try {
const response = await fetch(
`${groupsURL(username)}/_update/${groupId}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updateObj),
}
);
if (response.status === 200) {
return gameId;
}
} catch (err) {
throw errors.FAILURE(err);
}
throw errors.EXT_SVC_FAILURE(`failed to add game '${gameId}'`);
}
async function removeGame(username, groupId, gameId) {
if (!(await hasGame(username, groupId, gameId))) {
throw errors.NOT_FOUND(`game '${gameId}' was not found`);
}
const updateObj = {
script: {
source: `ctx._source.gameIds.remove(ctx._source.gameIds.indexOf('${gameId}'))`,
lang: "painless",
},
};
try {
const response = await fetch(
`${groupsURL(username)}/_update/${groupId}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updateObj),
}
);
if (response.status === 200) {
return gameId;
}
} catch (err) {
throw errors.FAILURE(err);
}
throw errors.EXT_SVC_FAILURE(`failed to remove game '${gameId}'`);
}
async function createGuestUser() {
const username = guest.user;
const token = guest.token;
const password = guest.password;
const user = { name: "Guest", password };
try {
const encodedToken = encode(token);
let response = await fetch(`${groupsURL(username)}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
});
if (response.status === 200) {
response = await fetch(
`${tokensURL}/_doc/${encodedToken}?refresh=wait_for`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username }),
}
);
if (response.status === 201) {
response = await fetch(
`${usersURL}/_doc/${username}?refresh=wait_for`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(user),
}
);
if (response.status === 201) {
return token;
}
}
}
} catch (err) {
throw errors.FAILURE(err);
}
throw errors.EXT_SVC_FAILURE(`failed to create user '${username}'`);
}
createGuestUser()
.then((token) => {
console.log("Created guest user: ", token);
})
.catch((_) => {
// Failed to create guest user.
// Probably because it already exists
});
return {
getUser,
createUser,
tokenToUsername,
usernameToToken,
createGroup,
loadGroup,
editGroup,
listAllGroups,
deleteGroup,
addGame,
removeGame,
};
};