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

207
Visualizações
I want to redirect to dashboard if user is already logged in when he try to access login route in express js

I want to redirect to dashboard if user is already logged in when he try to access login route in express js

Middleware

const isAuthenticate = async (req, res, next) => {
  const token = req.cookies.jwt;
if (token) {
    jwt.verify(token, "thisisjwtsecret", async (err, token_decode) => {
      if (!err) {
        const u_id = token_decode._id;
        const userData = await User.findOne({ _id: u_id });
        req.user = userData;
        req.isAuth = true;
        next();
      } else {
        res.redirect("/user/login");
      }
    });
  } else {
    res.redirect("/user/login");
    }
};

Route.js

// Auth Controller
const AuthController = require("../../controllers/auth/AuthController");
const { isAuthenticate } = require("../../middlewares/isAutheticated");

router.get("/user/login", isAuthenticate, AuthController.login);
router.post("/user/login", AuthController.checkLogin);
router.get("/user/register", isAuthenticate, AuthController.createUser);
router.post("/user/register", isAuthenticate, AuthController.storeUser);
module.exports = router;

LOgin function

// Showing Login Page to User
const login = (req, res) => {
  return res.render("auth/login");
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can break out the functionality from your existing isAuthenticate() function so it just returns a result and then use that to do something like this:

const { promisify } = require('util');
const verify = promisify(jwt.verify);

// resolves if jwt cookie verifies and user found
// rejects if jwt cookie is missing or doesn't verify or user not found
async function isLoggedIn(req) {
    const token = req.cookies.jwt;
    if (!token) throw new Error("no jwt cookie");
    const token_decode = await verify(token, "thisisjwtsecret");
    let user = await User.findOne({ _id: token_decode._id });
    if (!user) throw new Error("user not found");
    return;
}

// Showing Login Page to User
// Or redirect to /dashboard if already logged in
const login = async (req, res) => {
    try {
        await isLoggedIn(req);
        // already logged in, redirect to dashboard
        // you MUST make sure that /dashboard does not redirect to /user/login itself
        // when isLoggedIn resolves to avoid circular redirects
        res.redirect("/dashboard");
    } catch (e) {
        // not logged in, render the login page
        res.render("auth/login");
    }
};

The isLoggedIn(req) function resolves if the token validates and the user is found in the database. Otherwise, it rejects. You can then use that in other routes to decide whether you want to redirect or not.

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