Last active
April 28, 2024 12:17
-
-
Save afraz-khan/8666b111d55ffaa8a7d33df12b9e1d94 to your computer and use it in GitHub Desktop.
Whitelist request paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Middleware, ExpressMiddlewareInterface } from 'routing-controllers'; | |
import express from 'express'; | |
/** | |
* Regular expression pattern for whitelisting request paths. | |
* Each pattern represents an allowed HTTP method and path. | |
*/ | |
const whiteListedPathsPattern = new RegExp( | |
[ | |
`^GET /api/user$`, | |
`^POST /api/app//products/search$`, | |
`^POST /api/app/uninstall$`, | |
`^POST /api/app/disconnect$`, | |
`^GET /api/app/complaince/[a-z_]*$`, | |
`^POST /api/notification/brand$`, | |
].join('|') | |
); | |
/** | |
* Express middleware to skip authentication for listed paths. | |
*/ | |
@Middleware({ type: 'before' }) | |
export class SkipUserAuthMiddleware implements ExpressMiddlewareInterface { | |
/** | |
* Checks if the request path matches any whitelisted path and sets a flag to skip user auth. | |
* | |
* @param request - Express request object | |
* @param _response - Express response object | |
* @param next - Next middleware function | |
*/ | |
use(request: express.Request, _response: any, next: (err?: any) => any): void { | |
// Construct the URL string from the HTTP method and path | |
const url = `${request.method} ${request.originalUrl.split('?')[0]}`; | |
// Check if the URL matches any whitelisted path | |
if (whiteListedPathsPattern.test(url)) { | |
(request as any).skipAuth = true; // Set a flag to skip user authentication | |
} | |
next(); // Continue to the next middleware | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment