I want to verify token and then verify some role using verifytoken middleware in veygiyRole middleware, I got an error "veryIfytoken is not found"
const jwt = require("jsonwebtoken");
const ErrorResponse = require("../utils/ErrorResponse");
exports.verifyToken = (req, res, next) => {
if (
!req.headers["authorization"]
) {
return next(new ErrorResponse("you are not authorize", 403));
}
const [Bearer, token] = req.headers["authorization"].split(" ");
if (token === null || Bearer !== "Bearer")
return next(new ErrorResponse("Invalid Token", 403));
jwt.verify(token, process.env.JWT_SECRET_KEY, (err, user) => {
if (err) return next(new ErrorResponse("Token is not valid", 403));
req.user = user;
console.log(user);
next();
});
};
exports.verifyUser = (req, res, next) => {
verifyToken(req, res, next, () => {
if (req.user.id === req.params.id || req.user.role === "admin") {
next();
} else {
return next(new ErrorResponse("you are not authorize", 403));
}
});
};
If you are not accessing verifyToken
and verifyUser
anywhere outside the current context you can modify your function as follows
const jwt = require("jsonwebtoken");
const ErrorResponse = require("../utils/ErrorResponse");
const verifyToken = (req, res, next) => {
if (
!req.headers["authorization"]
) {
return next(new ErrorResponse("you are not authorize", 403));
}
const [Bearer, token] = req.headers["authorization"].split(" ");
if (token === null || Bearer !== "Bearer")
return next(new ErrorResponse("Invalid Token", 403));
jwt.verify(token, process.env.JWT_SECRET_KEY, (err, user) => {
if (err) return next(new ErrorResponse("Token is not valid", 403));
req.user = user;
console.log(user);
next();
});
};
const verifyUser = (req, res, next) => {
verifyToken(req, res, next, () => {
if (req.user.id === req.params.id || req.user.role === "admin") {
next();
} else {
return next(new ErrorResponse("you are not authorize", 403));
}
});
};
and if you want to access these function outside of the current context you do so with
module.exports = {
verifyToken,
verifyUser
}
hope this helps:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.