All files / Backend/Middleware Auth.js

42.85% Statements 9/21
11.76% Branches 2/17
42.85% Functions 3/7
44.44% Lines 8/18

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 511x   1x             2x 2x 2x                         25x                         7x               1x          
require('dotenv').config();
 
const jwt = require('jsonwebtoken');
 
/**
 * Middleware to authenticate JWT token from Authorization header.
 * Attaches user info to req.user if valid.
 */
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  Eif (!token) return res.status(401).json({ error: 'No token provided.' });
  jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) return res.status(403).json({ error: 'Invalid or expired token.' });
    req.user = user;
    next();
  });
}
 
/**
 * Middleware to require a specific user role.
 * Usage: requireRole('platformAdmin')
 */
function requireRole(role) {
  return (req, res, next) => {
    if (!req.user || !req.user.roles || !req.user.roles.includes(role)) {
      return res.status(403).json({ error: 'Forbidden: insufficient role.' });
    }
    next();
  };
}
 
/**
 * Middleware to allow if user is self or has one of the specified roles.
 * Usage: requireSelfOrRole(['platformAdmin', 'host'])
 */
function requireSelfOrRole(roles = []) {
  return (req, res, next) => {
    if (req.user && (req.user.id === req.params.id || roles.some(role => req.user.roles.includes(role)))) {
      return next();
    }
    return res.status(403).json({ error: 'Forbidden: not allowed.' });
  };
}
 
module.exports = {
  authenticateToken,
  requireRole,
  requireSelfOrRole
};