Skip to content

Instantly share code, notes, and snippets.

@evanshortiss
Last active October 25, 2017 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanshortiss/08e723e9e44935d0c7bbb1a32902cc57 to your computer and use it in GitHub Desktop.
Save evanshortiss/08e723e9e44935d0c7bbb1a32902cc57 to your computer and use it in GitHub Desktop.
An express middleware function that ensures requests are coming from the IP addresses defined in IP_ALLOWED_ADDRESSES
'use strict'
// Ensure you run "npm install env-var@3 --save"
const env = require('env-var')
// Used to bypass check when running locally
const isLocal = env.get('FH_USE_LOCAL_DB').asBool()
// Valid mbaas IP(s) that can be in the "x-forwarded-for" header
// This must be set or app will not start (required() call) and must be comma separated
// e.g '1.2.3.4,5.6.7.8' or '1.2.3.4' for just a single address
const mbaasAddresses = env.get('IP_ALLOWED_ADDRESSES').required().asArray()
// Replace with your logger of choice so you can enable/disable logs based on environment
function log (str) {
console.log(`IP Filter: ${str}`)
}
/**
* Generates an express middleware function that blocks requests based on IP
* Does not operate during local development
*
* @return {Function}
*/
module.exports = function (req, res, next) {
// MBaaS requests can be identified since their "x-forwaded-for" will contain
// only a single internally accessible IP Address, e.g 'x-forwarded-for': '1.2.3.4'
if (isLocal) {
console.log('running locally, bypassing IP checks')
return next()
}
const forwardedFor = req.headers['x-forwarded-for']
if (mbaasAddresses.indexOf(forwardedFor) !== -1) {
log(`received request from valid IP ${mbaasAddresses}`)
next();
} else {
log(`received request from "${forwardedFor}", but only accepting requests from "${mbaasAddresses}"`)
res.status(403).end('access denied')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment