19 lines
655 B
JavaScript
19 lines
655 B
JavaScript
import jwt from 'jsonwebtoken';
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET || 'sandbox-secret-key-change-in-production';
|
|
|
|
export function generateToken(userId) {
|
|
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: '7d' });
|
|
}
|
|
|
|
export function authenticateToken(req, res, next) {
|
|
const authHeader = req.headers['authorization'];
|
|
const token = authHeader && authHeader.split(' ')[1];
|
|
if (!token) return res.status(401).json({ error: 'Authentication required' });
|
|
jwt.verify(token, JWT_SECRET, (err, decoded) => {
|
|
if (err) return res.status(403).json({ error: 'Invalid or expired token' });
|
|
req.userId = decoded.userId;
|
|
next();
|
|
});
|
|
}
|