-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (63 loc) · 2.24 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
const express = require('express');
const app = express();
const port = 80;
const fs = require('fs');
const multer = require('multer');
const upload = multer({dest: 'uploads/'});
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const ejs = require('ejs');
const rateLimit = require('express-rate-limit');
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 2 // limit each IP to 2 requests per windowMs
});
app.use('/upload', limiter);
app.use('/download', limiter);
const bandwidthLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 10000000 // limit each IP to 10MB per windowMs
});
app.use('/download', bandwidthLimiter);
app.use((req, res, next) => {
statusCodes = [404, 500, 400, 401, 403, 405, 406, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 421, 422, 423, 424, 425, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511];
if (statusCodes.includes(res.statusCode)) {
errorMessage = `${res.statusCode}`;
res.render('error', {error: errorMessage});
}
next();
});
app.get('/', (req, res) => {
res.render('index');
});
app.post('/upload', upload.single('file'), (req, res) => {
const maxFileSize = 100000000;
if (req.file.size > maxFileSize) {
res.render('error', {error: 'File size is too large'});
return;
}
const file = req.file;
const id = uuidv4();
const fileExtension = file.originalname.split('.').pop();
fs.rename(file.path, `uploads/${id}.${fileExtension}`, (err) => {
if (err) {
res.render('error', {error: 'File could not be uploaded'});
return;
}
});
res.render('success', {id: `${id}.${fileExtension}`});
});
app.get('/download/:id', (req, res) => {
const file = fs.readFileSync(`uploads/${req.params.id}`);
res.set('Content-Disposition', `attachment; filename=${req.params.id}`);
res.send(file);
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});