20 lines
539 B
JavaScript
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; |