Create midware.js
Browse files- midware.js +44 -0
midware.js
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
var Database = require('./database.js');
|
2 |
+
|
3 |
+
const CheckMilWare = async (app) => {
|
4 |
+
return async (req, res, next) => {
|
5 |
+
try {
|
6 |
+
const dbClient = new Database("AkenoXJs", "FastJsAPI");
|
7 |
+
|
8 |
+
const xForwardedFor = req.headers['x-forwarded-for'];
|
9 |
+
const xRealIP = req.headers['x-real-ip'];
|
10 |
+
const cfConnectingIP = req.headers['cf-connecting-ip'];
|
11 |
+
let realIP = req.ip;
|
12 |
+
|
13 |
+
if (xForwardedFor) {
|
14 |
+
realIP = xForwardedFor.split(',')[0].trim();
|
15 |
+
} else if (xRealIP) {
|
16 |
+
realIP = xRealIP;
|
17 |
+
} else if (cfConnectingIP) {
|
18 |
+
realIP = cfConnectingIP;
|
19 |
+
}
|
20 |
+
|
21 |
+
req.realIP = realIP;
|
22 |
+
|
23 |
+
const isBlocked = await dbClient.CheckIsBlocked(realIP);
|
24 |
+
if (isBlocked && isBlocked.blocked === true) {
|
25 |
+
return res.status(403).send("Access denied: IP is blocked");
|
26 |
+
}
|
27 |
+
|
28 |
+
if (req.path === '/env') {
|
29 |
+
console.log("Check path /env");
|
30 |
+
await dbClient.AddIpisBlocked(realIP);
|
31 |
+
return res.status(403).send("Access denied: IP is blocked..");
|
32 |
+
}
|
33 |
+
|
34 |
+
await dbClient.IPAddressAndUpdate(realIP);
|
35 |
+
|
36 |
+
console.log(`Real IP address is: ${realIP}, header: ${xForwardedFor ? "x-forwarded-for" : xRealIP ? "x-real-ip" : cfConnectingIP ? "cf-connecting-ip" : "req.ip"}`);
|
37 |
+
|
38 |
+
next();
|
39 |
+
} catch (error) {
|
40 |
+
console.error("Error in middleware: " + error);
|
41 |
+
res.status(500).send("Something bad happened");
|
42 |
+
}
|
43 |
+
};
|
44 |
+
};
|