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");
}
});
CodePudding user response:
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
CodePudding user response:
Please confirm whether my interpretation or 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()
.