Files
graphs/backend/auth.js
Cauê Faleiros 8c2590c56a
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m32s
refactor backend and persist stock campaign queue
2026-05-27 15:00:23 -03:00

41 lines
1.1 KiB
JavaScript

const jwt = require('jsonwebtoken');
const { ADMIN_EMAIL, ADMIN_PASSWORD, API_KEY, JWT_SECRET } = require('./config');
const verifyToken = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) return res.status(403).json({ error: 'No token provided' });
const token = authHeader.split(' ')[1];
if (!token) return res.status(403).json({ error: 'Malformed token' });
jwt.verify(token, JWT_SECRET, (err, decoded) => {
if (err) return res.status(401).json({ error: 'Unauthorized' });
req.user = decoded;
next();
});
};
const authenticateAPIKey = (req, res, next) => {
const apiKey = req.headers['x-api-key'];
if (apiKey === API_KEY) {
next();
return;
}
res.status(401).json({ error: 'Unauthorized: Invalid API Key' });
};
const login = (email, password) => {
if (email !== ADMIN_EMAIL || password !== ADMIN_PASSWORD) {
return null;
}
return jwt.sign({ email }, JWT_SECRET, { expiresIn: '24h' });
};
module.exports = {
verifyToken,
authenticateAPIKey,
login
};