hrms-edm/Services/client/src/services/KeyCloakService.ts

48 lines
1 KiB
TypeScript
Raw Normal View History

2023-11-28 09:22:44 +07:00
import Keycloak from 'keycloak-js'
2023-11-23 08:47:44 +07:00
2025-02-17 09:21:28 +07:00
const keycloak = new Keycloak({
2025-02-17 11:19:12 +07:00
realm: import.meta.env.VITE_KC_REALM,
url: import.meta.env.VITE_KC_URL,
clientId: import.meta.env.VITE_CLIENTID_KEYCLOAK,
2025-02-17 09:21:28 +07:00
})
2023-12-11 10:10:39 +07:00
let init = false
2023-11-23 08:47:44 +07:00
2023-12-11 10:10:39 +07:00
export async function login(cb?: (...args: any[]) => void) {
const auth = !init
? await keycloak
.init({
onLoad: 'login-required',
responseMode: 'query',
checkLoginIframe: false,
})
.catch((e) => console.dir(e))
: await keycloak.login().catch((e) => console.dir(e))
if (auth) init = true
if (auth && cb) cb()
}
2023-11-23 08:47:44 +07:00
export async function logout() {
await keycloak.logout()
}
2023-11-23 08:47:44 +07:00
export async function getToken() {
await keycloak.updateToken(60).catch(() => login())
return keycloak.token
2023-11-28 09:22:44 +07:00
}
2023-11-23 08:47:44 +07:00
export function getUsername(): string {
return keycloak.tokenParsed?.preferred_username
}
2023-11-23 08:47:44 +07:00
export function getRole(): string[] {
const decoded = keycloak.tokenParsed
2023-11-23 08:47:44 +07:00
2025-09-09 15:01:33 +07:00
return decoded?.roles ?? decoded?.role ?? []
2023-11-28 09:22:44 +07:00
}
2023-11-23 08:47:44 +07:00
export function isLoggedIn() {
return !!keycloak.token
2023-11-28 09:22:44 +07:00
}