ryu-js / midware.js
randydev's picture
Update midware.js
21cab6c verified
raw
history blame
1.89 kB
var Database = require('./database.js');
class CheckMilWare {
constructor() {
this.dbClient = new Database("AkenoXJs", "FastJsAPI");
}
async handle(req, res, next) {
try {
// Extract IP addresses from headers
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; // Default IP
// Determine the real IP address based on available headers
if (xForwardedFor) {
realIP = xForwardedFor.split(',')[0].trim();
} else if (xRealIP) {
realIP = xRealIP;
} else if (cfConnectingIP) {
realIP = cfConnectingIP;
}
// Attach the real IP to the request object
req.realIP = realIP;
// Log the extracted real IP for debugging
console.log(`Extracted Real IP: ${realIP}`);
// Check if the IP is blocked in the database
const isBlocked = await this.dbClient.CheckIsBlocked(realIP);
console.log(`CheckIsBlocked result for ${realIP}:`, isBlocked);
if (isBlocked && isBlocked.blocked === true) {
return res.status(403).send("Access denied: IP is blocked");
}
// Special check for "/env" path
if (req.path === '/env') {
console.log("Check path /env");
await this.dbClient.AddIpisBlocked(realIP);
return res.status(403).send("Access denied: IP is blocked..");
}
await this.dbClient.IPAddressAndUpdate(realIP);
console.log(`Real IP address is: ${realIP}, 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");
}
}
}
module.exports = CheckMilWare;