Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
Authenticating a user when clicking a link

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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!!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!