Team Ai
Apppublic

sanket3280/code-execution

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
challengeParticipant.js76 linesDownload Raw Back to middleware
1const Challenge = require('../models/Challenge');2 3/**4 * Middleware to verify that the authenticated user is a participant in the challenge5 * or is the creator of the challenge.6 * 7 * This prevents unauthorized access to challenge problems and related resources.8 * 9 * @param {Object} req - Express request object (must have req.user from auth middleware)10 * @param {Object} res - Express response object11 * @param {Function} next - Express next middleware function12 */13const verifyParticipant = async (req, res, next) => {14  try {15    // Extract challengeId from params or body16    const challengeId = req.params.challengeId || req.body.challengeId;17    18    if (!challengeId) {19      return res.status(400).json({ 20        error: 'Challenge ID is required' 21      });22    }23 24    const userId = req.user.id;25 26    // Fetch challenge27    const challenge = await Challenge.findById(challengeId).select('participants createdBy');28    29    if (!challenge) {30      return res.status(404).json({ 31        error: 'Challenge not found' 32      });33    }34 35    // Check if user is the creator36    const isCreator = challenge.createdBy && challenge.createdBy.toString() === userId;37 38    // Check if user is a participant39    const isParticipant = challenge.participants.some(40      participant => participant.user && participant.user.toString() === userId41    );42 43    // Allow access if user is creator or participant44    if (isCreator || isParticipant) {45      // Attach challenge to request for potential use in route handler46      req.challenge = challenge;47      return next();48    }49 50    // User is neither creator nor participant - deny access51    console.warn(`🚫 Unauthorized challenge problem access attempt: User ${userId} tried to access challenge ${challengeId}`);52    53    return res.status(403).json({ 54      error: 'You must join this challenge to access its problems',55      requiresJoin: true,56      challengeId: challengeId57    });58 59  } catch (error) {60    console.error('Error in verifyParticipant middleware:', error);61    62    // Handle invalid ObjectId63    if (error.kind === 'ObjectId') {64      return res.status(400).json({ 65        error: 'Invalid challenge ID format' 66      });67    }68    69    return res.status(500).json({ 70      error: 'Server error while verifying participant status' 71    });72  }73};74 75module.exports = { verifyParticipant };76