|
| 1 | +const jwt = require('jsonwebtoken'); |
| 2 | +const User = require('../models/User.model'); |
| 3 | + |
| 4 | +/** |
| 5 | + * Authentication middleware - verifies JWT token and attaches user to request |
| 6 | + */ |
| 7 | +const authenticate = async (req, res, next) => { |
| 8 | + try { |
| 9 | + // Get token from Authorization header |
| 10 | + const authHeader = req.headers.authorization; |
| 11 | + if (!authHeader || !authHeader.startsWith('Bearer ')) { |
| 12 | + const error = new Error('Authentication required'); |
| 13 | + error.statusCode = 401; |
| 14 | + error.isOperational = true; |
| 15 | + return next(error); |
| 16 | + } |
| 17 | + |
| 18 | + const token = authHeader.substring(7); // Remove 'Bearer ' prefix |
| 19 | + |
| 20 | + // Verify the token |
| 21 | + const decoded = jwt.verify(token, process.env.JWT_SECRET); |
| 22 | + |
| 23 | + // Check if token is an access token |
| 24 | + if (decoded.type !== 'access') { |
| 25 | + const error = new Error('Invalid token type'); |
| 26 | + error.statusCode = 401; |
| 27 | + error.isOperational = true; |
| 28 | + return next(error); |
| 29 | + } |
| 30 | + |
| 31 | + // Find the user |
| 32 | + const user = await User.findById(decoded.sub); |
| 33 | + if (!user) { |
| 34 | + const error = new Error('User not found'); |
| 35 | + error.statusCode = 401; |
| 36 | + error.isOperational = true; |
| 37 | + return next(error); |
| 38 | + } |
| 39 | + |
| 40 | + // Attach user to request object |
| 41 | + req.user = user; |
| 42 | + req.userId = user._id.toString(); |
| 43 | + |
| 44 | + next(); |
| 45 | + } catch (error) { |
| 46 | + if (error.name === 'JsonWebTokenError') { |
| 47 | + error.message = 'Invalid token'; |
| 48 | + error.statusCode = 401; |
| 49 | + error.isOperational = true; |
| 50 | + } else if (error.name === 'TokenExpiredError') { |
| 51 | + error.message = 'Token expired'; |
| 52 | + error.statusCode = 401; |
| 53 | + error.isOperational = true; |
| 54 | + } |
| 55 | + next(error); |
| 56 | + } |
| 57 | +}; |
| 58 | + |
| 59 | +module.exports = authenticate; |
0 commit comments