todolist-proto/frontend/src/keycloak.ts

71 lines
1.9 KiB
TypeScript
Raw Normal View History

2026-01-20 18:40:33 +01:00
import Keycloak from 'keycloak-js'
let keycloak: Keycloak | null = null
export const initKeycloak = async (): Promise<Keycloak> => {
2026-01-20 20:34:43 +01:00
console.log('Initializing Keycloak...')
const clientId = 'dalex-proto'
2026-01-20 18:40:33 +01:00
keycloak = new Keycloak({
2026-01-20 20:34:43 +01:00
url: 'https://terminus.bluelake.cloud', // Remove trailing slash
2026-01-20 18:40:33 +01:00
realm: 'dalex-immo-dev',
2026-01-20 20:34:43 +01:00
clientId: clientId
})
console.log('Keycloak config:', {
url: 'https://terminus.bluelake.cloud',
realm: 'dalex-immo-dev',
clientId: clientId
2026-01-20 18:40:33 +01:00
})
try {
const authenticated = await keycloak.init({
onLoad: 'login-required',
2026-01-20 20:34:43 +01:00
checkLoginIframe: false,
pkceMethod: 'S256', // Using PKCE for public clients
redirectUri: 'http://localhost:3030/', // Explicit redirect URI
flow: 'standard' // Explicitly use standard (Authorization Code) flow
2026-01-20 18:40:33 +01:00
})
2026-01-20 20:34:43 +01:00
console.log('Keycloak initialized. Authenticated:', authenticated)
2026-01-20 18:40:33 +01:00
if (!authenticated) {
2026-01-20 20:34:43 +01:00
console.warn('User not authenticated after Keycloak init')
// Don't reload - keycloak.init with 'login-required' should redirect automatically
// The error will be thrown and handled by main.ts
throw new Error('Not authenticated')
2026-01-20 18:40:33 +01:00
}
2026-01-20 20:34:43 +01:00
console.log('User authenticated successfully')
console.log('Token:', keycloak.token?.substring(0, 50) + '...')
2026-01-20 18:40:33 +01:00
// Token refresh
setInterval(() => {
2026-01-20 20:34:43 +01:00
keycloak?.updateToken(70).catch((error) => {
console.error('Failed to refresh token', error)
2026-01-20 18:40:33 +01:00
keycloak?.login()
})
}, 60000)
return keycloak
} catch (error) {
2026-01-20 20:34:43 +01:00
console.error('Failed to initialize Keycloak:', error)
2026-01-20 18:40:33 +01:00
throw error
}
}
export const getKeycloak = (): Keycloak | null => {
return keycloak
}
export const getToken = (): string | undefined => {
return keycloak?.token
}
export const logout = (): void => {
2026-01-20 20:34:43 +01:00
keycloak?.logout({
redirectUri: 'http://localhost:3030/'
})
2026-01-20 18:40:33 +01:00
}