Skip to content

Commit

Permalink
fix: UserSession user type augmentation (#54)
Browse files Browse the repository at this point in the history
* feat: create User interface for module augmentation

* fix: user is no longer possibly undefined when using `requireUserSession`

* chore: update docs

---------

Co-authored-by: Sébastien Chopin <[email protected]>
  • Loading branch information
Gerbuuun and atinux authored Feb 16, 2024
1 parent 58268d7 commit 1b99533
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 17 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,15 @@ You can define the type for your user session by creating a type declaration fil

```ts
declare module '#auth-utils' {
interface User {
// Add your own fields
}

interface UserSession {
// define the type here
// Add your own fields
}
}

export {}
```

Expand Down
25 changes: 13 additions & 12 deletions playground/auth.d.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
declare module '#auth-utils' {
interface User {
spotify?: any
github?: any
google?: any
twitch?: any
auth0?: any
microsoft?: any;
discord?: any
battledotnet?: any
keycloak?: any
linkedin?: any
}

interface UserSession {
user: {
spotify?: any
github?: any
google?: any
twitch?: any
auth0?: any
microsoft?: any;
discord?: any
battledotnet?: any
keycloak?: any
linkedin?: any
}
extended?: any
loggedInAt: number
}
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/server/utils/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useSession, createError } from 'h3'
import { defu } from 'defu'
import { createHooks } from 'hookable'
import { useRuntimeConfig } from '#imports'
import type { UserSession } from '#auth-utils'
import type { User, UserSession } from '#auth-utils'

export interface SessionHooks {
/**
Expand Down Expand Up @@ -69,7 +69,7 @@ export async function requireUserSession(event: H3Event) {
})
}

return userSession
return userSession as UserSession & { user: User }
}

let sessionConfig: SessionConfig
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export type { UserSession } from './session'
export type { UserSession, User } from './session'
export type { OAuthConfig } from './oauth-config'
5 changes: 4 additions & 1 deletion src/runtime/types/session.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
export interface User {
}

export interface UserSession {
user?: {}
user?: User
}

0 comments on commit 1b99533

Please sign in to comment.