'Session not getting destroyed in nodejs

I am using the code as stated below to logout from my site created using nodejs and mysql but its simply redirecting to the login page without destroying the session. Even after logging out I can visit other pages of the site. I want my session to be destroyed on logout and it should ask to login to visit the pages of the website.

router.get('/logout', function(req, res) {
    req.session.destroy((err) => {
        if (err) {
            console.log(err)
            return next(err)
        }

        return res.redirect("/")
    })
  
  });


Solution 1:[1]

How to use Redis Enterprise for session management

Consider a text chat application that uses MySQL as the relational database, Node.js as the backend server technology and Redis Enterprise for session management. The frontend consists of two pages: a home page, where users register, and a chat page, where users write and send messages.

For simplicity, we will only show the server code. We will explain how to implement the session state lifecycle in Node.js. We will also omit the HTML view pages and the rest of the application.

First, the application loads the dependencies, including the session, the Redis objects and the MySQL client:

var express = require("express");
var session = require('express-session');
var mysql = require("mysql");
var redis = require("redis");
var redisStore = require('connect-redis')(session);
var redisClient = redis.createClient();
// aquí se cargan más dependencias ...

These statements create objects to manage web routing, session, database, caching and session Node.js libraries. It then configures Redis as a session store:

app.use(session({
secret: 'mysecret',
// crear nuevo almacén redis.
store: new redisStore({ host: 'localhost', port: 6379, client: redisClient }),
saveUninitialized: false,
resave: false
}));

Next, you configure Node.js express routes for the home and chat page, along with support for AJAX requests coming from the client, including login, logout, and commenting.

When a user requests the home page, the server redirects the user to the chat.html page or displays the login.html page, depending on whether the user is logged in or not. The following snippet shows you the controller code for the web /get path:

app.get('/',function(req,res){
// crear nuevo objeto de sesión.
if(req.session.key) {
// el usuario ya ha iniciado sesión
res.redirect('/chat');
} else {
// no se ha encontrado ninguna sesión, vaya a la página de inicio
res.render("login.html");
}
});

When the user submits the login form data (with email and password), the JavaScript AJAX client sends the form data to the server. In this example, it triggers the executeLoginDbCommand function (not shown here), which executes an SQL query against the MySQL database and returns an object containing the user's previously saved session data.

If the login is successful, the user's data from MySQL is saved in the web session backed by the Redis session store, and the client's JavaScript code redirects the user to the chat page:

app.post('/login',function(req, res){
// SQL Query comparará los datos de inicio de sesión y la contraseña
// desde el cuerpo de la solicitud HTTP a los datos de la tabla de usuarios
executeLoginDbCommand(req.body.Email, req.body.Password, function(dbResult){
//
if(!dbResult) {
res.json({"success" : false,"message" : "Login failed ! Please register"});
} else {
req.session.key = dbResult;
res.json({"success" : true,"message" : "Login success."});
}
});
});

The application's chat page allows users to read and send messages to other people connected to the application. Since users only see their own message interactions with other people, the data returned by the server for chat page requests changes from user to user. And the most important thing, access to this page is restricted exclusively to registered users. Checking the session key reveals whether the user is logged in or not:

app.get('/chat',function(req,res){
if(req.session.key) {
//el usuario ya ha iniciado sesión,
//pasemos a la página del chat con el correo electrónico del usuario
res.render("chat.html",
{
email : req.session.key["UserEmail"],
name : req.session.key["UserName"]
});
} else {
// no se ha encontrado ninguna sesión, vaya a la página de inicio
res.redirect("/");
}
});

When the user submits a new comment from the chat page, the JavaScript AJAX client sends the form data to the server. If the user is logged in, the comments are inserted into the MySQL UserComments table. To do this, use the executeSendCommmentDbCommand function (not shown here).

app.post("/sendComment",function(req,res){
// This SQL command will insert a new comment in
// users table
app.post("/sendComment",function(req,res){
// Este comando SQL introducirá un nuevo comentario en
// tabla de usuarios
if(req.session.key) {
executeSendCommmentDbCommand(req.body.Email, req.body.Recipient, req.body.Comment, function(dbResult){
if(!dbResult) {
res.json({"success" : true, "message" : "Comment has been sent successfully."});
} else {
res.json({"success" : false, "message" : "SendComment failed!"});
}
});
} else {
res.json({"success" : false, "message" : "Please login first."});
}
});

When the user logs out, the session object is destroyed and the user is redirected to the login page. But before that, the executePersistSessionDbCommand function (not shown here) saves the user session in memory in the MySQL database:

app.get('/logout',function(req,res){
// el usuario ya ha iniciado sesión, borremos la sesión
// y redireccionar a la página de inicio de sesión.
if(req.session.key) {
executePersistSessionDbCommand(req.session, function(dbResult){
if(!dbResult) {
req.session.destroy(function(){
res.redirect("/");
} else {
res.json({"success" : false, "message" : "Session persistence failed!"});
}
});
});
} else {
res.redirect("/");
}
});

These snippets superficially show a real application using Redis as a session store. This serves to show how Redis can manage the lifecycle of in-memory session state in combination with permanent database storage such as MySQL.

URL : https://redis.com/es/soluciones/casos-de-uso/gestion-de-sesiones/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Javier G.Raya