This repository was archived by the owner on Jan 29, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathauth.js
More file actions
49 lines (41 loc) · 1.19 KB
/
auth.js
File metadata and controls
49 lines (41 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Authentication Middleware
*
* Provides simple API key authentication for admin endpoints.
* Uses X-API-Key header or API_KEY environment variable.
*/
import { logger } from '../../utils/logger.js';
const API_KEY = process.env.API_KEY || '';
/**
* Authentication middleware
* @param {Object} options - Authentication options
* @param {boolean} options.required - Whether authentication is required
*/
export function authenticate(options = { required: true }) {
return (req, res, next) => {
if (!options.required) {
return next();
}
const providedKey = req.headers['x-api-key'];
if (!API_KEY) {
logger.warn('API_KEY not configured, authentication disabled');
return next();
}
if (!providedKey || providedKey !== API_KEY) {
logger.warn({ ip: req.ip }, 'Unauthorized access attempt');
return res.status(401).json({
success: false,
error: { message: 'Unauthorized. Provide valid X-API-Key header.' }
});
}
next();
};
}
/**
* Async handler wrapper for route handlers
*/
export function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}