CoolFace
Apppublic

sanket3280/code-execution

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
auth.js65 linesDownload Raw Back to middleware
1const jwt = require('jsonwebtoken');2const { config } = require('../config/env.config');3const User = require('../models/User');4 5/**6 * Authentication middleware7 * Verifies JWT token from request header/cookie and adds user to request object8 * Supports multi-server load balancing with shared JWT secret9 */10module.exports = async function(req, res, next) {11  // Get token from multiple sources (header, cookie)12  let token = req.header('x-auth-token');13  14  // Check Authorization Bearer header15  if (!token) {16    const authHeader = req.header('Authorization');17    if (authHeader && authHeader.startsWith('Bearer ')) {18      token = authHeader.substring(7);19    }20  }21  22  // Check cookie (for JWT-based auth)23  if (!token && req.cookies && req.cookies.token) {24    token = req.cookies.token;25  }26 27  // Check if no token28  if (!token) {29    return res.status(401).json({ msg: 'No token, authorization denied' });30  }31 32  try {33    // Verify token with shared JWT secret (works across all servers)34    const decoded = jwt.verify(token, config.jwt.secret);35    36    // Support both token structures: { id } and { userId }37    const userId = decoded.id || decoded.userId;38    39    if (!userId) {40      return res.status(401).json({ msg: 'Invalid token structure' });41    }42    43    // Fetch user from shared database44    try {45      const user = await User.findById(userId).select('-password');46      if (!user) {47        return res.status(401).json({ msg: 'User not found' });48      }49      req.user = user;50    } catch (err) {51      console.error('Error fetching user in auth middleware:', err);52      return res.status(500).json({ msg: 'Server error during authentication' });53    }54    55    next();56  } catch (err) {57    if (err.name === 'TokenExpiredError') {58      return res.status(401).json({ msg: 'Token expired' });59    }60    if (err.name === 'JsonWebTokenError') {61      return res.status(401).json({ msg: 'Invalid token' });62    }63    return res.status(401).json({ msg: 'Token verification failed' });64  }65};