ip-allowed
v1.1.1
Published
A middleware for access permissions based on IP/host addresses. Customers who are not on the whitelist have their requests blocked.
Downloads
12
Maintainers
Readme
IP Allowed
A middleware for access permissions based on IP/host addresses. Customers who are not on the whitelist have their requests blocked. The response of the request is resumed with status code 401 and an error message that may be pernanalized.
Features
- Create a list of permissions with hostnames and IP addresses and control who can access the resources of your API;
- Support IPv4, IPv6, CIDR format & IPv4 mapped IPv6 addresses;
- Custom log function;
- Custom message function;
- Set request code status or use default;
- Set URL to redirect.
Installation
npm i ip-allowed --save
Usage
To use middleware is very simple, just import and then define your list of permissions and available options, such as log and message.
const ipAllowed = require('ip-allowed');
// Create middleware.
// Only requests the "localhost/127.0.0.1"
// and ip from the domain "client.com" will be accepted.
const middleware = ipAllowed(['127.0.0.1', 'client.com']);
// Injecting middleware into instance express
const express = require('express');
const app = express();
app.use(middleware);
Options
const options = {
log: (clientIp, accessDenied) => {
console.log(`${clientIp} access ${accessDenied ? 'denied!' : 'allowed!'}`)
},
message: (err, clientIp) => {
return {error: `Client with IP address ${clientIp} is not allowed!`}
},
statusCode: 401,
redirectTo: ''
};
const middleware = ipAllowed(['127.0.0.1', 'client.com'], options);
app.use(middleware);
The options are not mandatory and have default values.
- log: Allows you to manipulate the log on each request. To disable log assign its value equal to
false
.- Default value:
(clientIp, accessDenied) => { console.log(`Access ${accessDenied ? 'denied' : 'allowed'} for ip address ${clientIp}`) }
- message: Allows you to handle the error message when the client IP is not on the whitelist.
- Default value:
(err, clientIp) => { return { code: '401', message: 'Unauthorized', description: `Access denied for IP address ${clientIp}` } }
- statusCode: The status code sent when the request was denied.
- Default value:
401
- Default value:
- redirectTo: URL to redirect when request is denied. Be sure to set the statusCode to
301
or302
as it is the HTTP status codes that apply in this situation. Otherwise, the default401
will be used.- Default value:
''
- Default value: