1

First Time I implementing Session Authentication using Node JS and PostgreSQL. In this implementation I facing an issue in backend side i have a /login endpoint. In this endpoint user login successfully It will generated session_id and stored on the PostgreSQL Database. Next, I get that sessionID pass to the client-side for accessing user details using this /user. In this endpoint I tried to compare request.sessionID equal to client-side sessionID. But they two session id are not equal. it's showing Invalid Session ID Error. Each request it generating new Session ID. I think its's not an issue it's my mistake. I referred many documentation but I could n't understand. can you pls explain how to implement session id authentication using node js

Client-side Code

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("form").submit(function(e){
    e.preventDefault()
    console.log($('#email').val())
    console.log($('#password').val())
    var formData = {'email':$('#email').val(), 'password':$('#password').val()}
    $.ajax({
    url : "http://localhost:4000/login",
    type: "POST",
    data : formData,
    success: function(data, textStatus, jqXHR)
    {
        console.log('data', data)
        $.ajax({
            url: 'http://localhost:4000/user',
            type: 'GET',
            dataType: 'json',
            headers: {'session_id': 'nd0KLK9Jb4HXJspdF4ZY-8QDJnlfwaTb'},
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
               // CallBack(result);
               console.log('result', result)
            },
            error: function (error) {
             console.log('error', error)   
            }
        })
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        console.log('textStatus', textStatus)
    }
});
  });
});
</script>
</head>
<body>

<form action="">
  email: <input type="text" id='email' name="email" value="Mickey"><br>
  password: <input type="text" id='password' name="password" value="Mouse"><br>
  <input type="submit" value="Submit">
</form> 

</body>
</html>

If login successfully client-side pass the session_id to backend for authenticate user. So, session_id i pass request header section I mention in the client-side code

Backend-code

const express = require('express');
const cookieParser = require("cookie-parser");
const sessions = require('express-session');
var cors = require('cors')
var pg = require('pg')
  , pgSession = require('connect-pg-simple')(sessions);

const app = express();
const PORT = 4000;

const oneDay = 1000 * 60 * 60 * 24;

var pgPool = new pg.Pool({
    // Insert pool options here
    connectionString: `postgres://******:***@127.0.0.1:5432/local`,

});
app.use(cors())

//session middleware
app.use(sessions({
    store: new pgSession({
        pool : pgPool,                
        schemaName: "public",
        pruneSessionInterval: false,
        tableName: "session",
        errorLog: (...args) => console.error(...args)
      }),
    secret: "thisismysecrctekeyfhrgfgrfrty84fwir767",
    saveUninitialized:false,
    cookie: { maxAge: oneDay },
    resave: false
}));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(cookieParser());

app.post('/login',(req,res) => {
    if(req.body.email == 'testing.v@gmail.com' && req.body.password == 'Pass@123'){
        var session=req.session;
        session.email=req.body.email;
        console.log(req.session)
        res.send(req.session);
    }
    else{
        res.send('Invalid username or password');
    }
})

app.get('/testing',(req,res) => {
    res.send('hello world');
})

app.get('/user',(req,res) => {
    console.log('headers_session_id', req.headers['session_id'])
    if(Object.keys(req.headers).includes('session_id')){
        console.log('request session_id', req.sessionID)
        if(req.sessionID){
            let session_id = req.headers['session_id']
            if(req.sessionID == session_id){
                res.send(true)
            }
            else{
                res.send('Invalid session id');
            }
        }
        else{
            res.send('Session ID is expired');
        }
    }
    else{
        res.send('Session_id is Required');
    }
})
app.listen(PORT, () => console.log(`Server Running at port ${PORT}`));
hari prasanth
  • 716
  • 1
  • 15
  • 35

0 Answers0