-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmiddleware.js
More file actions
35 lines (31 loc) · 1.26 KB
/
middleware.js
File metadata and controls
35 lines (31 loc) · 1.26 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
import dotenv from 'dotenv';
dotenv.config();
export function apiKeyAuth(req, res, next) {
const apiKey = req.headers['x-api-key'];
const expectedApiKey = process.env.X_API_KEY;
if (!apiKey || apiKey !== expectedApiKey) {
return res.status(401).json({ success: false, error: 'Invalid or missing x-api-key' });
}
next();
}
export function basicAuth(req, res, next) {
if (req.session.isAuthenticated) {
return next();
}
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Basic ')) {
res.setHeader('WWW-Authenticate', 'Basic realm="Facebook Bot Admin"');
return res.status(401).send('Authentication required');
}
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
const expectedUsername = process.env.ADMIN_USERNAME;
const expectedPassword = process.env.ADMIN_PASSWORD;
if (username === expectedUsername && password === expectedPassword) {
req.session.isAuthenticated = true;
return next();
}
res.setHeader('WWW-Authenticate', 'Basic realm="Facebook Bot Admin"');
return res.status(401).send('Invalid credentials');
}