This commit is contained in:
Alvin
2025-10-21 20:54:03 +02:00
parent 97c80d7800
commit a5c73ad907
35 changed files with 4899 additions and 0 deletions

29
middleware/auth.js Normal file
View File

@@ -0,0 +1,29 @@
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const auth = async (req, res, next) => {
try {
const token = req.header('Authorization').replace('Bearer ', '');
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findOne({ _id: decoded.userId });
if (!user) {
throw new Error();
}
req.token = token;
req.user = user;
next();
} catch (error) {
res.status(401).send({ error: 'Please authenticate' });
}
};
const adminOnly = async (req, res, next) => {
if (req.user.role !== 'admin') {
return res.status(403).send({ error: 'Access denied' });
}
next();
};
module.exports = { auth, adminOnly };