Created
May 20, 2024 20:35
-
-
Save helabenkhalfallah/01406c844e35c7cf2ae3fc4e4e9ed151 to your computer and use it in GitHub Desktop.
Proxy secure API Gateway
This file contains hidden or 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 http from 'http'; | |
import url from 'url'; | |
// Validation function to perform security checks | |
const validateRequest = (req) => { | |
const apiKey = req.headers['x-api-key']; | |
if (!apiKey || apiKey !== 'your-secure-api-key') { | |
console.log('Invalid API Key'); | |
return false; | |
} | |
return true; | |
}; | |
// Define the services and their handlers | |
const services = { | |
service1: function (req, res) { | |
if (!res.finished) { | |
res.statusCode = 200; | |
res.end('Service 1 Response'); | |
} | |
}, | |
service2: function (req, res) { | |
if (!res.finished) { | |
res.statusCode = 200; | |
res.end('Service 2 Response'); | |
} | |
}, | |
fallback: function (req, res) { | |
if (!res.finished) { | |
res.statusCode = res.statusCode || 404; | |
res.end(res.statusCode === 403 ? 'Forbidden' : 'Not Found'); | |
} | |
}, | |
}; | |
// Proxy handler to intercept and manage requests | |
const handler = { | |
apply: function (target, thisArg, argumentsList) { | |
const [req, res] = argumentsList; | |
// Extract method and path from request | |
const { pathname } = url.parse(req.url, true); | |
// Log request details | |
console.log(`Received request: ${req.method} ${pathname}`); | |
// Perform security checks | |
/* if (!validateRequest(req)) { | |
res.statusCode = 403; | |
if (!res.finished) res.end('Forbidden'); | |
return Reflect.apply(target.fallback, target, argumentsList); | |
}*/ | |
// Routing logic (simple example) | |
if (pathname === '/api/service1') { | |
return Reflect.apply(target.service1, target, argumentsList); | |
} else if (pathname === '/api/service2') { | |
return Reflect.apply(target.service2, target, argumentsList); | |
} else { | |
res.statusCode = 404; | |
if (!res.finished) res.end('Not Found'); | |
return Reflect.apply(target.fallback, target, argumentsList); | |
} | |
}, | |
}; | |
// Create a proxy for the services | |
const proxy = new Proxy(function () {}, handler); | |
// Attach the services to the proxy's target | |
Object.assign(proxy, services); | |
// Create the HTTP server | |
const server = http.createServer((req, res) => { | |
proxy(req, res); // Invoke the proxy directly with the request and response objects | |
}); | |
server.listen(3000, () => { | |
console.log('API Gateway listening on port 3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment