-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
213 lines (180 loc) · 5.8 KB
/
index.mjs
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
import http from 'node:http';
import express from 'express';
import enforce from 'express-sslify';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import dotenv from 'dotenv';
import fs from 'fs';
import rateLimit from 'express-rate-limit';
import { createClient, commandOptions } from 'redis';
import Utils from './utils/utils.mjs';
const utils = new Utils();
import path from 'path';
const dynamicEnvs = {
YEAR: new Date().getFullYear(),
};
const limiterMiddleware = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
utils.patch_env(process.env, dynamicEnvs) && dotenv.config({ path: `.env.${process.env.NODE_ENV}` });
const app = express();
const middleware = [
cors(),
helmet.contentSecurityPolicy({
useDefaults: true,
directives: {
'img-src': ['\'self\'', 'https: data:'],
'script-src': ['\'self\'', 'https: data:'],
'default-src': ['\'self\'', 'https: data:'],
},
}),
express.urlencoded({ extended: true }),
express.json(),
morgan('combined'),
];
if (process.env.NODE_ENV === 'production') {
app.use(enforce.HTTPS({ trustProtoHeader: true }));
}
app.disable('x-powered-by');
app.use(middleware);
if (process.env.NODE_ENV === 'production') {
app.use(/^(?!\/m*).*$/, limiterMiddleware);
}
const redisMiddleware = async (req, res, next) => {
const redisClient = createClient({
password: process.env.REDIS_PASSWORD,
socket: {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT
},
database: process.env.REDIS_DB,
});
redisClient.connect();
// redisClient.on('connect', () => {
// console.log('Connesso a Redis!');
// });
// redisClient.on('end', () => {
// console.log('Disconnesso da Redis!');
// });
// redisClient.on('error', (error) => {
// console.error('Redis Server Error:', error);
// });
req.redis$ = redisClient;
next();
};
const server = http.createServer(app);
app.get('/images/:file', redisMiddleware, async (req, res) => {
const redis$ = await req.redis$;
const pathRedis = '/images/';
const cacheData = await redis$.get(commandOptions({ returnBuffers: true }), `${pathRedis}${req.params.file}`);
if (cacheData) {
const imageBuffer = Buffer.from(cacheData, 'binary');
res.writeHead(200, { 'Content-Type': 'image/png' });
res.write(imageBuffer);
await redis$.disconnect();
return res.end();
}
utils.parseImage(process.env, `${req.params.file}`, redis$, pathRedis, async (error, data) => {
if (error) {
res.status(500).send(error.message.split(', open \'./static/')[0]);
return;
}
res.writeHead(200, {'Content-Type': 'image/png'});
res.write(data);
res.end();
});
});
app.get('/assets/:file', redisMiddleware, async (req, res) => {
const redis$ = await req.redis$;
const pathRedis = '/assets/';
const cacheData = await redis$.get(commandOptions({ returnBuffers: true }), `${pathRedis}${req.params.file}`);
if (cacheData) {
const imageBuffer = Buffer.from(cacheData, 'binary');
res.writeHead(200, { 'Content-Type': 'image/png' });
res.write(imageBuffer);
await redis$.disconnect();
return res.end();
}
utils.parseImage(process.env, `${req.params.file}`, redis$, pathRedis, async (error, data) => {
if (error) {
res.status(500).send(error.message.split(', open \'./static/')[0]);
return;
}
res.writeHead(200, {'Content-Type': 'image/png'});
res.write(data);
res.end();
});
});
app.get('/svg/:file', redisMiddleware, async (req, res) => {
const redis$ = await req.redis$;
const pathRedis = '/svg/';
const cacheData = await redis$.get(commandOptions({ returnBuffers: true }), `${pathRedis}${req.params.file}`);
if (cacheData) {
const imageBuffer = Buffer.from(cacheData, 'binary');
res.writeHead(200, { 'Content-Type': 'image/svg+xml' });
res.write(imageBuffer);
await redis$.disconnect();
return res.end();
}
utils.parseImage(process.env, `${req.params.file}`, redis$, pathRedis, async (error, data) => {
if (error) {
res.status(500).send(error.message.split(', open \'./static/')[0]);
return;
}
res.writeHead(200, {'Content-Type': 'image/svg+xml'});
res.write(data);
res.end();
});
});
app.get('/', redisMiddleware, async (req, res) => {
const redis$ = await req.redis$;
const pathRedis = '/html/';
const cacheData = await redis$.get(`${pathRedis}coming_soon.html`);
if (cacheData) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(cacheData);
await redis$.disconnect();
return res.end();
}
fs.readFile(`${process.env.STATIC_DIR}${pathRedis}coming_soon.html`, async (error, data) => {
if (error) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.write('File non trovato');
return res.end();
}
data = utils.htmlReplaceEnv(process.env, data);
await redis$.set(`${pathRedis}coming_soon.html`, data, {
EX: utils.secondsInHours(12),
NX: true
});
await redis$.disconnect();
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
});
const staticDirAngular = `${process.env.STATIC_DIR}/angular/`;
app.use('/app', express.static(staticDirAngular, {
setHeaders: (res, filePath) => {
if (path.extname(filePath) === '.js') {
res.setHeader('Content-Type', 'application/javascript');
}
}
}));
app.get('/app/*', (req, res) => {
res.sendFile('index.html', { root: staticDirAngular });
});
app.get('/alive', (req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(`Hello, cashback-lefrecce mode:${process.env.NODE_ENV}\n`);
});
const hostname = process.env.HOST || 'www.cashback-lefrecce.it';
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log(`Server running at ${hostname}:${port}/`);
});