Answer the question
In order to leave comments, you need to log in
How to protect routes from unlogged users and by roles if JWT is used?
On the server side, I have 2 middleware - protect (logged in?) and restrictTo (has the appropriate role?), which do not allow certain actions to be performed if the site visitor does not have the rights to do so
exports.protect = catchAsync(async (req, res, next) => {
let token;
if (
req.headers.authorization && req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
}
if (!token) {
return next(new AppError("Вы не вошли в систему!", 401));
}
const decodedToken = await promisify(jwt.verify)(
token,
process.env.JWT_SECRET
);
const currentUser = await User.findById(decodedToken.id);
if (!currentUser) {
return next(new AppError("Пользователя с таким токеном больше не существует"));
}
req.user = currentUser;
next();
});
exports.restrictTo = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return next(new AppError("Нет прав для выполнения этого действия", 403));
}
next();
};
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question