tenderizer / src /utils /authMiddleware.js
ismizo's picture
Upload 28 files
1d3aceb verified
Raw History Blame Contribute Delete
2.24 kB
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' });
}
};