refactor: implement API key authentication for secure access to endpoints
This commit is contained in:
@@ -11,6 +11,29 @@ const PORT = 3001;
|
|||||||
app.use(cors());
|
app.use(cors());
|
||||||
app.use(express.json({ limit: '5mb' }));
|
app.use(express.json({ limit: '5mb' }));
|
||||||
|
|
||||||
|
// ========== API Key Authentication ==========
|
||||||
|
const API_KEY = process.env.API_KEY || '';
|
||||||
|
|
||||||
|
function extractApiKey(req) {
|
||||||
|
const auth = req.headers.authorization || '';
|
||||||
|
if (auth.startsWith('Bearer ')) return auth.slice(7);
|
||||||
|
return req.headers['x-api-key'] || req.query.key || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireAuth(req, res, next) {
|
||||||
|
if (!API_KEY) return next(); // Auth disabled when no key configured
|
||||||
|
if (extractApiKey(req) === API_KEY) return next();
|
||||||
|
return res.status(401).json({ error: 'Unauthorized — invalid or missing API key' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Protect mutating endpoints when an API key is set
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
return requireAuth(req, res, next);
|
||||||
|
});
|
||||||
|
|
||||||
// Rewrite requests that arrive without /api prefix (from reverse proxy stripping it)
|
// Rewrite requests that arrive without /api prefix (from reverse proxy stripping it)
|
||||||
app.use((req, res, next) => {
|
app.use((req, res, next) => {
|
||||||
if (!req.path.startsWith('/api') && req.path !== '/' && req.path !== '/health') {
|
if (!req.path.startsWith('/api') && req.path !== '/' && req.path !== '/health') {
|
||||||
|
|||||||
Reference in New Issue
Block a user