2024-07-23 14:46:40 +07:00
|
|
|
// authen with keycloak client
|
2023-11-17 01:08:27 +07:00
|
|
|
import Keycloak from 'keycloak-js'
|
2023-11-15 09:51:52 +07:00
|
|
|
|
2024-07-26 14:17:03 +07:00
|
|
|
const ACCESS_TOKEN = 'BMAHRIS_KEYCLOAK_IDENTITY'
|
|
|
|
|
const REFRESH_TOKEN = 'BMAHRIS_KEYCLOAK_REFRESH'
|
2024-07-16 21:27:39 +07:00
|
|
|
const keycloakConfig = {
|
2024-08-01 13:50:21 +07:00
|
|
|
url: import.meta.env.VITE_URL_KEYCLOAK,
|
|
|
|
|
realm: import.meta.env.VITE_REALM_KEYCLOAK,
|
|
|
|
|
clientId: import.meta.env.VITE_CLIENTID_KEYCLOAK,
|
|
|
|
|
clientSecret: import.meta.env.VITE_CLIENTSECRET_KEYCLOAK,
|
2023-11-17 01:08:27 +07:00
|
|
|
}
|
2023-11-15 09:51:52 +07:00
|
|
|
|
2024-07-16 21:27:39 +07:00
|
|
|
const keycloak = new Keycloak(keycloakConfig)
|
2024-07-26 14:17:03 +07:00
|
|
|
|
|
|
|
|
async function kcAuthen(access_token: string, refresh_token: string) {
|
|
|
|
|
await setCookie(ACCESS_TOKEN, access_token, 1)
|
|
|
|
|
await setCookie(REFRESH_TOKEN, refresh_token, 1)
|
|
|
|
|
window.location.href = '/'
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function kcLogout() {
|
|
|
|
|
await deleteCookie(ACCESS_TOKEN)
|
|
|
|
|
await deleteCookie(REFRESH_TOKEN)
|
|
|
|
|
if (keycloak.authenticated !== undefined) {
|
|
|
|
|
keycloak.logout()
|
|
|
|
|
}
|
|
|
|
|
window.location.href = '/login'
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function getToken() {
|
|
|
|
|
return {
|
|
|
|
|
token: getCookie(ACCESS_TOKEN),
|
|
|
|
|
refresh_token: getCookie(REFRESH_TOKEN),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function setCookie(name: string, value: any, days: number) {
|
|
|
|
|
let expires = ''
|
|
|
|
|
if (days) {
|
|
|
|
|
const date = new Date()
|
|
|
|
|
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)
|
|
|
|
|
expires = '; expires=' + date.toUTCString()
|
|
|
|
|
}
|
|
|
|
|
document.cookie = name + '=' + (value || '') + expires + '; path=/'
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function getCookie(name: string) {
|
|
|
|
|
const nameEQ = name + '='
|
|
|
|
|
const ca = document.cookie.split(';')
|
|
|
|
|
for (let i = 0; i < ca.length; i++) {
|
|
|
|
|
let c = ca[i]
|
|
|
|
|
while (c.charAt(0) == ' ') c = c.substring(1, c.length)
|
|
|
|
|
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length)
|
|
|
|
|
}
|
|
|
|
|
return null
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function deleteCookie(name: string) {
|
|
|
|
|
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`
|
|
|
|
|
}
|
|
|
|
|
|
2023-11-17 01:08:27 +07:00
|
|
|
export default keycloak
|
2024-07-26 14:17:03 +07:00
|
|
|
export {
|
|
|
|
|
keycloakConfig,
|
|
|
|
|
getToken,
|
|
|
|
|
kcAuthen,
|
|
|
|
|
kcLogout,
|
|
|
|
|
ACCESS_TOKEN,
|
|
|
|
|
REFRESH_TOKEN,
|
|
|
|
|
}
|