mirror of
https://github.com/Alvin-Zilverstand/Challenge_15_Magazijn_App_Maken.git
synced 2026-03-06 11:06:34 +01:00
init
This commit is contained in:
29
middleware/auth.js
Normal file
29
middleware/auth.js
Normal 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 };
|
||||
Reference in New Issue
Block a user