Skip to content

Commit

Permalink
feat: add replaceUserSession() (#44)
Browse files Browse the repository at this point in the history
* feat: add replaceUserSession()

* chore: update

---------

Co-authored-by: Sébastien Chopin <[email protected]>
  • Loading branch information
maximilianmikus and atinux authored Feb 13, 2024
1 parent e761369 commit e74f238
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ The following helpers are auto-imported in your `server/` directory.
```ts
// Set a user session, note that this data is encrypted in the cookie but can be decrypted with an API call
// Only store the data that allow you to recognize an user, but do not store sensitive data
// Merges new data with existing data using defu()
await setUserSession(event, {
user: {
// ... user data
Expand All @@ -98,6 +99,9 @@ await setUserSession(event, {
// Any extra fields
})

// Replace a user session. Same behaviour as setUserSession, except it does not merge data with existing data
await replaceUserSession(event, data)

// Get the current user session
const session = await getUserSession(event)

Expand Down
1 change: 1 addition & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export default defineNuxtModule<ModuleOptions>({
'sessionHooks',
'getUserSession',
'setUserSession',
'replaceUserSession',
'clearUserSession',
'requireUserSession',
]
Expand Down
14 changes: 14 additions & 0 deletions src/runtime/server/utils/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,20 @@ export async function setUserSession (event: H3Event, data: UserSession) {
return session.data
}

/**
* Replace a user session
* @param event
* @param data User session data, please only store public information since it can be decoded with API calls
*/
export async function replaceUserSession (event: H3Event, data: UserSession) {
const session = await _useSession(event)

await session.clear()
await session.update(data)

return session.data
}

export async function clearUserSession (event: H3Event) {
const session = await _useSession(event)

Expand Down

0 comments on commit e74f238

Please sign in to comment.