fix: desregistrar Service Worker al perder autenticación
All checks were successful
build-and-deploy / build (push) Successful in 23s
build-and-deploy / deploy (push) Successful in 3s

- Desregistrar SW automáticamente cuando se detecta pérdida de auth
- Desregistrar SW antes de triggerAuth para evitar conflictos con Authentik
- Deshabilitar polling y listeners de visibility (causan errores de CORS)
- Confiar en detección reactiva de errores del musicStore
- Usar window.location.href en lugar de reload() para forzar navegación
This commit is contained in:
2025-10-12 03:12:03 -06:00
parent fda5b2497a
commit cda4722a27
2 changed files with 50 additions and 13 deletions

View File

@@ -37,22 +37,25 @@ const musicStore = useMusicStore()
// Check auth on mount and setup listeners // Check auth on mount and setup listeners
onMounted(async () => { onMounted(async () => {
// Asumimos autenticado inicialmente (si la página cargó, pasamos Authentik) // Asumimos autenticado inicialmente (si la página cargó, pasamos Authentik)
// Solo verificamos para confirmar // NO hacemos checkAuth inicial para evitar conflictos con Service Worker y Authentik
await checkAuth(false) console.log('[AuthIndicator] Mounted - assuming authenticated (page loaded successfully)')
setupVisibilityListener() setupVisibilityListener()
// Polling más inteligente: solo si estamos autenticados // POLLING DESHABILITADO: Causa conflictos con Authentik cuando no estamos autenticados
// En su lugar, confiamos en la detección reactiva de errores del musicStore
console.log('[AuthIndicator] Polling disabled - relying on reactive error detection')
/* CÓDIGO DESHABILITADO
const interval = setInterval(() => { const interval = setInterval(() => {
if (!document.hidden && isAuthenticated.value) { if (!document.hidden && isAuthenticated.value) {
// Solo hace polling si creemos estar autenticados
// Evita spam de requests cuando ya sabemos que no estamos autenticados
checkAuth(false) checkAuth(false)
} }
}, 60000) // 60 segundos (menos agresivo) }, 60000)
onUnmounted(() => { onUnmounted(() => {
clearInterval(interval) clearInterval(interval)
}) })
*/
}) })
// Cleanup listeners on unmount // Cleanup listeners on unmount

View File

@@ -86,24 +86,57 @@ export const useAuth = () => {
} }
} }
const triggerAuth = () => { const triggerAuth = async () => {
console.log('[Auth] Triggering authentication flow - forcing page reload...') console.log('[Auth] Triggering authentication flow...')
// Simplemente recargamos la página completamente // Desregistrar el Service Worker temporalmente para evitar conflictos con Authentik
// Si no estamos autenticados, Authentik interceptará y redirigirá al login if ('serviceWorker' in navigator) {
// Si ya estamos autenticados, la página se recarga normalmente try {
window.location.reload() const registrations = await navigator.serviceWorker.getRegistrations()
console.log('[Auth] Unregistering Service Workers before auth...')
await Promise.all(registrations.map(reg => reg.unregister()))
} catch (error) {
console.warn('[Auth] Could not unregister SW:', error)
}
}
// Forzar navegación completa a la raíz
// Authentik interceptará y redirigirá al login si no estamos autenticados
console.log('[Auth] Forcing hard navigation to trigger Authentik...')
window.location.href = window.location.origin + '/'
} }
const markUnauthenticated = () => { const markUnauthenticated = async () => {
// Helper para marcar como no autenticado (útil cuando detectamos 401/403) // Helper para marcar como no autenticado (útil cuando detectamos 401/403)
console.log('[Auth] Marking as unauthenticated') console.log('[Auth] Marking as unauthenticated')
isAuthenticated.value = false isAuthenticated.value = false
authChecked.value = true authChecked.value = true
lastCheckTime.value = Date.now() lastCheckTime.value = Date.now()
// Desregistrar Service Worker para evitar conflictos con Authentik
if ('serviceWorker' in navigator) {
try {
const registrations = await navigator.serviceWorker.getRegistrations()
if (registrations.length > 0) {
console.log('[Auth] Unregistering Service Worker due to auth loss...')
await Promise.all(registrations.map(reg => reg.unregister()))
console.log('[Auth] Service Worker unregistered - page will need reload for re-auth')
}
} catch (error) {
console.warn('[Auth] Could not unregister SW:', error)
}
}
} }
const setupVisibilityListener = () => { const setupVisibilityListener = () => {
// DESHABILITADO: Los listeners causan problemas con Authentik
// Cuando no estamos autenticados, los listeners intentan hacer fetch
// y Authentik redirige, causando errores de CORS
// En su lugar, confiamos en que el usuario haga click en "Reautenticar"
console.log('[Auth] Visibility listeners disabled to avoid conflicts with Authentik')
return
/* CÓDIGO DESHABILITADO
// Re-chequea auth cuando la pestaña vuelve a ser visible // Re-chequea auth cuando la pestaña vuelve a ser visible
// (útil si el usuario se autentica en otra pestaña) // (útil si el usuario se autentica en otra pestaña)
if (typeof document !== 'undefined' && !visibilityChangeListener) { if (typeof document !== 'undefined' && !visibilityChangeListener) {
@@ -129,6 +162,7 @@ export const useAuth = () => {
} }
window.addEventListener('focus', focusListener) window.addEventListener('focus', focusListener)
} }
*/
} }
const cleanupListeners = () => { const cleanupListeners = () => {