Skip to content

Commit

Permalink
refactor: allow user to overwrite #auth-utils-session
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Nov 7, 2023
1 parent 6a89589 commit b3e92c8
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 55 deletions.
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,21 @@ await clearUserSession(event)
const session = await requireUserSession(event)
```

You can define the type for your user session by creating a type declaration file (for example, `auth.d.ts`) in your project:

```ts
declare module '#auth-utils-session' {
interface UserSession {
// define the type here
}
}
```

### OAuth Event Handlers

All helpers are exposed from the `oauth` global variable and can be used in your server routes or API routes.

The pattern is `oauth.<provider>EventHandler({ onSuccess?, config?, onError? })`, example: `oauth.githubEventHandler`.
The pattern is `oauth.<provider>EventHandler({ onSuccess, config?, onError? })`, example: `oauth.githubEventHandler`.

The helper returns an event handler that automatically redirects to the provider authorization page and then call `onSuccess` or `onError` depending on the result.

Expand Down
6 changes: 0 additions & 6 deletions playground/app/auth-utils-session.ts

This file was deleted.

9 changes: 9 additions & 0 deletions playground/auth.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
declare module '#auth-utils-session' {
interface UserSession {
user: {
spotify?: any
github?: any
}
loggedInAt: number
}
}
13 changes: 12 additions & 1 deletion playground/server/routes/auth/github.get.ts
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
export default oauth.githubEventHandler()
export default oauth.githubEventHandler({
async onSuccess(event, { user }) {
await setUserSession(event, {
user: {
github: user,
},
loggedInAt: Date.now()
})

return sendRedirect(event, '/')
}
})
13 changes: 12 additions & 1 deletion playground/server/routes/auth/spotify.get.ts
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
export default oauth.spotifyEventHandler()
export default oauth.spotifyEventHandler({
async onSuccess(event, { user }) {
await setUserSession(event, {
user: {
spotify: user,
},
loggedInAt: Date.now()
})

return sendRedirect(event, '/')
}
})
17 changes: 3 additions & 14 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { defineNuxtModule, addPlugin, createResolver, addImportsDir, addServerHandler, findPath } from '@nuxt/kit'
import { defineNuxtModule, addPlugin, createResolver, addImportsDir, addServerHandler } from '@nuxt/kit'
import { sha256 } from 'ohash'
import { defu } from 'defu'
import { resolve } from 'pathe'

// Module options TypeScript interface definition
export interface ModuleOptions {}
Expand All @@ -13,7 +12,7 @@ export default defineNuxtModule<ModuleOptions>({
},
// Default configuration options of the Nuxt module
defaults: {},
async setup (options, nuxt) {
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)

if (!process.env.NUXT_SESSION_PASSWORD) {
Expand All @@ -25,10 +24,7 @@ export default defineNuxtModule<ModuleOptions>({
}
}

// Allow user to define custom session/user
nuxt.options.watch.push('app/auth-utils-session.ts', 'app/auth-utils-session.js', 'app/auth-utils-session.mjs')

nuxt.options.alias['#auth-utils-session'] = await findFirstExisting(nuxt.options._layers.map(layer => resolve(layer.config.srcDir || layer.cwd, 'app/auth-utils-session'))) || resolver.resolve('./runtime/app/auth-utils-session')
nuxt.options.alias['#auth-utils-session'] = resolver.resolve('./runtime/types/auth-utils-session')

// App
addImportsDir(resolver.resolve('./runtime/composables'))
Expand Down Expand Up @@ -70,10 +66,3 @@ export default defineNuxtModule<ModuleOptions>({
})
}
})

async function findFirstExisting (paths: string[]) {
for (const path of paths) {
const resolvedPath = await findPath(path)
if (resolvedPath) { return resolvedPath }
}
}
9 changes: 0 additions & 9 deletions src/runtime/app/auth-utils-session.ts

This file was deleted.

3 changes: 1 addition & 2 deletions src/runtime/composables/session.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useState, computed, useRequestFetch } from '#imports'
import type { default as UserSessionFactory } from '#auth-utils-session'
type UserSession = ReturnType<typeof UserSessionFactory>
import type { UserSession } from '#auth-utils-session'

const useSessionState = () => useState<UserSession | Record<string, unknown>>('nuxt-session', () => ({}))

Expand Down
10 changes: 1 addition & 9 deletions src/runtime/server/lib/oauth/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { eventHandler, createError, getQuery, getRequestURL, sendRedirect } from
import { ofetch } from 'ofetch'
import { withQuery } from 'ufo'
import { defu } from 'defu'
import { default as createUserSession } from '#auth-utils-session'
import { setUserSession } from '../../utils/session'

export interface OAuthGitHubConfig {
/**
Expand Down Expand Up @@ -45,7 +43,7 @@ export interface OAuthGitHubConfig {

interface OAuthConfig {
config?: OAuthGitHubConfig
onSuccess?: (event: H3Event, result: { user: any, tokens: any }) => Promise<void> | void
onSuccess: (event: H3Event, result: { user: any, tokens: any }) => Promise<void> | void
onError?: (event: H3Event, error: H3Error) => Promise<void> | void
}

Expand Down Expand Up @@ -129,12 +127,6 @@ export function githubEventHandler({ config, onSuccess, onError }: OAuthConfig)
user.email = primaryEmail.email
}

if (!onSuccess) {
const session = await createUserSession(event, { provider: 'github', user, tokens })
await setUserSession(event, session)
return sendRedirect(event, '/')
}

return onSuccess(event, {
user,
tokens,
Expand Down
9 changes: 1 addition & 8 deletions src/runtime/server/lib/oauth/spotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { eventHandler, createError, getQuery, getRequestURL, sendRedirect } from
import { withQuery, parsePath } from 'ufo'
import { ofetch } from 'ofetch'
import { defu } from 'defu'
import { default as createUserSession } from '#auth-utils-session'

export interface OAuthSpotifyConfig {
/**
Expand Down Expand Up @@ -44,7 +43,7 @@ export interface OAuthSpotifyConfig {

interface OAuthConfig {
config?: OAuthSpotifyConfig
onSuccess?: (event: H3Event, result: { user: any, tokens: any }) => Promise<void> | void
onSuccess: (event: H3Event, result: { user: any, tokens: any }) => Promise<void> | void
onError?: (event: H3Event, error: H3Error) => Promise<void> | void
}

Expand Down Expand Up @@ -119,12 +118,6 @@ export function spotifyEventHandler({ config, onSuccess, onError }: OAuthConfig)
}
})

if (!onSuccess) {
const session = await createUserSession(event, { provider: 'spotify', user, tokens })
await setUserSession(event, session)
return sendRedirect(event, '/')
}

return onSuccess(event, {
tokens,
user
Expand Down
5 changes: 1 addition & 4 deletions src/runtime/server/utils/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ import type { H3Event } from 'h3'
import { useSession, createError } from 'h3'
import { defu } from 'defu'
import { useRuntimeConfig } from '#imports'
import type { default as UserSessionFactory } from '#auth-utils-session'
type UserSession = ReturnType<typeof UserSessionFactory>

export const defineSession = <T extends Record<string, unknown> & { user?: unknown }>(definition: (event: H3Event, result: { provider: string, user: any, tokens: any }) => T) => definition
import type { UserSession } from '#auth-utils-session'

export async function getUserSession (event: H3Event) {
return (await _useSession(event)).data as UserSession
Expand Down
3 changes: 3 additions & 0 deletions src/runtime/types/auth-utils-session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface UserSession {
user?: {}
}

0 comments on commit b3e92c8

Please sign in to comment.