fix: auth redirects and routing context issues

This commit is contained in:
2026-06-13 10:22:00 +02:00 Unverified
parent 1dbbfbaa2e
commit ca866404af
6 changed files with 17 additions and 16 deletions
+3 -2
View File
@@ -2,7 +2,8 @@ import { defu } from 'defu'
export const useApiFetch = <T>(request: string, options: Parameters<typeof $fetch>[1] = {}) => {
const config = useRuntimeConfig()
const tokenCookie = useCookie('auth_token')
const nuxtApp = useNuxtApp()
const tokenCookie = useCookie('auth_token', { path: '/' })
const tokenState = useState<string | null>('auth_token_state')
const tokenValue = tokenState.value ?? tokenCookie.value
@@ -38,7 +39,7 @@ export const useApiFetch = <T>(request: string, options: Parameters<typeof $fetc
}
try {
navigateTo('/auth/login')
nuxtApp.runWithContext(() => navigateTo('/auth/login'))
} catch (e) {
console.error('[API] Error navigating to login:', e)
}
+11 -8
View File
@@ -8,9 +8,13 @@ import type {
} from "~/types/api";
export const useAuth = () => {
const token = useCookie('auth_token', {
const route = useRoute()
const nuxtApp = useNuxtApp()
const token = useCookie<string | null>('auth_token', {
maxAge: 60 * 60 * 12,
sameSite: 'lax',
path: '/',
watch: true
})
@@ -25,7 +29,7 @@ export const useAuth = () => {
tokenState.value = newVal || null
})
const syncUser = async () => {
const syncUser = async (redirectOnSuccess = false) => {
const tokenVal = tokenState.value || token.value
if (!tokenVal || isSyncingUser.value) return
@@ -36,12 +40,11 @@ export const useAuth = () => {
console.log('[Auth] User synced successfully')
user.value = res.user
const route = useRoute()
if (res.user.must_change_password && route.path !== '/auth/change-password') {
console.log('[Auth] User must change password, redirecting...')
await navigateTo('/auth/change-password')
} else {
await navigateTo('/dashboard')
await nuxtApp.runWithContext(() => navigateTo('/auth/change-password'))
} else if (redirectOnSuccess && route.path.startsWith('/auth')) {
await nuxtApp.runWithContext(() => navigateTo('/me'))
}
}
} catch (error) {
@@ -55,14 +58,14 @@ export const useAuth = () => {
const handleLoginSuccess = async (jwtToken: string) => {
token.value = jwtToken
tokenState.value = jwtToken
await syncUser()
await syncUser(true)
}
const logout = () => {
token.value = null
tokenState.value = null
user.value = null
navigateTo('/auth/login')
nuxtApp.runWithContext(() => navigateTo('/auth/login'))
}
const register = (body: RegisterCitizenRequest) =>