All files / middleware auth.js

89.28% Statements 25/28
81.25% Branches 13/16
100% Functions 3/3
89.28% Lines 25/28

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 55 56 57 58 594x 4x     4x 26x 26x   26x 4x     22x     19x         19x       19x       19x 19x   3x 2x   1x 1x             4x 30x 3x 1x     2x 1x     1x       4x    
const jwt = require('jsonwebtoken');
const pool = require('../config/database');
 
// Verify JWT token
const authenticate = async (req, res, next) => {
  try {
    const token = req.headers.authorization?.split(' ')[1] || req.headers['x-access-token'];
 
    if (!token) {
      return res.status(401).json({ error: 'No token provided' });
    }
 
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // Get user from database
    const [users] = await pool.query(
      'SELECT id, email, role, name, status FROM users WHERE id = ?',
      [decoded.userId]
    );
 
    Iif (users.length === 0) {
      return res.status(401).json({ error: 'User not found' });
    }
 
    Iif (users[0].status !== 'active') {
      return res.status(403).json({ error: 'User account is not active' });
    }
 
    req.user = users[0];
    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({ error: 'Invalid token' });
    }
    Eif (error.name === 'TokenExpiredError') {
      return res.status(401).json({ error: 'Token expired' });
    }
    return res.status(500).json({ error: 'Authentication error' });
  }
};
 
// Check if user has required role
const authorize = (...roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({ error: 'Authentication required' });
    }
 
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ error: 'Insufficient permissions' });
    }
 
    next();
  };
};
 
module.exports = { authenticate, authorize };