Aldabeth
Aldabeth

Reputation: 63

fastify session is throwing something that I dont understand

I have problem with fastify sessions. I am using typescript:

import fastify from "fastify"
import randomString = require("crypto-random-string")
import fastifyCookie = require("fastify-cookie")
import fastifySession = require("fastify-session")

const app = fastify()

const safeSecret = randomString({length:32, type: 'base64'})

app.register(fastifyCookie)
app.register(fastifySession, {secret: safeSecret, saveUninitialized: true, cookie: {secure:false, httpOnly: true, sameSite: false, maxAge: 60 *60 *60}})

app.addHook('preHandler', (request, _reply, next) => {
    request.session.sessionData = {userId: String, name: String, email: String, password: String, loggedOn: Date};
    next();
})


app.get('/', (req, reply) => {
    let oldName = req.session.sessionData.name
    req.session.sessionData.name = randomString({length: 32, type: 'base64'})
    reply.send("name:" + req.session.sessionData.name + " old name: " + oldName)
})

app.get('/showmename', (req, reply) => {
    reply.send("name:" + req.session.sessionData.name)
})

app.listen(3000)

The code works, but, when I go first to localhost/ it says my random name, but oldname is this code below. The showmename says exactly the same thing as oldname.

name:function String() { [native code] }

am I doing something wrong? Because when I go to localhost/showmename, the cookie-editor addon for firefox shows me the exact same session cookie with the same session id as localhost/.

Upvotes: 2

Views: 2718

Answers (1)

Manuel Spigolon
Manuel Spigolon

Reputation: 12900

The preHandler hook is run every request so you are just overwriting your sessionData every time:

app.addHook('preHandler', (request, _reply, next) => {
    request.session.sessionData = {userId: String, name: String, email: String, password: String, loggedOn: Date};
    next();
})

Because of this, name is the String constructor that it is stringified to your output.

You should check the session:

app.addHook('preHandler', (request, _reply, next) => {
  if (!request.session.sessionData) {
    request.session.sessionData = { userId: String, name: String, email: String, password: String, loggedOn: Date }
  }
  next()
})

then it will work.

Anyway, I would avoid setting a JSON property to the String() constructor.

Upvotes: 2

Related Questions