All files / Backend/Middleware permissions.js

7.69% Statements 2/26
0% Branches 0/23
0% Functions 0/7
9.52% Lines 2/21

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 481x                                                                                 1x            
const Event = require('../Models/Event');
 
async function requireHostOrCoHost(req, res, next) {
  const userId = req.user.id;
  const eventId = req.body.eventId || req.params.id;
  try {
    const event = await Event.findById(eventId);
    if (!event) {
      return res.status(404).json({ error: 'Event not found.' });
    }
    if (event.hostUserId.toString() === userId || event.coHosts.map(id => id.toString()).includes(userId)) {
      return next();
    }
    return res.status(403).json({ error: 'Only host or approved co-host can perform this action.' });
  } catch (error) {
    next(error);
  }
}
 
function requireVerifier(req, res, next) {
  if (req.user.roles.includes('verifier') || req.user.roles.includes('platformAdmin')) return next();
  return res.status(403).json({ error: 'Only verifier or platform admin can perform this action.' });
}
 
function requireAdmin(req, res, next) {
  if (req.user.roles.includes('platformAdmin')) return next();
  return res.status(403).json({ error: 'Only platform admin can perform this action.' });
}
 
function requireInstitution(req, res, next) {
  if (req.user.roles.includes('institution') || req.user.roles.includes('platformAdmin')) return next();
  return res.status(403).json({ error: 'Only institution or platform admin can perform this action.' });
}
 
function requireSelfOrRole(role) {
  return (req, res, next) => {
    if (req.user.id === req.params.id || req.user.roles.includes(role) || req.user.roles.includes('platformAdmin')) return next();
    return res.status(403).json({ error: 'Forbidden: insufficient role.' });
  };
}
 
module.exports = {
  requireHostOrCoHost,
  requireVerifier,
  requireAdmin,
  requireInstitution,
  requireSelfOrRole
};