Skip to content

Commit 5276a97

Browse files
andychuksezoey-kaiserphoenix-ru
authored
enh(#861): Redirect back to requested page after authentication (#870)
* merge with main * added check for presence of addDefaultCallbackUrl in globalAppMiddleware * Update src/runtime/composables/local/useAuth.ts * Update useAuth.ts --------- Co-authored-by: Zoey <[email protected]> Co-authored-by: Marsel Shayhin <[email protected]>
1 parent 8c73bf3 commit 5276a97

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/runtime/composables/local/useAuth.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { type UseAuthStateReturn, useAuthState } from './useAuthState'
1010
import { callWithNuxt } from '#app/nuxt'
1111
// @ts-expect-error - #auth not defined
1212
import type { SessionData } from '#auth'
13-
import { navigateTo, nextTick, useNuxtApp, useRuntimeConfig } from '#imports'
13+
import { navigateTo, nextTick, useNuxtApp, useRoute, useRuntimeConfig } from '#imports'
1414

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

@@ -60,7 +60,13 @@ const signIn: SignInFunc<Credentials, any> = async (credentials, signInOptions,
6060
const { redirect = true, external } = signInOptions ?? {}
6161
let { callbackUrl } = signInOptions ?? {}
6262
if (typeof callbackUrl === 'undefined') {
63-
callbackUrl = await determineCallbackUrl(runtimeConfig.public.auth, () => getRequestURLWN(nuxt))
63+
const redirectQueryParam = useRoute()?.query?.redirect
64+
if (redirectQueryParam) {
65+
callbackUrl = redirectQueryParam.toString()
66+
}
67+
else {
68+
callbackUrl = await determineCallbackUrl(runtimeConfig.public.auth, () => getRequestURLWN(nuxt))
69+
}
6470
}
6571
if (redirect) {
6672
return navigateTo(callbackUrl, { external })

src/runtime/middleware/auth.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,19 @@ export default defineNuxtRouteMiddleware((to) => {
105105
return navigateTo(metaAuth.navigateUnauthenticatedTo)
106106
}
107107
else {
108+
if (typeof globalAppMiddleware === 'object' && globalAppMiddleware.addDefaultCallbackUrl) {
109+
let redirectUrl: string = to.fullPath
110+
if (typeof globalAppMiddleware.addDefaultCallbackUrl === 'string') {
111+
redirectUrl = globalAppMiddleware.addDefaultCallbackUrl
112+
}
113+
114+
return navigateTo({
115+
path: authConfig.provider.pages.login,
116+
query: {
117+
redirect: redirectUrl
118+
}
119+
})
120+
}
108121
return navigateTo(authConfig.provider.pages.login)
109122
}
110123
})

0 commit comments

Comments
 (0)