indicador de conexion y logging
This commit is contained in:
81
composables/useAuth.ts
Normal file
81
composables/useAuth.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
// Estado global compartido para auth
|
||||
const authChecked = ref(false)
|
||||
const isAuthenticated = ref(false)
|
||||
const isCheckingAuth = ref(false)
|
||||
const lastCheckTime = ref(0)
|
||||
|
||||
export const useAuth = () => {
|
||||
const checkAuth = async (force = false) => {
|
||||
// Evitar chequeos duplicados (cache de 30 segundos)
|
||||
const now = Date.now()
|
||||
if (!force && isCheckingAuth.value) return
|
||||
if (!force && authChecked.value && now - lastCheckTime.value < 30000) {
|
||||
return
|
||||
}
|
||||
|
||||
isCheckingAuth.value = true
|
||||
|
||||
try {
|
||||
// Intenta hacer fetch a un endpoint protegido
|
||||
const response = await fetch('/api/music', {
|
||||
method: 'HEAD', // Solo headers, no body
|
||||
credentials: 'include', // Include cookies for auth
|
||||
signal: AbortSignal.timeout(5000) // 5s timeout
|
||||
})
|
||||
|
||||
// Si responde 200, estamos autenticados
|
||||
// Si responde 401/403, no estamos autenticados
|
||||
isAuthenticated.value = response.ok
|
||||
authChecked.value = true
|
||||
lastCheckTime.value = now
|
||||
|
||||
console.log('[Auth] Status:', isAuthenticated.value ? 'authenticated' : 'unauthenticated')
|
||||
} catch (error) {
|
||||
console.warn('[Auth] Failed to check authentication status:', error)
|
||||
// En caso de error de red, mantenemos el último estado conocido si existe
|
||||
// Solo marcamos como no autenticado si es el primer chequeo
|
||||
if (!authChecked.value) {
|
||||
isAuthenticated.value = false
|
||||
}
|
||||
authChecked.value = true
|
||||
lastCheckTime.value = now
|
||||
} finally {
|
||||
isCheckingAuth.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const triggerAuth = () => {
|
||||
console.log('[Auth] Redirecting to trigger Authentik...')
|
||||
// Redirige a la página principal para que Authentik intercepte
|
||||
// Si ya estamos en /, forzamos reload
|
||||
if (window.location.pathname === '/') {
|
||||
window.location.reload()
|
||||
} else {
|
||||
window.location.href = '/'
|
||||
}
|
||||
}
|
||||
|
||||
const markUnauthenticated = () => {
|
||||
// Helper para marcar como no autenticado (útil cuando detectamos 401/403)
|
||||
isAuthenticated.value = false
|
||||
authChecked.value = true
|
||||
lastCheckTime.value = Date.now()
|
||||
}
|
||||
|
||||
const authStatus = computed(() => {
|
||||
if (!authChecked.value) return 'unknown'
|
||||
return isAuthenticated.value ? 'authenticated' : 'unauthenticated'
|
||||
})
|
||||
|
||||
return {
|
||||
isAuthenticated,
|
||||
authChecked,
|
||||
isCheckingAuth,
|
||||
authStatus,
|
||||
checkAuth,
|
||||
triggerAuth,
|
||||
markUnauthenticated
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user