Spaces:
Paused
Paused
File size: 2,241 Bytes
1d3aceb | 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 | import jwt from 'jsonwebtoken';
import User from '../models/User.js';
export const protect = async (req, res, next) => {
let token;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
try {
token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select('-loginCode');
if (!req.user) {
return res.status(401).json({ message: 'User not found' });
}
if (req.user.isBanned) {
return res.status(403).json({
message: `Your account has been suspended. Reason: ${req.user.banReason || 'Policy violation'}`
});
}
next();
} catch (error) {
console.error(error);
res.status(401).json({ message: 'Not authorized, token failed' });
}
}
if (!token) {
res.status(401).json({ message: 'Not authorized, no token' });
}
};
export const protectUrlParams = async (req, res, next) => {
let token;
if (req.query.access_token) {
try {
token = req.query.access_token;
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select('-loginCode');
if (!req.user) {
return res.status(401).json({ message: 'User not found' });
}
if (req.user.isBanned) {
return res.status(403).json({
message: 'Account suspended'
});
}
next();
} catch (error) {
console.error(error);
res.status(401).json({ message: 'Not authorized, token failed' });
}
}
if (!token) {
res.status(401).json({ message: 'Not authorized, no token' });
}
};
// Middleware to ensure user is an admin
export const adminOnly = async (req, res, next) => {
if (req.user && req.user.isAdmin) {
next();
} else {
res.status(403).json({ message: 'Admin access required' });
}
};
|