Spaces:
Sleeping
Sleeping
Download backend/src/middleware/auth.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 5.05 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/middleware/auth.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/middleware/auth.js
-
curl -L -o auth.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/middleware/auth.js
5.05 kB
| 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 | |
| }; |