Move x-forwarded-for middleware

This commit is contained in:
calzoneman 2015-10-27 23:54:32 -07:00
parent 13d4a49976
commit c2726898e5
6 changed files with 53 additions and 40 deletions

View file

@ -0,0 +1,32 @@
import net from 'net';
export default function initialize(app, webConfig) {
function isTrustedProxy(ip) {
return webConfig.getTrustedProxies().indexOf(ip) >= 0;
}
function getForwardedIP(req) {
const xForwardedFor = req.header('x-forwarded-for');
if (!xForwardedFor) {
return req.ip;
}
const ipList = xForwardedFor.split(',');
for (let i = 0; i < ipList.length; i++) {
const ip = ipList[i].trim();
if (net.isIP(ip)) {
return ip;
}
}
return req.ip;
}
app.use((req, res, next) => {
if (isTrustedProxy(req.ip)) {
req.realIP = getForwardedIP(req);
}
next();
});
}