-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
278 lines (251 loc) · 8.11 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
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
// helper middleware for express requests with logging and error handling
const fs = require('fs');
const log = require('rf-log').customPrefixLogger('[rf-api-simple]');
const jwt = require('jsonwebtoken');
const rfHttp = require('rf-http');
module.exports = {
createApi
};
function createApi (config, apiCallbackFunction) {
config = config || {};
// import webserver path from rf-config
if (config.paths) {
if (config.paths.webserver) config.pathsWebserver = config.paths.webserver;
if (config.paths.apis) config.pathsApis = config.paths.apis;
}
const defaultConfig = {
port: 4000,
pathsWebserver: 'dest',
// pathsApis: 'server/apis', // no default
bodyParserLimitSize: '110mb',
devMode: false,
sessionSecret: null,
expiresIn: false
};
// use default options if not defined
for (var key in defaultConfig) {
if (!config[key] && config[key] !== false) config[key] = defaultConfig[key];
}
// init
let http = rfHttp.start(config);
let expressApp = http.app;
if (config.pathsApis && apiCallbackFunction) {
log.success(`starting apis under ${config.pathsApis}`);
// dirty trick: wait till API was returned, so it can be used for the start function
setTimeout(function () {
startApiFiles(config.pathsApis, apiCallbackFunction);
}, 100);
} else if (apiCallbackFunction && !config.pathsApis) {
log.error(`apiCallbackFunction defined but no config.pathsApis`);
} else if (!apiCallbackFunction && config.pathsApis) {
log.error(`config.pathsApis defined but no apiCallbackFunction`);
}
return {
prefix: '/api/',
app: expressApp,
server: http.server, // return of "app.listen"
close, // stop webserver
startApi, // start everything
generateToken,
checkToken,
// HTTP helper functions to shorten the code
get,
post
};
function close () {
if (http && http.server) {
http.server.close();
http = {};
}
}
function startApi (callback) {
startApiFiles(config.pathsApis, callback);
}
function generateToken (user, sessionSecret, rights) {
let data = JSON.parse(JSON.stringify(user));
if (data.firstname) data.firstname = b64EncodeUnicode(user.firstname);
if (data.lastname) data.lastname = b64EncodeUnicode(user.lastname);
if (rights) user.rights = rights;
if (sessionSecret) config.sessionSecret = sessionSecret;
let expiresIn = config.expiresIn || 60 * 60 * 168; // 1 week as default
return jwt.sign(data, config.sessionSecret, expiresIn);
}
function checkToken (settings, req) {
var decoded = {};
var token = req.body.token || req.query.token || req.headers['x-access-token'];
var err = new Error();
if (token) {
try {
decoded = jwt.verify(token, config.sessionSecret, { ignoreExpiration: true });
} catch (e) {
err.code = 498;
err.message = 'Bad Request - Invalid Token';
}
}
return new Promise(function (resolve, reject) {
if (settings.permission === false) {
if (decoded) {
resolve(decoded);
} else {
resolve();
}
} else if (decoded && decoded.rights && decoded.rights.indexOf(settings.section) !== -1) {
resolve(decoded);
} else {
err.code = 401;
reject(err);
}
});
}
function get (endpointName, func, settings) {
if (!settings) return log.critical(`endpoint ${endpointName} has no settings defined!`);
if (settings.realGet) {
apiSend(expressApp, endpointName, func, settings, 'realGet', this);
} else {
apiSend(expressApp, endpointName, func, settings, 'get', this);
}
}
function post (endpointName, func, settings) {
if (!settings) return log.critical(`endpoint ${endpointName} has no settings defined!`);
apiSend(expressApp, endpointName, func, settings, 'post', this);
}
}
function apiSend (app, functionName, func, settings, method, self) {
var options = getOptions(method);
var endPoint = self.prefix + options.methodPrefix + functionName;
app[options.httpMethod](endPoint, function (req, res) {
// Log request
if (!settings.logDisabled) log.info(options.log + ': ' + functionName);
res = new Response(res);
req.body = req.body || {};
req.body.data = req.body.data || {};
let request = {
data: req.body.data,
originalRequest: req
};
self.checkToken(settings, req).then(function (decoded) {
request.user = decoded || {};
request.rights = decoded.rights || [];
delete request.user.rights;
func(request, res);
}).catch(function (e) {
if (e.code === 401) {
res.errorAuthorizationRequired(`${functionName} token invalid! ${e.message}`);
} else {
log.error(e);
res.errorAccessDenied(`${functionName} not allowed! ${e.message}`);
}
});
});
}
function getOptions (method) {
return {
get: {
methodPrefix: 'get-',
log: 'GET',
httpMethod: 'post'
},
realGet: {
methodPrefix: '',
log: 'GET',
httpMethod: 'get'
},
post: {
methodPrefix: 'post-',
log: 'POST',
httpMethod: 'post'
}
}[method];
}
function Response (res) {
var self = this;
self.send = function (err, docs, callback) {
if (!err && callback && typeof (callback) === 'function') {
callback(docs);
} else {
send(err, docs, res);
}
};
self.error = function (err) {
err = handleError(err);
send('Server Error: ' + err, null, res, 500);
log.error('Server Error: ' + err);
};
self.errorBadRequest = function (err) {
send('Bad request: ' + err, null, res, 400);
};
self.errorAuthorizationRequired = function (msg) {
send(`Authorization required! ${msg || ''}`, null, res, 401);
};
self.errorAccessDenied = function (err) {
send('Access denied: ' + err, null, res, 403);
};
function send (err, docs, res, status) { // handle requests
if (err) {
status = status || 500;
err = handleError(err);
res
.status(status)
.send(err)
.end();
} else { // success; last step
status = status || 200;
res
.status(status)
.json(docs)
.end();
}
}
function handleError (err) {
// return the required error string for the response
if (typeof err === 'object') {
// MongoDB Unique Error
if (err.code === 11000) return err.errmsg;
// else
return JSON.stringify(err);
}
return err;
}
}
function startApiFiles (apiPath, callback) {
try {
var paths = getDirectoryPaths(apiPath);
paths.forEach(function (path) {
var apiStartFunction = require(path).start;
callback(apiStartFunction);
});
} catch (err) {
log.critical(err);
}
function getDirectoryPaths (path) {
var pathList = [];
fs.readdirSync(path).forEach(function (file) {
var filePath = path + '/' + file;
var stat = fs.statSync(filePath);
if (stat && stat.isDirectory()) {
pathList = pathList.concat(getDirectoryPaths(filePath));
} else if (file[0] !== '.') {
pathList.push(path + '/' + file.split('.')[0]);
}
});
return pathList;
}
}
function b64EncodeUnicode (str) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
return btoaNode(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes (match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function btoaNode (str) {
var buffer;
if (str instanceof Buffer) {
buffer = str;
} else {
buffer = Buffer.from(str.toString(), 'binary');
}
return buffer.toString('base64');
}