Spaces:
Running
Running
const http = require('http'); | |
const originalCreateServer = http.createServer; | |
http.createServer = function() { | |
const server = originalCreateServer.apply(this, arguments); | |
const originalEmit = server.emit; | |
server.emit = function(type, req, res) { | |
if (type === 'request') { | |
const authHeader = req.headers.authorization; | |
const apiKey = process.env.API_KEY; | |
if (!apiKey) { | |
console.warn('API_KEY environment variable is not set'); | |
return originalEmit.apply(this, arguments); | |
} | |
if (!authHeader || authHeader !== 'Bearer ' + apiKey) { | |
res.writeHead(401, {'Content-Type': 'application/json'}); | |
res.end(JSON.stringify({error: 'Unauthorized: Invalid API key'})); | |
return true; | |
} | |
} | |
return originalEmit.apply(this, arguments); | |
}; | |
return server; | |
}; | |
module.exports = {}; |