-
Notifications
You must be signed in to change notification settings - Fork 1
/
apiUtils.js
68 lines (57 loc) · 1.84 KB
/
apiUtils.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
'use strict';
const fs = require('fs');
const padManager = require('ep_etherpad-lite/node/db/PadManager');
const settings = require('ep_etherpad-lite/node/utils/Settings');
// ensure we have an apiKey
let apiKey = '';
try {
apiKey = fs.readFileSync('./APIKEY.txt', 'utf8').trim();
} catch (e) {
console.warn('Could not find APIKEY');
}
// Checks if api key is correct and prepare response if it is not.
// Returns true if valid, false otherwise.
exports.validateApiKey = (fields, res) => {
let valid = true;
const apiKeyReceived = fields.apikey || fields.api_key;
if (apiKeyReceived !== apiKey) {
res.statusCode = 401;
res.json({code: 4, message: 'no or wrong API Key', data: null});
valid = false;
}
return valid;
};
const isValid = (originalFields, fieldName) => (typeof originalFields[fieldName] !== 'undefined');
// Checks if required fields are present, and prepare response if any of them
// is not. Returns true if valid, false otherwise.
exports.validateRequiredFields = (originalFields, requiredFields, res) => {
for (const i of requiredFields) {
const requiredField = requiredFields[i];
if (!isValid(originalFields, requiredField)) {
const errorMessage = `${requiredField} is required`;
res.json({code: 1, message: errorMessage, data: null});
return false;
}
}
return true;
};
// Sanitizes pad id and returns it:
exports.sanitizePadId = (req) => {
let padIdReceived = req.params.pad;
padManager.sanitizePadId(padIdReceived, (padId) => {
padIdReceived = padId;
});
return padIdReceived;
};
// Builds url for message broadcasting, based on settings.json and on the
// given endPoint:
exports.broadcastUrlFor = (endPoint) => {
let url = '';
if (settings.ssl) {
url += 'https://';
} else {
url += 'http://';
}
url += `${settings.ip}:${settings.port}${endPoint}`;
return url;
};