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

fix: authState getting wiped on page reload on static websites #785

Open
wants to merge 29 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
6dd86b2
set and reload data, rawToken from cookie
Vijayabhaskar96 Mar 14, 2024
8a36118
fix lint
Vijayabhaskar96 Mar 14, 2024
9b4b8b1
fix typecheck
Vijayabhaskar96 Mar 14, 2024
505c583
Merge branch 'main' into main
zoey-kaiser Apr 5, 2024
534557a
Merge branch 'main' into main
phoenix-ru Apr 18, 2024
d371950
set and reload data, rawToken from cookie
Vijayabhaskar96 Mar 14, 2024
5780a45
fix undefined sessionCookie case
Vijayabhaskar96 Jul 5, 2024
38cb342
Merge remote-tracking branch 'origin/main' into update-pull-request
Vijayabhaskar96 Jul 6, 2024
600d69c
Merge branch 'main' into update-pull-request
Vijayabhaskar96 Jul 6, 2024
d8f0461
fix lint
Vijayabhaskar96 Jul 6, 2024
d814048
fix undefined cases
Vijayabhaskar96 Jul 6, 2024
a43147c
Merge branch 'main' into update-pull-request
zoey-kaiser Jul 13, 2024
6d13eb4
Merge branch 'main' into update-pull-request
zoey-kaiser Jul 19, 2024
fb7a26a
Merge branch 'main' into update-pull-request
zoey-kaiser Aug 8, 2024
e1a122e
Merge branch 'main' into update-pull-request
zoey-kaiser Aug 8, 2024
0060358
Merge branch 'main' into update-pull-request
zoey-kaiser Aug 9, 2024
25ee10e
Merge branch 'main' into update-pull-request
zoey-kaiser Aug 20, 2024
e64a195
Merge branch 'main' into update-pull-request
zoey-kaiser Sep 18, 2024
b0ad984
fix: linting in useAuth
zoey-kaiser Sep 18, 2024
882061f
fix: lint in plugin
zoey-kaiser Sep 18, 2024
907ff2e
fix: trailing spaces
zoey-kaiser Sep 18, 2024
f812357
organize code
Vijayabhaskar96 Sep 19, 2024
e7163cc
Merge branch 'main' into update-pull-request
Vijayabhaskar96 Sep 19, 2024
86feff3
fix typo
Vijayabhaskar96 Sep 19, 2024
75d167e
Merge branch 'update-pull-request' of https://github.com/Vijayabhaska…
Vijayabhaskar96 Sep 19, 2024
0f7e51a
Merge branch 'main' into update-pull-request
Vijayabhaskar96 Oct 29, 2024
7d04329
Merge branch 'sidebase:main' into update-pull-request
Vijayabhaskar96 Dec 5, 2024
2be6b25
Merge branch 'main' into update-pull-request
phoenix-ru Dec 12, 2024
44d1291
Merge branch 'main' into update-pull-request
phoenix-ru Dec 19, 2024
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
12 changes: 11 additions & 1 deletion src/runtime/composables/local/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { formatToken } from '../../utils/local'
import { useAuthState } from './useAuthState'
// @ts-expect-error - #auth not defined
import type { SessionData } from '#auth'
import { useNuxtApp, useRuntimeConfig, nextTick, navigateTo } from '#imports'
import { useCookie, useNuxtApp, useRuntimeConfig, nextTick, navigateTo } from '#imports'

type Credentials = { username?: string, email?: string, password?: string } & Record<string, any>

Expand Down Expand Up @@ -91,12 +91,21 @@ const getSession: GetSessionFunc<SessionData | null | void> = async (getSessionO
if (getSessionConfig) {
const headers = new Headers(token ? { [config.token.headerName]: token } as HeadersInit : undefined)
const { path, method } = getSessionConfig
const sessionCookie = useCookie<Object | null>('auth:sessionCookie', {
default: () => null,
maxAge: config.token.maxAgeInSeconds,
sameSite: config.token.sameSiteAttribute
})

loading.value = true
try {
const result = await _fetch<any>(nuxt, path, { method, headers })
const { dataResponsePointer: sessionDataResponsePointer } = config.session
data.value = jsonPointerGet<SessionData>(result, sessionDataResponsePointer)
sessionCookie.value = {
lastRefreshedAt: lastRefreshedAt.value,
data: data.value
}
} catch (err) {
if (!data.value && err instanceof Error) {
console.error(`Session: unable to extract session, ${err.message}`)
Expand All @@ -105,6 +114,7 @@ const getSession: GetSessionFunc<SessionData | null | void> = async (getSessionO
// Clear all data: Request failed so we must not be authenticated
data.value = null
rawToken.value = null
sessionCookie.value = null
}
loading.value = false
lastRefreshedAt.value = new Date()
Expand Down
28 changes: 25 additions & 3 deletions src/runtime/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { getHeader } from 'h3'
import authMiddleware from './middleware/auth'
import { getNitroRouteRules } from './utils/kit'
import { addRouteMiddleware, defineNuxtPlugin, useRuntimeConfig, useAuth, useAuthState, _refreshHandler } from '#imports'
import { useTypedBackendConfig } from './helpers'
import type { SessionCookie } from './types'
import { addRouteMiddleware, defineNuxtPlugin, useRuntimeConfig, useAuth, useAuthState, useCookie, _refreshHandler } from '#imports'

export default defineNuxtPlugin(async (nuxtApp) => {
// 1. Initialize authentication state, potentially fetch current session
const { data, lastRefreshedAt, loading } = useAuthState()
const { data, lastRefreshedAt, rawToken, loading } = useAuthState()
const { getSession } = useAuth()

// use runtimeConfig
Expand All @@ -31,7 +33,27 @@ export default defineNuxtPlugin(async (nuxtApp) => {

// Only fetch session if it was not yet initialized server-side
if (typeof data.value === 'undefined' && !nitroPrerender && !disableServerSideAuth) {
await getSession()
// Restore the session data from the cookie if it exists
const config = useTypedBackendConfig(useRuntimeConfig(), 'local')
const sessionCookie = useCookie<SessionCookie | null>('auth:sessionCookie')
const cookieToken = useCookie<string | null>(config.token.cookieName)
if (sessionCookie.value && !rawToken.value && cookieToken.value) {
try {
loading.value = true
const sessionData = sessionCookie.value
lastRefreshedAt.value = sessionData?.lastRefreshedAt
data.value = sessionData?.data
rawToken.value = cookieToken.value
} catch (error) {
console.error('Failed to parse session data from cookie:', error)
} finally {
loading.value = false
}
}

if (!data.value) {
await getSession()
}
}

// 2. Setup session maintanence, e.g., auto refreshing or refreshing on foux
Expand Down
11 changes: 11 additions & 0 deletions src/runtime/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,3 +573,14 @@ export interface ModuleOptionsNormalized extends ModuleOptions {
fullBaseUrl: string
}
}
export interface SessionCookie {
lastRefreshedAt?: SessionLastRefreshedAt
data?: SessionDataObject
}

// Augment types
declare module 'nuxt/schema' {
interface PublicRuntimeConfig {
auth: ModuleOptionsNormalized
}
}
Comment on lines +637 to +642
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question as to why was this added?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I don't remember, but I guess it was causing merge conflicts.

Loading