Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Add saveUninitialized option #41

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,9 @@ Here's what the full _default_ module configuration looks like:
// Sessions aren't pinned to the user's IP address
ipPinning: false,
// Expiration of the sessions are not reset to the original expiryInSeconds on every request
rolling: false
rolling: false,
// Uninitialized, resp. unmodified sessions are saved to the store, so session cookies are set at the first response
saveUninitialized: true
},
api: {
// The API is enabled
Expand Down
7 changes: 3 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"argon2": "^0.30.2",
"dayjs": "^1.11.6",
"defu": "^6.1.0",
"fast-deep-equal": "^3.1.3",
"h3": "^1.0.1",
"unstorage": "^1.0.1"
},
Expand Down
3 changes: 2 additions & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ const defaults: FilledModuleOptions = {
},
domain: false,
ipPinning: false as boolean|SessionIpPinningOptions,
rolling: false
rolling: false,
saveUninitialized: true
},
api: {
isEnabled: true,
Expand Down
28 changes: 25 additions & 3 deletions src/runtime/server/middleware/session/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { deleteCookie, eventHandler, H3Event, parseCookies, setCookie } from 'h3'
import { nanoid } from 'nanoid'
import dayjs from 'dayjs'
import { SameSiteOptions, Session, SessionOptions } from '../../../../types'
import equal from 'fast-deep-equal'
import { SameSiteOptions, Session, SessionOptions, SessionContent } from '../../../../types'
import { dropStorageSession, getStorageSession, setStorageSession } from './storage'
import { processSessionIp, getHashedIpAddress } from './ipPinning'
import { SessionExpired } from './exceptions'
import { resEndProxy } from './resEndProxy'
import { useRuntimeConfig } from '#imports'

const SESSION_COOKIE_NAME = 'sessionId'
Expand Down Expand Up @@ -65,7 +67,7 @@ export const deleteSession = async (event: H3Event) => {
deleteCookie(event, SESSION_COOKIE_NAME)
}

const newSession = async (event: H3Event) => {
const newSession = async (event: H3Event, sessionContent?: SessionContent) => {
const runtimeConfig = useRuntimeConfig()
const sessionOptions = runtimeConfig.session.session as SessionOptions
const now = new Date()
Expand All @@ -80,11 +82,23 @@ const newSession = async (event: H3Event) => {
createdAt: now,
ip: sessionOptions.ipPinning ? await getHashedIpAddress(event) : undefined
}
if (sessionContent) {
Object.assign(session, sessionContent)
}
await setStorageSession(sessionId, session)

return session
}

const newSessionIfModified = (event: H3Event, sessionContent: SessionContent) => {
const source = { ...sessionContent }
resEndProxy(event.res, async () => {
if (!equal(sessionContent, source)) {
await newSession(event, sessionContent)
}
})
}

const getSession = async (event: H3Event): Promise<null | Session> => {
// 1. Does the sessionId cookie exist on the request?
const existingSessionId = getCurrentSessionId(event)
Expand Down Expand Up @@ -136,7 +150,15 @@ const ensureSession = async (event: H3Event) => {

let session = await getSession(event)
if (!session) {
session = await newSession(event)
if (sessionOptions.saveUninitialized) {
session = await newSession(event)
} else {
// 1. Create an empty session object in the event context
event.context.session = {}
Copy link
Contributor Author

@interpretor interpretor Dec 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't a good idea, it is just a workaround so the rest of the module behaves as before. Initializing an empty session and only saving it when saveUninitialized is true is implemented in #48. I would suggest to merge only #48 instead of this and #47.

// 2. Create a new session if the object has been modified by any event handler
newSessionIfModified(event, event.context.session)
return null
}
} else if (sessionOptions.rolling) {
session = updateSessionExpirationDate(session, event)
}
Expand Down
14 changes: 14 additions & 0 deletions src/runtime/server/middleware/session/resEndProxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { ServerResponse } from 'node:http'

type MiddleWare = () => Promise<void>

// Proxy res.end() to get a callback at the end of all event handlers
export const resEndProxy = (res: ServerResponse, middleWare: MiddleWare) => {
const _end = res.end

// @ts-ignore Replacing res.end() will lead to type checking error
res.end = async (chunk: any, encoding: BufferEncoding) => {
await middleWare()
return _end.call(res, chunk, encoding) as ServerResponse
}
}
14 changes: 13 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,15 @@ export interface SessionOptions {
* @example true
* @type boolean
*/
rolling: boolean
rolling: boolean,
/**
* Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified.
* Choosing false is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie.
* @default true
* @example false
* @type boolean
*/
saveUninitialized: boolean
}

export interface ApiOptions {
Expand Down Expand Up @@ -189,3 +197,7 @@ export declare interface Session {

[key: string]: any;
}

export declare interface SessionContent {
[key: string]: any;
}