Spaces:
Sleeping
Sleeping
File size: 5,049 Bytes
0b355ec | 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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | const jwt = require('jsonwebtoken');
const User = require('../models/User');
const logger = require('../utils/logger');
const { redisUtils } = require('../utils/redis');
const auth = async (req, res, next) => {
try {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({
success: false,
error: 'Access denied. No token provided.'
});
}
// Check if token is blacklisted
const isBlacklisted = await redisUtils.exists(`blacklist:${token}`);
if (isBlacklisted) {
return res.status(401).json({
success: false,
error: 'Token has been invalidated'
});
}
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Check cache first
let user = await redisUtils.get(`user:${decoded.id}`);
if (!user) {
// Get user from database
user = await User.findById(decoded.id).select('-passwordHash');
if (!user) {
return res.status(401).json({
success: false,
error: 'Token is not valid'
});
}
// Cache user for 5 minutes
await redisUtils.setex(`user:${user._id}`, 300, user);
}
// Check if user is active
if (!user.isActive) {
return res.status(401).json({
success: false,
error: 'Account has been deactivated'
});
}
// Update last activity (only if method exists)
if (user && typeof user.updateActivity === 'function') {
try {
await user.updateActivity();
} catch (error) {
logger.warn('Failed to update user activity', { userId: user._id, error: error.message });
}
}
req.user = user;
req.token = token;
next();
} catch (error) {
if (error.name === 'JsonWebTokenError') {
logger.warn('Invalid JWT token attempt', {
tokenPrefix: req.header('Authorization')?.substring(0, 20) + '...', // Only log token prefix for security
ip: req.ip,
userAgent: req.get('User-Agent')
});
return res.status(401).json({
success: false,
error: 'Token is not valid'
});
}
if (error.name === 'TokenExpiredError') {
return res.status(401).json({
success: false,
error: 'Token has expired'
});
}
logger.error('Auth middleware error:', error);
res.status(500).json({
success: false,
error: 'Server error during authentication'
});
}
};
// Admin authorization middleware
const adminAuth = async (req, res, next) => {
try {
if (!req.user || req.user.role !== 'admin') {
logger.warn('Unauthorized admin access attempt', {
userId: req.user?.id,
role: req.user?.role,
ip: req.ip
});
return res.status(403).json({
success: false,
error: 'Access denied. Admin privileges required.'
});
}
next();
} catch (error) {
logger.error('Admin auth middleware error:', error);
res.status(500).json({
success: false,
error: 'Server error during authorization'
});
}
};
// Faculty authorization middleware
const facultyAuth = async (req, res, next) => {
try {
if (!req.user || !['faculty', 'admin'].includes(req.user.role)) {
return res.status(403).json({
success: false,
error: 'Access denied. Faculty privileges required.'
});
}
next();
} catch (error) {
logger.error('Faculty auth middleware error:', error);
res.status(500).json({
success: false,
error: 'Server error during authorization'
});
}
};
// Student authorization middleware
const studentAuth = async (req, res, next) => {
try {
if (!req.user || req.user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access denied. Student privileges required.'
});
}
next();
} catch (error) {
logger.error('Student auth middleware error:', error);
res.status(500).json({
success: false,
error: 'Server error during authorization'
});
}
};
// Rate limiting for sensitive operations
const sensitiveAuth = async (req, res, next) => {
try {
const key = `sensitive:${req.user.id}:${req.ip}`;
const attempts = await redisUtils.get(key) || 0;
if (attempts > 5) {
logger.warn('Sensitive operation rate limit exceeded', {
userId: req.user.id,
ip: req.ip,
attempts
});
return res.status(429).json({
success: false,
error: 'Too many sensitive operations. Please try again later.'
});
}
// Increment attempts
await redisUtils.setex(key, 3600, attempts + 1); // 1 hour window
next();
} catch (error) {
logger.error('Sensitive auth middleware error:', error);
next(); // Continue on error to not break the flow
}
};
module.exports = {
auth,
adminAuth,
facultyAuth,
studentAuth,
sensitiveAuth
}; |