-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.js
302 lines (254 loc) · 10.2 KB
/
server.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
const jsonServer = require("./json-server");
const { validationsRoutes } = require("./routes/validations.route");
const { getConfigValue, getFeatureFlagConfigValue, isBugEnabled } = require("./config/config-manager");
const { ConfigKeys, FeatureFlagConfigKeys, BugConfigKeys } = require("./config/enums");
const fs = require("fs");
const path = require("path");
const cookieparser = require("cookie-parser");
const helmet = require("helmet");
const express = require("express");
const { getDbPath, countEntities, visitsData, initVisits } = require("./helpers/db.helpers");
const { formatErrorResponse, sleep } = require("./helpers/helpers");
const { logDebug, logError, logTrace } = require("./helpers/logger-api");
const {
HTTP_INTERNAL_SERVER_ERROR,
HTTP_CREATED,
HTTP_BAD_REQUEST,
HTTP_NOT_FOUND,
} = require("./helpers/response.helpers");
const {
customRoutes,
statsRoutes,
visitsRoutes,
queryRoutes,
onlyBackendRoutes,
homeRoutes,
} = require("./routes/custom.route");
const { fileUploadRoutes } = require("./routes/file-upload.route");
const { renderResponse } = require("./renders/custom.render");
const { healthCheckRoutes } = require("./routes/healthcheck.route");
const {
loginApiRoutes,
processLoginRoutes,
loginRoutes,
welcomeRoutes,
logoutRoutes,
} = require("./routes/login.route");
const { calcRoutes } = require("./routes/calc.route");
const bodyParser = require("body-parser");
const { randomErrorsRoutes } = require("./routes/error.route");
const { checkDatabase } = require("./helpers/sanity.check");
const { copyDefaultDbIfNotExists } = require("./helpers/setup");
const { getOriginMethod, getTracingInfo, getWasAuthorized } = require("./helpers/tracing-info.helper");
const { setEntitiesInactive, replaceRelatedContactsInDb } = require("./helpers/db-queries.helper");
const { diagnosticRoutes } = require("./routes/diagnostic.route");
const app = require("./app.json");
const DatabaseManager = require("./helpers/db.manager");
const { simpleMigrator, checkIfDbExists, overwriteDbIfDefined } = require("./db/migrators/migrator");
const { exitRoutes, restartRoutes } = require("./routes/debug.route");
const middlewares = jsonServer.defaults();
const port = process.env.PORT || getConfigValue(ConfigKeys.DEFAULT_PORT);
copyDefaultDbIfNotExists();
overwriteDbIfDefined();
simpleMigrator(getDbPath(getConfigValue(ConfigKeys.DB_PATH)), getDbPath(getConfigValue(ConfigKeys.DB_RESTORE_PATH)));
checkDatabase();
initVisits();
const server = jsonServer.create();
const router = jsonServer.router(getDbPath(getConfigValue(ConfigKeys.DB_PATH)));
const dbManager = DatabaseManager.getInstance();
dbManager.setDb(router.db);
server.use(diagnosticRoutes);
const clearDbRoutes = (req, res, next) => {
try {
const restoreDb = (dbPath, successMessage) => {
const db = JSON.parse(fs.readFileSync(path.join(__dirname, getConfigValue(dbPath)), "utf8"));
router.db.setState(db);
const entities = countEntities(db);
logDebug(successMessage, entities);
visitsData.generateVisits();
res.status(HTTP_CREATED).send({ message: successMessage, entities });
};
if (req.method === "GET" && req.url.includes("restore")) {
const url = req.url.replace(/\?.*$/, "").replace(/\/$/, "");
const urlLastPart = url.split("/").pop();
switch (urlLastPart) {
case "restoreDB":
restoreDb(ConfigKeys.DB_RESTORE_PATH, "Database successfully restored");
break;
case "restoreBigDB":
restoreDb(ConfigKeys.DB_BIG_RESTORE_PATH, "Big Database successfully restored");
break;
case "restoreDB2":
restoreDb(ConfigKeys.DB2_RESTORE_PATH, "Database successfully restored");
break;
case "restoreTinyDB":
restoreDb(ConfigKeys.DB_TINY_RESTORE_PATH, "Tiny Database successfully restored");
break;
case "restoreEmptyDB":
restoreDb(ConfigKeys.DB_EMPTY_RESTORE_PATH, "Empty Database successfully restored");
break;
case "restoreTestDB":
restoreDb(ConfigKeys.DB_TEST_RESTORE_PATH, "Test Database successfully restored");
break;
default:
logDebug("No action for restore", { url, req_url: req.url, urlLastPart });
res.status(HTTP_NOT_FOUND).send(formatErrorResponse("No action for restore", { parameter: urlLastPart }));
break;
}
}
if (res.headersSent !== true) {
next();
}
} catch (error) {
logError("Fatal error. Please contact administrator.", {
route: "clearDbRoutes",
error,
stack: error.stack,
});
res.status(HTTP_INTERNAL_SERVER_ERROR).send(formatErrorResponse("Fatal error. Please contact administrator."));
}
};
server.get(/.*/, onlyBackendRoutes);
server.use((req, res, next) => {
if (getFeatureFlagConfigValue(FeatureFlagConfigKeys.FEATURE_CACHE_CONTROL_NO_STORE)) {
res.header("Cache-Control", "no-store");
}
next();
});
server.use(healthCheckRoutes);
// actions invoked just before returning response
server.use((req, res, next) => {
res.on("finish", function () {
// TODO: add your custom logic here
});
next();
});
server.use(middlewares);
server.use((req, res, next) => {
bodyParser.json()(req, res, (err) => {
if (err) {
logError("SyntaxError: Unexpected data in JSON - Please check Your JSON.", { err: JSON.stringify(err) });
return res
.status(HTTP_BAD_REQUEST)
.json({ error: "SyntaxError: Unexpected data in JSON. Please check Your JSON.", details: err?.body });
}
next();
});
});
server.use(jsonServer.bodyParser);
server.use(helmet());
server.use(cookieparser());
// allow the express server to read and render the static css file
server.use(express.static(path.join(__dirname, "public", "login")));
server.set("view engine", "ejs");
// render the ejs views
server.set("views", path.join(__dirname, "public", "login"));
server.get("/home", homeRoutes);
// Login to one of the users from ./users.json
server.post("/api/login", loginApiRoutes);
server.post("/process_login", processLoginRoutes);
server.get("/login", loginRoutes);
server.get("/welcome", welcomeRoutes);
server.get("/logout", logoutRoutes);
server.get("/api/debug/restart", restartRoutes);
server.get("/api/debug/exit", exitRoutes);
server.use(clearDbRoutes);
server.use(statsRoutes);
server.use(visitsRoutes);
server.use(queryRoutes);
server.use(customRoutes);
server.use(randomErrorsRoutes);
server.use(validationsRoutes);
server.use(fileUploadRoutes);
server.use(calcRoutes);
server.use(function (req, res, next) {
// soft delete articles:
if (getOriginMethod(req) === "DELETE" && getWasAuthorized(req) === true && req.url.includes("articles")) {
const tracingInfo = getTracingInfo(req);
logTrace("SOFT_DELETE: articles -> soft deleting comments", { url: req.url, tracingInfo });
const bugEnabled = isBugEnabled(BugConfigKeys.BUG_DELAY_SOFT_DELETE_COMMENTS);
let timeout = 0;
if (bugEnabled) {
timeout = getConfigValue(ConfigKeys.COMMENTS_SOFT_DELETE_DELAY_IN_SECONDS_BUG) * 1000;
}
sleep(timeout, bugEnabled ?? "Bug for SOFT_DELETE was enabled").then(() => {
setEntitiesInactive(router.db, "comments", { article_id: parseInt(tracingInfo.resourceId) });
setEntitiesInactive(router.db, "comments", { article_id: tracingInfo.resourceId });
});
}
// soft delete users:
if (getOriginMethod(req) === "DELETE" && getWasAuthorized(req) === true && req.url.includes("users")) {
const isFeatureEnabled = getFeatureFlagConfigValue(FeatureFlagConfigKeys.FEATURE_SOFT_DELETE_USERS);
if (isFeatureEnabled === true) {
const tracingInfo = getTracingInfo(req);
logTrace("SOFT_DELETE: users -> soft deleting articles", { url: req.url, tracingInfo });
const query = { user_id: parseInt(tracingInfo.resourceId) };
const query2 = { user_id: tracingInfo.resourceId };
setEntitiesInactive(router.db, "articles", query);
setEntitiesInactive(router.db, "comments", query);
setEntitiesInactive(router.db, "articles", query2);
setEntitiesInactive(router.db, "comments", query2);
}
}
// add contacts:
if (
getOriginMethod(req) === "PUT" &&
getWasAuthorized(req) === true &&
req.url.includes("contacts") &&
(res.statusCode === 200 || res.statusCode === 201)
) {
const tracingInfo = getTracingInfo(req);
logDebug("UPDATE: /messenger/contacts", { url: req.url, tracingInfo });
replaceRelatedContactsInDb(router.db, parseInt(tracingInfo.targetResourceId), tracingInfo.targetResource);
}
next();
});
server.use("/api", router);
router.render = renderResponse;
server.use(function (req, res, next) {
logTrace("Hit 404:", { url: req.url });
res.status(404);
// respond with html page
if (req.accepts("html")) {
res.render("404", { url: req.url });
return;
}
// respond with json
if (req.accepts("json")) {
res.json({ error: "Not found" });
return;
}
// default to plain-text. send()
res.type("txt").send("Not found");
});
const sslEnabled = getConfigValue(ConfigKeys.SSL_ENABLED);
if (sslEnabled !== true) {
logDebug(`Starting 🦎 GAD on port ${port}...`);
logDebug(`--------------------------------`);
var serverApp = server.listen(port, () => {
logDebug(`🦎 GAD listening on ${port}!`);
var address = serverApp.address().address;
address = address == "::" ? "localhost" : "localhost";
logDebug(`Visit it on -> http://${address}:${port}`);
logDebug(`🎉 Your custom 🦎 GAD (${app.version}) is up and running!!!`);
});
} else {
logDebug(`Starting 🔒 SSL 🦎 GAD on port ${port}...`);
logDebug(`--------------------------------`);
const options = {
key: fs.readFileSync(path.join(__dirname, "./certs/ca-key.pem")),
cert: fs.readFileSync(path.join(__dirname, "./certs/ca-cert.pem")),
};
const https = require("https");
const sslServer = https.createServer(options, server);
sslServer.listen(port, () => {
logDebug(`🔒 SSL 🦎 GAD listening on ${port}!`);
let address = sslServer.address().address;
address = address == "::" ? "localhost" : "localhost";
logDebug(`Visit it on -> https://${address}:${port}`);
logDebug(`🎉 Your custom 🔒 SSL 🦎 GAD (${app.version}) is up and running!!!`);
});
}
module.exports = {
serverApp,
};