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

Make mandatory session properties immutable #54

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
16 changes: 15 additions & 1 deletion src/runtime/server/middleware/session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,20 @@ const getSession = async (event: H3Event): Promise<null | Session> => {
return session
}

const getImmutableSession = (session: Session) => {
const immutableSession = { ...session }
const properties = ['id', 'createdAt', 'ip']

properties.forEach((property) => {
Object.defineProperty(immutableSession, property, {
writable: false,
configurable: false
})
})

return immutableSession as Session
interpretor marked this conversation as resolved.
Show resolved Hide resolved
}

const updateSessionExpirationDate = (session: Session, event: H3Event) => {
const now = new Date()
safeSetCookie(event, SESSION_COOKIE_NAME, session.id, now)
Expand All @@ -142,7 +156,7 @@ const ensureSession = async (event: H3Event) => {
}

event.context.sessionId = session.id
event.context.session = session
event.context.session = getImmutableSession(session)
return session
}

Expand Down
12 changes: 9 additions & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,15 @@ export interface ModulePublicRuntimeConfig {
}

export declare interface Session {
id: string;
createdAt: Date;
ip?: string;
readonly id: string;
readonly createdAt: Date;
readonly ip?: string;
Copy link
Contributor

Choose a reason for hiding this comment

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

and, sorry to kind of push this in here, but as we're already working on the Session interface: Would you consider adapting the h3 event context as done here:
https://github.com/sidebase/nuxt-prisma/blob/b1ffd717cf1061215498fa8e9b90ce62cac8b494/src/runtime/server/middleware/prisma.ts#L7-L11

whuile you're add it? This way, typing for the end-user should improve when they access event.context.session

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added it, but somehow the types aren't available when packed and imported as module in a project. Any suggestions?


[key: string]: any;
}

declare module 'h3' {
interface H3EventContext {
session: Session
}
}