15 lines
460 B
JavaScript
15 lines
460 B
JavaScript
import jwt from 'jsonwebtoken';
|
|
|
|
export function requireAuth(req, res, next) {
|
|
try {
|
|
const h = req.headers.authorization || '';
|
|
const token = h.startsWith('Bearer ') ? h.slice(7) : '';
|
|
if (!token) return res.status(401).json({ error: 'missing_token' });
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'supersecret');
|
|
req.user = decoded;
|
|
next();
|
|
} catch (e) {
|
|
res.status(401).json({ error: 'invalid_token' });
|
|
}
|
|
}
|