I am authenticating the user by using the cookie stored in the request by using the authenticate middleware which I have included below.
const Authenticate = async (req, res, next) => {
try {
const token = req.cookies.jwtoken;
const verifyToken = jwt.verify(token, JWT_SECRET);
const mainUser = await User.findOne({
_id: verifyToken._id,
"tokens.token": token,
});
if (!mainUser) {
throw new Error("User not Found");
}
req.token = token;
req.mainUser = mainUser;
req.email = mainUser.email;
req.userID = mainUser._id;
// console.log(req.mainUser._id);
// console.log(req.email);
next();
} catch (error) {
res.send({ status: "error", error: error.message });
console.log(error);
}
};
I want to authenticate the user when he clicks any link in the navbar on the homepage. Right now it just takes the user to any page even if they are not signedin/ authenticated yet. The links are just anchor tags in navbar.
All my pages are static html pages being served by nodejs. This is what I have tried to authenticate the user but it does not seem to work
app.get("/mycourses.html", auth, (req, res) => {
console.log(req.email);
});
Expected functionality is that, user is asked to login/error is given when any link on homepage is clicked while the user is not logged in.
just use the auth middleware that you have in every single app.get('/**') in your code and inside your if block use res.redirect('/login')
if (!mainUser) {
//this line will redirect user to login page for example
res.redirect('/login');
throw new Error("User not Found");
}
have fun!!