File size: 2,260 Bytes
99c40f3 a5f7d1a 59c12a7 e6acbde 59c12a7 e6acbde 59c12a7 e6acbde 59c12a7 e151afc 21cab6c e6acbde 21cab6c e151afc 21cab6c b8e601f e151afc 6f9e59b 21cab6c e151afc 21cab6c 06932c2 e151afc 6f9e59b e151afc 21cab6c e151afc 5b96bf9 49284c1 5b96bf9 e151afc 21cab6c 6222fc9 59c12a7 c1aabc1 59c12a7 |
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 |
import { Database } from '../database/database.js';
import { rateLimit } from 'express-rate-limit';
const authenticateApiKey = async (req, res, next) => {
const apiKey = req.headers['x-api-key'];
const dbClient = new Database("AkenoXJs");
const db = dbClient.collection("api_keys");
if (!apiKey) {
return res.status(401).json({ error: 'API Key required' });
}
try {
const keyDoc = await db.findOne({key: apiKey});
if (!keyDoc) {
return res.status(403).json({ error: 'Invalid API Key' });
}
next();
} catch (err) {
res.status(500).json({ error: 'Server error' });
}
};
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
keyGenerator: (req) => req.headers['x-api-key'],
message: 'Too many requests from this API Key'
});
class CheckMilWare {
constructor() {
this.dbClient = new Database("AkenoXJs");
}
async handle(req, res, next) {
try {
delete req.headers["link"];
const xForwardedFor = req.headers['x-forwarded-for'];
const xRealIP = req.headers['x-real-ip'];
const cfConnectingIP = req.headers['cf-connecting-ip'];
let realIP = req.ip;
if (xForwardedFor) {
realIP = xForwardedFor.split(',')[0].trim();
} else if (xRealIP) {
realIP = xRealIP;
} else if (cfConnectingIP) {
realIP = cfConnectingIP;
}
req.realIP = realIP;
const isBlocked = await this.dbClient.CheckIsBlocked(realIP);
if (isBlocked && isBlocked.blocked) {
return res.status(403).send("Access denied: IP is blocked");
}
if (req.path === '/.env') {
console.log("Check path /env");
await this.dbClient.AddIpisBlocked(realIP);
return res.status(403).send("Access denied: IP is blocked..");
}
console.log(`Real IP address is: ${realIP}
path method: ${req.path}
method: ${req.method}
header used: ${xForwardedFor ? "x-forwarded-for" : xRealIP ? "x-real-ip" : cfConnectingIP ? "cf-connecting-ip" : "req.ip"}
`);
next();
} catch (error) {
console.error("Error in middleware: " + error);
res.status(500).send("Something bad happened");
}
}
}
export {
CheckMilWare,
authenticateApiKey,
apiLimiter
}; |