Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda