keycloak.ts 1.61 KB
import { useKeycloakStore } from '@/@core/stores/keycloakStore'
import keycloakInstance from '@/keycloak'

export default defineNuxtPlugin(async nuxtApp => {
  const keycloakStore = useKeycloakStore()

  /* `const {  } = nuxtApp` is a destructuring assignment in JavaScript/TypeScript. In this
  case, it is extracting the `` property from the `nuxtApp` object and assigning it to a new
  constant named ``. This allows you to access the `` object directly without having
  to use `nuxtApp.` every time. It's a shorthand way of accessing nested properties in
  objects. */
  // const { $router } = nuxtApp

  try {
    const authenticated = await keycloakInstance.init({
      onLoad: 'check-sso',
      checkLoginIframe: true,
      checkLoginIframeInterval: 5, // in seconds, default is 5
    })

    keycloakStore.authenticated = authenticated

    if (authenticated) {
      keycloakStore.refresh()
      console.log('User is authenticated')

      // $router.push('/profile')
      // console.log('Suppose to navigate To')

      setInterval(() => {
        const now = Math.floor(Date.now() / 1000)
        const tokenExp = keycloakInstance.tokenParsed?.exp ?? 0

        if (tokenExp <= now) {
          console.warn('Token expired. Logging out...')
          keycloakInstance.logout({ redirectUri: `${window.location.origin}/login` })
        }
        else {
          // console.log('Token expires in:', tokenExp - now, 'seconds')
        }
      }, 10_000)
    }
    else {
      console.log('User is not authenticated')

      // $router.push('/login')
    }
  }
  catch (error) {
    console.error('Keycloak init error:', error)
  }
})