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

241
Visualizações
How to use different session for different routes in express?

I am trying to make the login/logout functionality of two category, admin & employee.
And When used app.use(session()) session will be available to every routes. And that is great. But when I want to logout lets say admin using req.session.destroy(). It logs out but the entire session is gone including admin as well as the employee. And that's not i want. I want to destroy only admin related session for admin logout and employee related session for employee logout. So, how can I do this?
And I am new to authentication and authorization. Do let me know what's the best practices using sessions, or is it better to JWT or anything which will help me be better at it.
For this related question.
my app.js


// session
app.use(
  session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false,
    store,
    cookie: {
      maxAge: 20000,
      secure: false,
    },
  })
);

app.use("/api/admin", adminRoutes);
app.use("/api/employee", employeeRoutes);

app.get("/api", (req, res) => {
  res.send("Api is running");
});

and when the api/admin/login route is called this controller is called,

const adminLoginController = asyncHandler(async (req, res) => {
  console.log("I ran");
  const { pass } = req.body;

  if (someDBCheckHere) {
    req.session.adminAuthenticated = true;
    req.session.admin = { pass: pass };
    res.send("success");
  } else {
    res.status(401).send({ message: "Login Failed" });
    console.log("failure");
  }
});

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I'm not really sure why you would destroy the session. Did you read it somewhere that tell you to do so?
So from the behavior, you can see the session is intended to live, not to be destroy :D

To "logout" a user, you just set set the cookie to an expire date

over 4 years ago · Santiago Trujillo Relatório

0

Please confirm whether my interpretation of your requirement is correct:

Your users can log on in two roles, with different passwords per role. And they might even be logged on in both roles simultaneously (either by giving two passwords, or because the admin role includes the employee role).

You could achieve this by having only one session, with attributes req.session.employeeAuthenticated and req.session.adminAuthenticated. After validating a password, you would set one (or both) of these attributes, and users could also "log out from the admin role", after which you would simply set req.session.adminAuthenticated = false but keep the session.

The first of the adminRoutes must then validate that the current user indeed has the admin role:

function(req, res, next) {
  if (req.session.adminAuthenticated) next();
  else res.status(403).end("Forbidden for non-admins");
}

(and likewise in employeeRoutes).

Only when the user logs out completely would you call req.session.destroy().

over 4 years ago · Santiago Trujillo 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