57 lines
1.8 KiB
JavaScript
57 lines
1.8 KiB
JavaScript
const jwt = require('jsonwebtoken');
|
|
const pool = require('../db');
|
|
const { jwtSecret } = require('../config/runtime');
|
|
const { hashSecret } = require('../utils/security');
|
|
|
|
const authenticateToken = async (req, res, next) => {
|
|
if (req.path.startsWith('/auth/')) return next();
|
|
|
|
const authHeader = req.headers['authorization'];
|
|
|
|
if (authHeader && authHeader.startsWith('Bearer fasto_sk_')) {
|
|
const apiKey = authHeader.split(' ')[1];
|
|
try {
|
|
const [keys] = await pool.query(
|
|
'SELECT * FROM api_keys WHERE secret_hash = ? OR secret_key = ?',
|
|
[hashSecret(apiKey), apiKey]
|
|
);
|
|
if (keys.length === 0) return res.status(401).json({ error: 'Chave de API inválida.' });
|
|
|
|
await pool.query('UPDATE api_keys SET last_used_at = CURRENT_TIMESTAMP WHERE id = ?', [keys[0].id]);
|
|
|
|
req.user = {
|
|
id: 'bot_integration',
|
|
tenant_id: keys[0].tenant_id,
|
|
role: 'admin',
|
|
is_api_key: true
|
|
};
|
|
return next();
|
|
} catch (error) {
|
|
console.error('API Key validation error:', error);
|
|
return res.status(500).json({ error: 'Erro ao validar chave de API.' });
|
|
}
|
|
}
|
|
|
|
const token = authHeader && authHeader.split(' ')[1];
|
|
|
|
if (!token) return res.status(401).json({ error: 'Token não fornecido.' });
|
|
|
|
try {
|
|
req.user = jwt.verify(token, jwtSecret);
|
|
next();
|
|
} catch (err) {
|
|
return res.status(401).json({ error: 'Token inválido ou expirado.' });
|
|
}
|
|
};
|
|
|
|
const requireRole = (roles) => (req, res, next) => {
|
|
if (!req.user || !req.user.role) return res.status(401).json({ error: 'Não autenticado.' });
|
|
if (!roles.includes(req.user.role)) return res.status(403).json({ error: 'Acesso negado. Você não tem permissão para realizar esta ação.' });
|
|
next();
|
|
};
|
|
|
|
module.exports = {
|
|
authenticateToken,
|
|
requireRole,
|
|
};
|