voxpelli / node-connect-pg-simple

A simple, minimal PostgreSQL session store for Express
https://www.npmjs.com/package/connect-pg-simple
MIT License
234 stars 74 forks source link

session_id is ignored and a new one is generated instead #306

Open Leni-Vienne opened 8 months ago

Leni-Vienne commented 8 months ago

Hello, I'm facing an issue when inside a route where the req.session.id will always be a new one, thus retaining no information from the user cookie. EDIT : test yourself with Docker : https://github.com/Leni-Vienne/nodePgConnect_issue Here is some code of the backend :

const sessionStore = new pgSession({
    pool: pool,
    tableName: 'sessions'
})

app.use(expressSession({
    store: sessionStore,
    secret: process.env.CLE_COOKIE,
    resave: false,
    saveUninitialized: false,
    unset: 'destroy',
    cookie: { 
        maxAge: 60 * 60 * 1000,
        secure: false, 
        httpOnly: true,
    },
}));
app.post('/api/connexion', async (req, res) => {
    try {
        if (req.session) {
            console.log("'old id' : ", req.session.id) // actually a brand new id, not in the database...
            if (req.session.id_user) { // undefined
                let user = await getUserFromId(req.session.id_user)
                return res.json(user)
            }
        }
        let mail = (process.env.VITE_ENVIRONMENT === "dev") ? process.env.CAS_MOCK : await casAuth(req.body.ticket)
        if (mail) {
            let user = await getUserFromMail(mail)
            if (user) {
                console.log(req.session.id) // the same new one
                req.session.regenerate(function (err) {
                    if (err) throw (err)
                    console.log("new id : ",req.session.id) // a new id, which is expected and savec correctly
                    req.session.id_user = user.id_user
                    req.session.groupe = user.groupe
                    req.session.save(function (err) {
                        if (err) throw err(err)
                        res.json(user)
                    })
                })
            }
        }
    } catch (error) {
        console.error(`api/connexion : ${error}`)
        res.json({ error: 'Une erreur est survenue lors de la connexion.' })
    }
});

req.session.save() does save successfully in the databse with 'id_user' and 'groupe' at the end of the sess JSON. I had a previous implementation with mySQL that worked flawlessly, it was almost a drop in replacement up to this point. Same with the default memory storage, it's able to retrieve informations about the user flawlessly.

I would love to get some help, thanks :)

joewagner commented 7 months ago

Hey @Leni-Vienne I came here from your express-session issue. I'm not familiar with this package, but out of curiousity can you show where the pgSession variable comes from? Or even better share a small app that can be used to reproduce this issue?

Leni-Vienne commented 7 months ago

Thank you for helping me. I've made a repo where I can reproduce the issue with postman (a new cookie is always generated), And when commenting the line store : store the issue indeed goes away and the server is able to retrieve the cookie. It does need a postgres server unfortunately. Should I dockerise it? https://github.com/Leni-Vienne/nodePgConnect_issue

voxpelli commented 7 months ago

Not sure if related, but you do know express does not support async route handlers?

app.post('/login', async (req, res) => {

It will disregard whatever error or result that the promise resolves to.

voxpelli commented 7 months ago

If you could make a PR that adds the reproduction as a failing test here then it would be easier to look into and fix: https://github.com/voxpelli/node-connect-pg-simple/blob/main/test/integration/express.spec.js

I see that right now all the tests are using these settings:

    app.use(session({
      store,
      secret,
      resave: false,
      rolling: true,
      saveUninitialized: true,
      cookie: { maxAge },
      ...sessionOptions,
    }));

But none of the tests are sending in modified sessionOptions.

In your repository I'm seeing some different options, such as eg:

    resave: true,
    saveUninitialized: false,

If adding a test with eg. those options will fail similarly then it's no question that the error is in this module and we have to look at fixing it.

Sorry for not having a better reply right now 🙏

Leni-Vienne commented 5 months ago

Hi, I'm not sure myself what are the conditions required to reproduce the issue so I will struggle to write a test for it. However my repo of the issue is now dockerised so you can test it yourself : https://github.com/Leni-Vienne/nodePgConnect_issue You will see it that once you enter a username and login, a session is added in the DB but reloading the page won't keep you connected. Then commenting line 30 store: store, of server.js will make the issue go away. I tested the options you mentioned but it didn't change much. Hopefully you can find what's wrong with the package or with my code 😄