keycloak.ts
1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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)
}
})