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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | 6x 6x 6x 6x 6x 6x 6x 12x 6x 12x 6x 6x | const jwt = require('jsonwebtoken'); const User = require('../models/User'); const logger = require('../utils/logger'); const { RateLimiterMemory } = require('rate-limiter-flexible'); // Rate limiter for authentication attempts const rateLimiter = new RateLimiterMemory({ points: 5, // 5 attempts duration: 60 * 15, // Per 15 minutes }); /** * JWT Authentication Middleware * - Validates JWT tokens from headers or cookies * - Checks user status and activity * - Implements rate limiting */ const authenticateJWT = async (req, res, next) => { try { // Apply rate limiting try { await rateLimiter.consume(req.ip); } catch (limiterRes) { logger.warn(`Rate limit exceeded for IP: ${req.ip}`); return res.status(429).json({ success: false, message: 'Too many authentication attempts. Please try again later.' }); } // Get token from header or cookie const token = req.cookies?.jwt || req.headers.authorization?.replace('Bearer ', '') || req.query?.token; if (!token) { logger.warn('Authentication attempt without token', { ip: req.ip }); return res.status(401).json({ success: false, message: 'Authentication token required' }); } // Verify token const decoded = jwt.verify(token, process.env.JWT_SECRET); // Check if user exists and is active const user = await User.findById(decoded.id).select('+is_active'); if (!user || !user.is_active) { logger.warn(`Authentication attempt for inactive/missing user: ${decoded.id}`); return res.status(403).json({ success: false, message: 'User account not available or inactive' }); } // Attach user to request req.user = { id: user.id, username: user.username, email: user.email, role: user.role, is_active: user.is_active }; logger.info(`User authenticated: ${user.id}`, { userId: user.id, ip: req.ip }); next(); } catch (error) { // Handle different error types if (error instanceof jwt.TokenExpiredError) { logger.warn('Expired token attempt', { ip: req.ip }); return res.status(401).json({ success: false, message: 'Token expired. Please log in again.' }); } if (error instanceof jwt.JsonWebTokenError) { logger.warn('Invalid token attempt', { ip: req.ip }); return res.status(401).json({ success: false, message: 'Invalid authentication token' }); } logger.error(`Authentication error: ${error.message}`, { stack: error.stack, ip: req.ip }); res.status(500).json({ success: false, message: 'Authentication failed' }); } }; /** * Role-Based Access Control Middleware * - Checks if user has required role * - Supports multiple roles (array) or single role (string) */ const requireRole = (roles) => { if (!Array.isArray(roles)) { roles = [roles]; } return (req, res, next) => { if (!req.user) { logger.warn('Role check without authentication', { ip: req.ip }); return res.status(401).json({ success: false, message: 'Authentication required' }); } if (!roles.includes(req.user.role)) { logger.warn(`Unauthorized role attempt: ${req.user.id} tried accessing ${roles} route`, { userId: req.user.id, attemptedRoute: req.path, requiredRoles: roles }); return res.status(403).json({ success: false, message: 'Insufficient permissions for this action' }); } next(); }; }; /** * Ownership Check Middleware * - Verifies if user owns the resource they're trying to access */ const checkOwnership = (model, idParam = 'id') => { return async (req, res, next) => { try { const resource = await model.findById(req.params[idParam]); if (!resource) { return res.status(404).json({ success: false, message: 'Resource not found' }); } if (resource.user.toString() !== req.user.id && req.user.role !== 'admin') { logger.warn(`Unauthorized ownership attempt: ${req.user.id} tried accessing ${model.modelName} ${resource._id}`, { userId: req.user.id, resourceId: resource._id }); return res.status(403).json({ success: false, message: 'You do not have permission to access this resource' }); } req.resource = resource; next(); } catch (error) { logger.error(`Ownership check error: ${error.message}`, { stack: error.stack, userId: req.user?.id }); res.status(500).json({ success: false, message: 'Failed to verify resource ownership' }); } }; }; module.exports = { authenticateJWT, requireRole, checkOwnership, rateLimiter }; |