Move x-forwarded-for middleware
This commit is contained in:
parent
13d4a49976
commit
c2726898e5
6 changed files with 53 additions and 40 deletions
32
src/web/middleware/x-forwarded-for.js
Normal file
32
src/web/middleware/x-forwarded-for.js
Normal 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();
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue