Refactor authentication to use centralized session manager
Extract session management logic from middleware into reusable SessionManager utility to improve reliability, reduce code duplication, and prevent thundering herd issues with jittered cache expiry.
This commit is contained in:
@@ -209,30 +209,42 @@ export default defineNuxtPlugin(() => {
|
||||
})
|
||||
}
|
||||
|
||||
// Add periodic session validation (every 2 minutes)
|
||||
// Add periodic session validation (every 2 minutes with offset)
|
||||
let validationInterval: NodeJS.Timeout | null = null
|
||||
let isValidating = false // Prevent concurrent validations
|
||||
|
||||
onMounted(() => {
|
||||
validationInterval = setInterval(async () => {
|
||||
console.log('[AUTH_REFRESH] Performing periodic session validation')
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/session', {
|
||||
headers: {
|
||||
'Cache-Control': 'no-cache',
|
||||
'Pragma': 'no-cache'
|
||||
}
|
||||
})
|
||||
// Add random offset to prevent all clients checking at once
|
||||
const randomOffset = Math.floor(Math.random() * 5000) // 0-5 seconds
|
||||
|
||||
setTimeout(() => {
|
||||
validationInterval = setInterval(async () => {
|
||||
if (isValidating) return // Skip if already validating
|
||||
|
||||
if (!response.ok || response.status === 401) {
|
||||
console.log('[AUTH_REFRESH] Session invalid during periodic check')
|
||||
clearInterval(validationInterval!)
|
||||
await navigateTo('/login')
|
||||
isValidating = true
|
||||
console.log('[AUTH_REFRESH] Performing periodic session validation')
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/session', {
|
||||
headers: {
|
||||
'Cache-Control': 'no-cache',
|
||||
'Pragma': 'no-cache'
|
||||
}
|
||||
})
|
||||
|
||||
if (!response.ok || response.status === 401) {
|
||||
console.log('[AUTH_REFRESH] Session invalid during periodic check')
|
||||
clearInterval(validationInterval!)
|
||||
await navigateTo('/login')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[AUTH_REFRESH] Periodic validation error:', error)
|
||||
// Don't logout on network errors - let middleware handle it
|
||||
} finally {
|
||||
isValidating = false
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[AUTH_REFRESH] Periodic validation error:', error)
|
||||
}
|
||||
}, 2 * 60 * 1000) // Every 2 minutes
|
||||
}, 2 * 60 * 1000) // Keep at 2 minutes
|
||||
}, randomOffset)
|
||||
})
|
||||
|
||||
// Clean up timers on plugin destruction
|
||||
|
||||
Reference in New Issue
Block a user