sidebase / nuxt-auth

Authentication built for Nuxt 3! Easily add authentication via OAuth providers, credentials or Email Magic URLs!
https://auth.sidebase.io
MIT License
1.31k stars 164 forks source link

enableOnWindowFocus must be used only in authenticated condition #834

Closed YoshimiShima closed 3 months ago

YoshimiShima commented 3 months ago

Environment

Reproduction

// nuxt.config.ts

provider: {
  type: 'refresh',
  pages: {
    login: '/login',
  },
},
 sessionRefresh: {
   enablePeriodically: 90000,
   enableOnWindowFocus: true,
 },
globalAppMiddleware: {
   isEnabled: true,
},
// login.vue

definePageMeta({
   auth: {
     unauthenticatedOnly: true,
   },
})

Describe the bug

The enableOnWindowFocus feature should not be triggered on pages that are accessible to unauthenticated users. Currently, when a user switches back to a tab containing an unauthenticated page (such as the login page of us), the refresh mechanism is still executed, which is unnecessary and potentially problematic.

In the current implementation in src/runtime/utils/refreshHandler.ts, there's an inconsistency in how enablePeriodically and enableOnWindowFocus are handled. For enablePeriodically, there's a check for the authenticated state:

https://github.com/sidebase/nuxt-auth/blob/9295d1fe4f27d42c879862a48202f5b215fc0048/src/runtime/utils/refreshHandler.ts#L35-L42

However, for enableOnWindowFocus, no such check exists: https://github.com/sidebase/nuxt-auth/blob/9295d1fe4f27d42c879862a48202f5b215fc0048/src/runtime/utils/refreshHandler.ts#L72-L79 To resolve this issue and ensure consistency, we should add an authentication check for enableOnWindowFocus as well. A proposed solution is to add a condition like:

if (this.config?.enableOnWindowFocus && document.visibilityState === 'visible' && this.auth?.status.value !== 
'unauthenticated') {
  this.auth?.refresh()
}

This change would prevent unnecessary refresh attempts on unauthenticated pages and align the behavior with enablePeriodically. Thanks.

Additional context

No response

Logs

FetchError: [POST] "/app/main/api/auth/refresh": 403