forked from buerokratt/DataMapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
288 lines (255 loc) · 7.92 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
import express from "express";
import { create, engine } from "express-handlebars";
import setRateLimit from "express-rate-limit";
import { body, matchedData, validationResult } from "express-validator";
import jsdom from "jsdom";
const { JSDOM } = jsdom;
import Papa from "papaparse";
import secrets from "./controllers/secrets.js";
import fs from "fs";
import files from "./controllers/files.js";
import crypto from "crypto";
import bodyParser from "body-parser";
import encryption from "./controllers/encryption.js";
import decryption from "./controllers/decryption.js";
import * as path from "path";
import { fileURLToPath } from "url";
import sendMockEmail from "./js/email/sendMockEmail.js";
import { generatePdf } from "./js/generate/pdf.js";
import { generatePdfToBase64 } from "./js/generate/pdfToBase64.js";
import { generateHTMLTable } from "./js/convert/pdf.js";
import * as helpers from "./lib/helpers.js";
import {
buildContentFilePath,
getHeadersMapping,
parseBoolean,
} from "./js/util/utils.js";
import base64ToText from "./js/util/base64ToText.js";
import conversion from "./controllers/conversion.js";
import ruuter from "./controllers/ruuter.js";
import merge from "./controllers/merge.js";
import mergeYaml from "./js/file/mergeYaml.js";
import readFullFile from "./js/file/read-file.js";
import cron from "./controllers/cron.js";
import object from "./controllers/object.js";
import validate from "./controllers/validate.js";
import utils from "./controllers/utils.js";
import domain from "./controllers/domain.js";
import forms from "./controllers/forms.js";
import { requestLoggerMiddleware } from "./lib/requestLoggerMiddleware.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
});
const hbs = create({ helpers });
const PORT = process.env.PORT || 3000;
const app = express().disable("x-powered-by");
const rateLimit = setRateLimit({
windowMs: 60 * 1000,
max: 30,
message: "Too many requests",
headers: true,
statusCode: 429,
});
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(requestLoggerMiddleware({ logger: console.log }));
app.use(express.json());
app.use("/file-manager", files);
app.use("/conversion", conversion);
app.use("/ruuter", ruuter);
app.use("/merge", merge);
app.use("/mergeYaml", mergeYaml);
app.use("/cron", cron);
app.use("/object", object);
app.use("/validate", validate);
app.use("/utils", utils);
app.use("/domain", domain);
app.use("/forms", forms);
app.use(express.urlencoded({ extended: true }));
app.use(
"/encryption",
encryption({
publicKey: publicKey,
privateKey: privateKey,
})
);
app.use(
"/decryption",
decryption({
publicKey: publicKey,
privateKey: privateKey,
})
);
app.use(express.json({limit: '2Mb'}));
const handled = (controller) => async (req, res, next) => {
try {
await controller(req, res);
} catch (error) {
return next(error.message);
}
};
const EXTENSION = process.env.EXTENSION || ".handlebars";
app.engine(
".handlebars",
engine({
layoutsDir: path.join(__dirname, "views/layouts"),
})
);
app.engine(".hbs", hbs.engine);
app.set("views", ["./views", "./module/*/hbs/"]);
app.use("/secrets", secrets);
app.get(
"/",
handled(async (req, res, next) => {
res.render(__dirname + "/views/home.handlebars", { title: "Home" });
})
);
const handleRender = (req, res, templatePath) => {
res.render(templatePath, { ...req.body, helpers }, (err, response) => {
if (err) console.log("err:", err);
if (req.get("type") === "csv") {
res.json({ response });
} else if (req.get("type") === "json") {
if (response === undefined) {
res.json({
error: `There was an error executing ${templatePath}`,
});
} else {
res.json(JSON.parse(response));
}
} else {
res.send(response);
}
});
};
app.post(
"/hbs/*",
rateLimit,
handled(async (req, res) => {
const normalizedParams = path
.normalize(req.params[0])
.replace(/^(\.\.(\/|\\|$))+/, "");
const templatePath =
__dirname + "/views/" + normalizedParams + ".handlebars";
handleRender(req, res, templatePath);
})
);
app.post(
"/:project/hbs/*",
handled(async (req, res) => {
const project = req.params["project"];
const normalizedParams = path
.normalize(req.params[0])
.replace(/^(\.\.(\/|\\|$))+/, "");
const templatePath =
__dirname + "/module/" + project + "/hbs/" + normalizedParams + EXTENSION;
handleRender(req, res, templatePath);
})
);
app.post(
"/js/convert/pdf",
[
body("messages")
.isArray()
.withMessage("messages is required and must be an array"),
body("csaTitleVisible")
.isString()
.withMessage("csaTitleVisible is required and must be a string"),
body("csaNameVisible")
.isString()
.withMessage("csaNameVisible is required and must be a string"),
],
rateLimit,
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { messages, csaTitleVisible, csaNameVisible } = matchedData(req);
const template = fs
.readFileSync(__dirname + "/views/pdf.handlebars")
.toString();
const dom = new JSDOM(template);
generateHTMLTable(
dom.window.document.getElementById("chatHistoryTable"),
messages,
parseBoolean(csaTitleVisible),
parseBoolean(csaNameVisible)
);
generatePdfToBase64(dom.window.document.documentElement.innerHTML, res);
}
);
app.post("/js/generate/pdf", (req, res) => {
const filename = req.body.filename;
const template = req.body.template;
generatePdf(filename, template, res);
});
app.post(
"/parse-csv-to-opensearch-data",
[
body("file_path")
.isString()
.withMessage("file_path is required and must be a string"),
body("csv_type")
.isString()
.optional()
.withMessage("csv_type must be a string"),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { file_path, csv_type } = matchedData(req);
const readResult = await readFullFile(buildContentFilePath(file_path), res);
let file = base64ToText(readResult.file);
const headersMapping = getHeadersMapping(csv_type);
// Needed when csv second row is a header
if (csv_type === "municipalities") {
file = file.split("\n").slice(1).join("\n");
}
const result = Papa.parse(file, {
skipEmptyLines: true,
header: true,
transformHeader: (header) => {
if (headersMapping.hasOwnProperty(header)) {
return headersMapping[header];
} else {
return header;
}
},
});
let bulkData = "";
result.data.forEach((item) => {
bulkData += JSON.stringify({ index: {} }) + "\n";
bulkData += JSON.stringify(item) + "\n";
});
res.send(bulkData);
}
);
app.get("/js/*", rateLimit, (req, res) => {
const normalizedPath = path
.normalize(req.path)
.replace(/^(\.\.(\/|\\|$))+/, "");
const resolvedPath = path.join(__dirname, normalizedPath + ".js");
res.contentType("text/plain").send(fs.readFileSync(resolvedPath).toString());
});
// NOTE: This service is only for testing purposes. Needs to be replaced with actual mail service.
app.post("/js/email/*", (req, res) => {
const { to, subject, text } = req.body;
try {
sendMockEmail(to, subject, text);
res.contentType("text/plain").send(`email sent to: ${to}`);
} catch (err) {
res.errored(err);
}
});
app.post("/example/post", (req, res) => {
console.log(`POST endpoint received ${JSON.stringify(req.body)}`);
res.status(200).json({ message: `received value ${req.body.name}` });
});
app.get("/status", (req, res) => res.status(200).send("ok"));
app.listen(PORT, () => {
console.log("Nodejs server running on http://localhost:%s", PORT);
});