Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add replaceUserSession() #44

Merged
merged 2 commits into from
Feb 13, 2024
Merged
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: 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
Loading