keycloak.ts
1.06 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
import { useKeycloakStore } from '@/@core/stores/keycloakStore'
import keycloakInstance from '@/keycloak'
export default defineNuxtPlugin(async nuxtApp => {
const keycloakStore = useKeycloakStore()
try {
const authenticated = await keycloakInstance.init({
onLoad: 'check-sso',
})
keycloakStore.authenticated = authenticated
if (authenticated) {
keycloakStore.refresh()
console.log('User is authenticated')
navigateTo('/profile')
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')
navigateTo('/login')
}
}
catch (error) {
console.error('Keycloak init error:', error)
}
})