Skip to content

Commit

Permalink
Merge branch 'master' into feat-autorefresh-option
Browse files Browse the repository at this point in the history
  • Loading branch information
Eomm authored Nov 19, 2023
2 parents 0ae8b06 + a36a4e2 commit 40ef1c4
Show file tree
Hide file tree
Showing 12 changed files with 76 additions and 19 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Set default behavior to automatically convert line endings
* text=auto eol=lf
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,20 @@ fastify.decryptSession(sessionId, request, { maxAge: 86400 }, () => {
```

### Typescript support:
This plugin supports typescript, and you can extend fastify module to add your custom session type.
This plugin supports typescript, and you can extend fastify module to add your custom session type.

```ts
// Use module imports rather than commonjs' require for correct declaration merging in TypeScript.

// Wrong ❌:
// const fastifySession = require('@fastify/session');
// const fastifyCookie = require('@fastify/cookie');

// Correct ✔️:
import { fastifySession } from '@fastify/session';
import { fastifyCookie } from '@fastify/cookie';

// Extend fastify.session with your custom type.
declare module "fastify" {
interface Session {
user_id: string
Expand Down
2 changes: 1 addition & 1 deletion benchmark/bench.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const redisStoreFactory = require('connect-redis')
const Fastify = require('fastify')
const Redis = require('ioredis')
const fileStoreFactory = require('session-file-store')
const { isMainThread } = require('worker_threads')
const { isMainThread } = require('node:worker_threads')

const fastifySession = require('..')
const fastifyCookie = require('@fastify/cookie')
Expand Down
3 changes: 1 addition & 2 deletions examples/redis.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ const Fastify = require('fastify')
const fastifySession = require('..')
const fastifyCookie = require('@fastify/cookie')
const Redis = require('ioredis')
const redisStoreFactory = require('connect-redis')
const RedisStore = require('connect-redis').default

const fastify = Fastify()

const RedisStore = redisStoreFactory(fastifySession)
const store = new RedisStore({
client: new Redis({
enableAutoPipelining: true
Expand Down
11 changes: 4 additions & 7 deletions lib/fastifySession.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ function fastifySession (fastify, options, next) {
return function handleSession (request, reply, done) {
request.session = {}

const url = request.raw.url.split('?')[0]
const url = request.raw.url.split('?', 1)[0]
if (verifyPath(url, cookieOpts.path || '/') === false) {
done()
return
Expand Down Expand Up @@ -236,12 +236,9 @@ function fastifySession (fastify, options, next) {
}

function shouldSaveSession (request, cookieId, saveUninitializedSession, rollingSessions, refresh) {
if (cookieId !== request.session.encryptedSessionId) {
return saveUninitializedSession || request.session.isModified()
} else {
const shouldRefresh = refresh ? request.session.cookie.expires.getTime() < (Date.now() + refresh) : false
return rollingSessions || shouldRefresh || (Boolean(request.session.cookie.expires) && request.session.isModified())
}
return cookieId !== request.session.encryptedSessionId
? saveUninitializedSession || request.session.isModified()
: rollingSessions || shouldRefresh || (Boolean(request.session.cookie.expires) && request.session.isModified())
}

function option (options, key, def) {
Expand Down
2 changes: 1 addition & 1 deletion lib/idGenerator.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict'

const randomBytes = require('crypto').randomBytes
const randomBytes = require('node:crypto').randomBytes

const cacheSize = 24 << 7
let pos = 0
Expand Down
2 changes: 1 addition & 1 deletion lib/session.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict'

const crypto = require('crypto')
const crypto = require('node:crypto')

const Cookie = require('./cookie')
const { configure: configureStringifier } = require('safe-stable-stringify')
Expand Down
4 changes: 2 additions & 2 deletions lib/store.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict'

const EventEmitter = require('events').EventEmitter
const util = require('util')
const EventEmitter = require('node:events').EventEmitter
const util = require('node:util')

function Store (storeMap = new Map()) {
this.store = storeMap
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
{
"name": "@fastify/session",
"version": "10.4.0",
"version": "10.5.0",
"description": "a session plugin for fastify",
"main": "lib/fastifySession.js",
"type": "commonjs",
"scripts": {
"test": "npm run test:unit && npm run test:typescript",
"test:unit": "tap",
Expand Down Expand Up @@ -39,7 +40,7 @@
"session-file-store": "^1.5.0",
"standard": "^17.0.0",
"tap": "^16.3.0",
"tsd": "^0.28.0"
"tsd": "^0.29.0"
},
"types": "types/types.d.ts",
"files": [
Expand Down
2 changes: 1 addition & 1 deletion test/fastifySession.checkOptions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const test = require('tap').test
const Fastify = require('fastify')
const fastifyCookie = require('@fastify/cookie')
const fastifySession = require('..')
const crypto = require('crypto')
const crypto = require('node:crypto')

test('fastifySession.checkOptions: register should fail if no secret is specified', async t => {
t.plan(1)
Expand Down
2 changes: 1 addition & 1 deletion test/memorystore.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const test = require('tap').test
const { MemoryStore } = require('../lib/store')
const { EventEmitter } = require('stream')
const { EventEmitter } = require('node:stream')

test('MemoryStore.constructor: created MemoryStore should be an EventEmitter', (t) => {
t.plan(2)
Expand Down
47 changes: 47 additions & 0 deletions test/session.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1095,3 +1095,50 @@ test('will not update expires property of the session using Session#touch() if m
t.equal(response2.statusCode, 200)
t.same(response2.json(), { expires: null })
})

test('should save session if existing, modified, rolling false, and cookie.expires null', async (t) => {
t.plan(8)

const fastify = Fastify()
fastify.register(fastifyCookie)
fastify.register(fastifySession, {
...DEFAULT_OPTIONS,
cookie: { secure: false },
rolling: false
})
fastify.get('/', (request, reply) => {
request.session.set('foo', 'bar')
t.equal(request.session.cookie.expires, null)
reply.send(200)
})
fastify.get('/second', (request, reply) => {
t.equal(request.session.get('foo'), 'bar')
request.session.set('foo', 'baz')
t.equal(request.session.cookie.expires, null)
reply.send(200)
})
fastify.get('/third', (request, reply) => {
t.equal(request.session.get('foo'), 'baz')
t.equal(request.session.cookie.expires, null)
reply.send(200)
})
await fastify.listen({ port: 0 })
t.teardown(() => { fastify.close() })

const response1 = await fastify.inject({
url: '/'
})
t.equal(response1.statusCode, 200)

const response2 = await fastify.inject({
url: '/second',
headers: { Cookie: response1.headers['set-cookie'] }
})
t.equal(response2.statusCode, 200)

const response3 = await fastify.inject({
url: '/third',
headers: { Cookie: response1.headers['set-cookie'] }
})
t.equal(response3.statusCode, 200)
})

0 comments on commit 40ef1c4

Please sign in to comment.