Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 1x 1x 7x 7x 7x 2x 5x 5x 1x 1x 4x 4x 1x 1x | const jwt = require('jsonwebtoken'); // Middleware to authenticate JWT tokens const authenticateToken = (req, res, next) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN if (!token) { return res.status(401).json({ error: 'Access token required', message: 'Please provide a valid authentication token' }); } jwt.verify(token, process.env.JWT_SECRET, (err, user) => { if (err) { Iif (err.name === 'TokenExpiredError') { return res.status(401).json({ error: 'Token expired', message: 'Your authentication token has expired. Please login again.' }); } return res.status(403).json({ error: 'Invalid token', message: 'The provided authentication token is invalid' }); } req.user = user; next(); }); }; // Optional authentication middleware (doesn't fail if no token provided) const optionalAuth = (req, res, next) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (token) { jwt.verify(token, process.env.JWT_SECRET, (err, user) => { if (!err) { req.user = user; } next(); }); } else { next(); } }; module.exports = { authenticateToken, optionalAuth }; |