fastify / session

Session plugin for fastify
Other
96 stars 44 forks source link

`Session#regenerate` does not call `SessionStore#destroy` #240

Open SpraxDev opened 3 months ago

SpraxDev commented 3 months ago

Prerequisites

Fastify version

4.26.2

Plugin version

10.7.0

Node.js version

20.11.1

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

5.15.150-1-MANJARO

Description

I am trying to regenerate a session in one of my routes to make sure whatever data is in there is reset and I would prefer to also get a new session id as I am essentially restarting the session.

But as far as I can see there is no way for me, without manually interacting with the SessionStore myself, to delete the old session id.

#regenerate only generates a new session for me and stores it.

Steps to Reproduce

Something like:

this.fastify.get('/regenerate', async (request, reply) => {
  await request.session.regenerate();
  request.session.set('userId', 123);
  await request.session.save();

  return reply.send();
});

For easier understanding on what is happening in the store:

    this.fastify.register(FastifySession, {
      secret: '...',
      store: {
        set: (sessionId, session, callback) => {
          console.log(`#set(${JSON.stringify(sessionId)}, ${JSON.stringify(session)}`);
          callback();
        },
        get: (sessionId, callback) => {
          console.log(`#get(${JSON.stringify(sessionId)})`);
          callback(null, null);
        },
        destroy: (sessionId, callback) => {
          console.log(`#destroy(${JSON.stringify(sessionId)})`);
          callback();
        }
      }
    });

Expected Behavior

I am essentially generating a completely new session with different ID and data/content.

I'd expect the session to be automatically deleted from the store as it is no longer used/needed.

As far as I can see, there is also no good workaround for this as calling await request.session.destroy(); before regenerating the session sets it to null causing TypeError: Cannot read properties of null (reading 'regenerate')

gabor-s commented 2 months ago

A quick and dirty workaround:

let session = request.session;
await session.destroy();
await session.regenerate();
session = null; // just to make sure you don't use it or session = request.session