Skip to content

Commit

Permalink
feat: add opts to requireUserSession for error message and status cod…
Browse files Browse the repository at this point in the history
…e customization

* feat: add opts to requireUserSession for error message and status code customization

* Update src/runtime/server/utils/session.ts

* Update session.ts

---------

Co-authored-by: Sébastien Chopin <[email protected]>
  • Loading branch information
dethdkn and atinux authored Apr 17, 2024
1 parent 5fac9a1 commit 015e847
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/runtime/server/utils/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,20 @@ export async function clearUserSession(event: H3Event) {
return true
}

export async function requireUserSession(event: H3Event): Promise<UserSessionRequired> {
/**
* Require a user session
* @param event
* @param opts Options to customize the error message and status code
* @param opts.statusCode The status code to use for the error (defaults to 401)
* @param opts.message The message to use for the error (defaults to Unauthorized)
*/
export async function requireUserSession(event: H3Event, opts: { statusCode?: number, message?: string } = {}): Promise<UserSessionRequired> {
const userSession = await getUserSession(event)

if (!userSession.user) {
throw createError({
statusCode: 401,
message: 'Unauthorized',
statusCode: opts.statusCode || 401,
message: opts.message || 'Unauthorized',
})
}

Expand Down

0 comments on commit 015e847

Please sign in to comment.