Skip to content

Commit 3a0a3e7

Browse files
committed
fix: properly handle state if cookie already exists
resolves #461
1 parent f8f297c commit 3a0a3e7

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

src/runtime/server/lib/oauth/ory.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ export function defineOAuthOryEventHandler({ config, onSuccess, onError }: OAuth
126126
}
127127

128128
if (query.state !== state) {
129-
handleInvalidState(event, 'ory', onError)
129+
return handleInvalidState(event, 'ory', onError)
130130
}
131131

132132
const tokenURL = `${config.sdkURL}${config.tokenURL}`

src/runtime/server/lib/utils.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { type H3Event, deleteCookie, getCookie, setCookie } from 'h3'
1+
import { type H3Event, deleteCookie, getCookie, getQuery, setCookie } from 'h3'
22
import { getRequestURL } from 'h3'
33
import { FetchError } from 'ofetch'
44
import { snakeCase, upperFirst } from 'scule'
@@ -205,13 +205,16 @@ export async function handlePkceVerifier(event: H3Event) {
205205
}
206206

207207
export async function handleState(event: H3Event) {
208-
let state = getCookie(event, 'nuxt-auth-state')
209-
if (state) {
208+
const query = getQuery<{ state?: string }>(event)
209+
// If the state is in the query, get it from the cookie and delete the cookie
210+
if (query.state) {
211+
const state = getCookie(event, 'nuxt-auth-state')
210212
deleteCookie(event, 'nuxt-auth-state')
211213
return state
212214
}
213215

214-
state = encodeBase64Url(getRandomBytes(8))
216+
// If the state is not in the query, generate a new state and set it in the cookie
217+
const state = encodeBase64Url(getRandomBytes(8))
215218
setCookie(event, 'nuxt-auth-state', state)
216219
return state
217220
}

0 commit comments

Comments
 (0)