BinCode/middleware/auth.js
2025-01-17 15:05:21 -05:00

20 lines
539 B
JavaScript

const jwt = require('jsonwebtoken');
const config = require('../config/jwt');
const auth = (req, res, next) => {
try {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'Authentication required' });
}
const decoded = jwt.verify(token, config.secret);
req.userId = decoded.userId;
next();
} catch (error) {
console.error('Auth error:', error);
res.status(401).json({ error: 'Invalid token' });
}
};
module.exports = auth;