Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda