Skip to content

Commit

Permalink
Merge pull request #68 from AnkanSaha/dev
Browse files Browse the repository at this point in the history
Added: Added IP Access Controller Middleware
  • Loading branch information
AnkanSaha authored Jan 23, 2024
2 parents ec74c2e + dd59233 commit f7535d4
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 2 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -325,5 +325,16 @@ app.use('/api', Middleware.AccessController(['ARRAY OF URLs'], FailedStatusCode,
- Note : You can pass the Error Message in the third parameter of the function, by default it is set to 'You are not allowed to access this URL', it will send a error message if the verification failed
- Note : You can pass the Reverse in the fourth parameter of the function, by default it is set to false, if you set it to true then it will reverse the verification, it will send a 403 status code if the verification success
# Control IP Address Access in NodeJS
```javascript
const {Middleware} = require('outers'); // import the package

app.use('/api', Middleware.IPAccessController(['ARRAY OF IP ADDRESSES'], FailedStatusCode, ErrorMessage, Reverse), MainFunction); // control the IP Address Access in NodeJS with the Middleware function
```
- Note : You can pass as many as you want IP Addresses in the first parameter of the function
- Note : You can pass the Failed Status Code in the second parameter of the function, by default it is set to 403, it will send a 403 status code if the verification failed
- Note : You can pass the Error Message in the third parameter of the function, by default it is set to 'You are not allowed to access this URL', it will send a error message if the verification failed
- Note : You can pass the Reverse in the fourth parameter of the function, by default it is set to false, if you set it to true then it will reverse the verification, it will send a 403 status code if the verification success
## License
MIT
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@AnkanSaha/outers",
"version": "5.9.2",
"version": "6.0.1",
"description": "outers - a all in one package for your day to day use",
"main": "./lib/outer.js",
"types": "./lib/outer.d.ts",
Expand Down
84 changes: 84 additions & 0 deletions source/Middlewares/IP Controller/Base.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { Request, Response, NextFunction } from "express"; // Import Express Module

// Import Interfaces
import { Serve, StatusCodes } from "../../outer"; // Import red from outers

// Main Function
/**
* Middleware function to restrict access based on IP address or URL.
*
* @param AllowedIP - An array of allowed IP addresses. must be in string format
* @param StatusCode - Optional. The status code to be sent in the response if access is denied. Defaults to 406 (Not Acceptable).
* @param ErrorMessage - Optional. The error message to be sent in the response if access is denied. Defaults to "You are not allowed to access this server from this IP/URL."
* @param Reverse - Optional. If true, the middleware will allow access only if the requester IP/URL is not in the allowed list. Defaults to false.
*
* @returns The middleware function.
*/
export default function (
AllowedIP: string[],
StatusCode?: number,
ErrorMessage?: string,
Reverse?: boolean
) {
return async (Request: Request, Response: Response, Next: NextFunction) => {
const ReverseParams = Reverse ?? false; // Set Reverse to false if it is undefined
const RequesterIPaddress = String(
Request.headers["x-forwarded-for"] ||
Request.connection.remoteAddress ||
Request.socket.remoteAddress ||
Request.socket.remoteAddress
); // Get Requester IP Address

let isAllowed = false; // Set isAllowed to false

try {
// Check if Request Hostname is available in Array or not
isAllowed = AllowedIP.some((IP: string) => IP.toLowerCase() === RequesterIPaddress.toLowerCase()); // Check if Requester IP is Allowed or not
if (ReverseParams === false) {
if (isAllowed === true) {
Next(); // Next Middleware
} else {
// Handle the case when no match is found
Serve.JSON({
response: Response,
status: false,
Title: "IP Not Allowed to Access",
statusCode: StatusCode ?? StatusCodes.NOT_ACCEPTABLE,
message:
ErrorMessage ??
"You are not allowed to access this server from this IP.",
data: undefined,
cookieData: undefined,
}); // Serve JSON
// You may choose to send an error response or redirect the user to an error page
}
} else {
if (isAllowed === false) {
Next(); // Next Middleware
} else {
Serve.JSON({
response: Response,
status: false,
Title: "URL Not Allowed to Access",
statusCode: StatusCode ?? StatusCodes.NOT_ACCEPTABLE,
message:
ErrorMessage ??
"You are not allowed to access this server from this URL.",
data: undefined,
cookieData: undefined,
}); // Serve JSON
}
}
} catch (error) {
Serve.JSON({
response: Response,
status: false,
statusCode: StatusCodes.EXPECTATION_FAILED,
Title: "Failed To Proceed",
data: error,
message:
"Unable to Proceed your Request further, there is some error in configuration in Server",
}); // Send Error Response
}
};
}
13 changes: 12 additions & 1 deletion source/Middlewares/URL Controller/Base.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function (

// Check if Request Hostname is available in Array or not
isAllowed = AllowedURLs.some((url: string) => url.toLowerCase() === Request.hostname.toLowerCase());

try {
if (ReverseParams === false) {
if (isAllowed === true) {
Next(); // Next Middleware
Expand Down Expand Up @@ -62,5 +62,16 @@ export default function (
}); // Serve JSON
}
}
}
catch (error){
Serve.JSON({
response: Response,
status: false,
statusCode: StatusCodes.EXPECTATION_FAILED,
Title: "Failed To Proceed",
data: error,
message: "Unable to Proceed your Request further, there is some error in configuration in Server"
}); // Send Error Response
}
};
}
2 changes: 2 additions & 0 deletions source/outer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {Mongo} from 'mongosuper'; // Mongo Super Module
// Import All Middlewares
import InjectIP from './Middlewares/Request IP Injector/Base.middleware'; // Import Inject IP Module
import URL_Controller from './Middlewares/URL Controller/Base.middleware'; // Import URL Controller Module
import IP_Controller from './Middlewares/IP Controller/Base.middleware'; // Import IP Controller Module

// Export All Feature from internal module
/* The code is exporting an object named `ConsoleColors` that contains various color functions from the
Expand Down Expand Up @@ -54,6 +55,7 @@ export const Serve = Object.freeze({
export const Middleware = Object.freeze({
RequestInjectIP: InjectIP, // Export IP Injector Module as Middleware
AccessController: URL_Controller, // Export URL Controller Module as Middleware
IPAccessController: IP_Controller // Export IP Controller Module as Middleware
}); // Export IP Injector Module as Middleware


Expand Down

0 comments on commit f7535d4

Please sign in to comment.