Skip to content

Commit e7a0448

Browse files
authored
Merge pull request #306 from CyferShepard/unstable
backup fix hotfix
2 parents 6e10542 + 6bfaaa7 commit e7a0448

File tree

2 files changed

+64
-82
lines changed

2 files changed

+64
-82
lines changed

backend/routes/backup.js

Lines changed: 60 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1-
const express = require('express');
2-
const { Pool } = require('pg');
3-
const fs = require('fs');
4-
const path = require('path');
5-
const { randomUUID } = require('crypto');
6-
const multer = require('multer');
7-
8-
const Logging = require('../classes/logging');
9-
const backup = require('../classes/backup');
10-
const triggertype = require('../logging/triggertype');
11-
const taskstate = require('../logging/taskstate');
12-
const taskName = require('../logging/taskName');
13-
const sanitizeFilename = require('../utils/sanitizer');
14-
15-
const { sendUpdate } = require('../ws');
16-
const db = require('../db');
1+
const express = require("express");
2+
const { Pool } = require("pg");
3+
const fs = require("fs");
4+
const path = require("path");
5+
const { randomUUID } = require("crypto");
6+
const multer = require("multer");
7+
8+
const Logging = require("../classes/logging");
9+
const backup = require("../classes/backup");
10+
const triggertype = require("../logging/triggertype");
11+
const taskstate = require("../logging/taskstate");
12+
const taskName = require("../logging/taskName");
13+
const sanitizeFilename = require("../utils/sanitizer");
14+
15+
const { sendUpdate } = require("../ws");
16+
const db = require("../db");
1717

1818
const router = express.Router();
1919

@@ -22,14 +22,14 @@ const postgresUser = process.env.POSTGRES_USER;
2222
const postgresPassword = process.env.POSTGRES_PASSWORD;
2323
const postgresIp = process.env.POSTGRES_IP;
2424
const postgresPort = process.env.POSTGRES_PORT;
25-
const postgresDatabase = process.env.POSTGRES_DB || 'jfstat';
26-
const backupfolder = 'backup-data';
25+
const postgresDatabase = process.env.POSTGRES_DB || "jfstat";
26+
const backupfolder = "backup-data";
2727

2828
// Restore function
2929

3030
function readFile(path) {
3131
return new Promise((resolve, reject) => {
32-
fs.readFile(path, 'utf8', (err, data) => {
32+
fs.readFile(path, "utf8", (err, data) => {
3333
if (err) {
3434
reject(err);
3535
return;
@@ -41,10 +41,10 @@ function readFile(path) {
4141
}
4242

4343
async function restore(file, refLog) {
44-
refLog.logData.push({ color: 'lawngreen', Message: 'Starting Restore' });
44+
refLog.logData.push({ color: "lawngreen", Message: "Starting Restore" });
4545
refLog.logData.push({
46-
color: 'yellow',
47-
Message: 'Restoring from Backup: ' + file,
46+
color: "yellow",
47+
Message: "Restoring from Backup: " + file,
4848
});
4949
const pool = new Pool({
5050
user: postgresUser,
@@ -63,7 +63,7 @@ async function restore(file, refLog) {
6363
jsonData = await readFile(backupPath);
6464
} catch (err) {
6565
refLog.logData.push({
66-
color: 'red',
66+
color: "red",
6767
key: tableName,
6868
Message: `Failed to read backup file`,
6969
});
@@ -73,46 +73,46 @@ async function restore(file, refLog) {
7373

7474
// console.log(jsonData);
7575
if (!jsonData) {
76-
console.log('No Data');
76+
console.log("No Data");
7777
return;
7878
}
7979

8080
for (let table of jsonData) {
8181
const data = Object.values(table)[0];
8282
const tableName = Object.keys(table)[0];
8383
refLog.logData.push({
84-
color: 'dodgerblue',
84+
color: "dodgerblue",
8585
key: tableName,
8686
Message: `Restoring ${tableName}`,
8787
});
8888
for (let index in data) {
89-
const keysWithQuotes = Object.keys(data[index]).map(key => `"${key}"`);
90-
const keyString = keysWithQuotes.join(', ');
89+
const keysWithQuotes = Object.keys(data[index]).map((key) => `"${key}"`);
90+
const keyString = keysWithQuotes.join(", ");
9191

92-
const valuesWithQuotes = Object.values(data[index]).map(col => {
92+
const valuesWithQuotes = Object.values(data[index]).map((col) => {
9393
if (col === null) {
94-
return 'NULL';
95-
} else if (typeof col === 'string') {
94+
return "NULL";
95+
} else if (typeof col === "string") {
9696
return `'${col.replace(/'/g, "''")}'`;
97-
} else if (typeof col === 'object') {
97+
} else if (typeof col === "object") {
9898
return `'${JSON.stringify(col).replace(/'/g, "''")}'`;
9999
} else {
100100
return `'${col}'`;
101101
}
102102
});
103103

104-
const valueString = valuesWithQuotes.join(', ');
104+
const valueString = valuesWithQuotes.join(", ");
105105

106106
const query = `INSERT INTO ${tableName} (${keyString}) VALUES(${valueString}) ON CONFLICT DO NOTHING`;
107107
const { rows } = await pool.query(query);
108108
}
109109
}
110110
await pool.end();
111-
refLog.logData.push({ color: 'lawngreen', Message: 'Restore Complete' });
111+
refLog.logData.push({ color: "lawngreen", Message: "Restore Complete" });
112112
}
113113

114114
// Route handler for backup endpoint
115-
router.get('/beginBackup', async (req, res) => {
115+
router.get("/beginBackup", async (req, res) => {
116116
try {
117117
const last_execution = await db
118118
.query(
@@ -122,11 +122,11 @@ router.get('/beginBackup', async (req, res) => {
122122
ORDER BY "TimeRun" DESC
123123
LIMIT 1`
124124
)
125-
.then(res => res.rows);
125+
.then((res) => res.rows);
126126

127127
if (last_execution.length !== 0) {
128128
if (last_execution[0].Result === taskstate.RUNNING) {
129-
sendUpdate('TaskError', 'Error: Backup is already running');
129+
sendUpdate("TaskError", "Error: Backup is already running");
130130
res.send();
131131
return;
132132
}
@@ -137,50 +137,44 @@ router.get('/beginBackup', async (req, res) => {
137137
await Logging.insertLog(uuid, triggertype.Manual, taskName.backup);
138138
await backup(refLog);
139139
Logging.updateLog(uuid, refLog.logData, taskstate.SUCCESS);
140-
res.send('Backup completed successfully');
141-
sendUpdate('TaskComplete', { message: triggertype + ' Backup Completed' });
140+
res.send("Backup completed successfully");
141+
sendUpdate("TaskComplete", { message: triggertype + " Backup Completed" });
142142
} catch (error) {
143143
console.error(error);
144-
res.status(500).send('Backup failed');
144+
res.status(500).send("Backup failed");
145145
}
146146
});
147147

148-
router.get('/restore/:filename', async (req, res) => {
148+
router.get("/restore/:filename", async (req, res) => {
149149
try {
150150
const uuid = randomUUID();
151151
let refLog = { logData: [], uuid: uuid };
152152
Logging.insertLog(uuid, triggertype.Manual, taskName.restore);
153153

154154
const filename = sanitizeFilename(req.params.filename);
155-
const filePath = path.join(
156-
process.cwd(),
157-
__dirname,
158-
'..',
159-
backupfolder,
160-
filename
161-
);
155+
const filePath = path.join(__dirname, "..", backupfolder, filename);
162156

163157
await restore(filePath, refLog);
164158
Logging.updateLog(uuid, refLog.logData, taskstate.SUCCESS);
165159

166-
res.send('Restore completed successfully');
167-
sendUpdate('TaskComplete', { message: 'Restore completed successfully' });
160+
res.send("Restore completed successfully");
161+
sendUpdate("TaskComplete", { message: "Restore completed successfully" });
168162
} catch (error) {
169163
console.error(error);
170-
res.status(500).send('Restore failed');
164+
res.status(500).send("Restore failed");
171165
}
172166
});
173167

174-
router.get('/files', (req, res) => {
168+
router.get("/files", (req, res) => {
175169
try {
176-
const directoryPath = path.join(__dirname, '..', backupfolder);
170+
const directoryPath = path.join(__dirname, "..", backupfolder);
177171
fs.readdir(directoryPath, (err, files) => {
178172
if (err) {
179-
res.status(500).send('Unable to read directory');
173+
res.status(500).send("Unable to read directory");
180174
} else {
181175
const fileData = files
182-
.filter(file => file.endsWith('.json'))
183-
.map(file => {
176+
.filter((file) => file.endsWith(".json"))
177+
.map((file) => {
184178
const filePath = path.join(directoryPath, file);
185179
const stats = fs.statSync(filePath);
186180
return {
@@ -198,48 +192,36 @@ router.get('/files', (req, res) => {
198192
});
199193

200194
//download backup file
201-
router.get('/files/:filename', (req, res) => {
195+
router.get("/files/:filename", (req, res) => {
202196
const filename = sanitizeFilename(req.params.filename);
203-
const filePath = path.join(
204-
process.cwd(),
205-
__dirname,
206-
'..',
207-
backupfolder,
208-
filename
209-
);
197+
const filePath = path.join(__dirname, "..", backupfolder, filename);
210198
res.download(filePath);
211199
});
212200

213201
//delete backup
214-
router.delete('/files/:filename', (req, res) => {
202+
router.delete("/files/:filename", (req, res) => {
215203
try {
216204
const filename = sanitizeFilename(req.params.filename);
217-
const filePath = path.join(
218-
process.cwd(),
219-
__dirname,
220-
'..',
221-
backupfolder,
222-
filename
223-
);
224-
225-
fs.unlink(filePath, err => {
205+
const filePath = path.join(__dirname, "..", backupfolder, filename);
206+
207+
fs.unlink(filePath, (err) => {
226208
if (err) {
227209
console.error(err);
228-
res.status(500).send('An error occurred while deleting the file.');
210+
res.status(500).send("An error occurred while deleting the file.");
229211
return;
230212
}
231213

232214
console.log(`${filePath} has been deleted.`);
233215
res.status(200).send(`${filePath} has been deleted.`);
234216
});
235217
} catch (error) {
236-
res.status(500).send('An error occurred while deleting the file.');
218+
res.status(500).send("An error occurred while deleting the file.");
237219
}
238220
});
239221

240222
const storage = multer.diskStorage({
241223
destination: function (req, file, cb) {
242-
cb(null, path.join(__dirname, '..', backupfolder)); // Set the destination folder for uploaded files
224+
cb(null, path.join(__dirname, "..", backupfolder)); // Set the destination folder for uploaded files
243225
},
244226
filename: function (req, file, cb) {
245227
cb(null, file.originalname); // Set the file name
@@ -248,7 +230,7 @@ const storage = multer.diskStorage({
248230

249231
const upload = multer({ storage: storage });
250232

251-
router.post('/upload', upload.single('file'), (req, res) => {
233+
router.post("/upload", upload.single("file"), (req, res) => {
252234
// Handle the uploaded file here
253235
res.json({
254236
fileName: req.file.originalname,
@@ -258,7 +240,7 @@ router.post('/upload', upload.single('file'), (req, res) => {
258240

259241
// Handle other routes
260242
router.use((req, res) => {
261-
res.status(404).send({ error: 'Not Found' });
243+
res.status(404).send({ error: "Not Found" });
262244
});
263245

264246
module.exports = router;

backend/utils/sanitizer.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
const sanitizer = require("sanitize-filename");
1+
const sanitizeFilename = require("sanitize-filename");
22

3-
const sanitizeFilename = (filename) => {
4-
return sanitizer(filename);
3+
const sanitizeFile = (filename) => {
4+
return sanitizeFilename(filename);
55
};
66

7-
module.export = { sanitizeFilename };
7+
module.exports = sanitizeFile;

0 commit comments

Comments
 (0)