fixing check token

This commit is contained in:
Warunee Tamkoo 2024-07-26 14:17:03 +07:00
parent 04da1988b0
commit 00cb0c6f23
7 changed files with 83 additions and 66 deletions

View file

@ -1,6 +1,8 @@
// authen with keycloak client
import Keycloak from 'keycloak-js'
const ACCESS_TOKEN = 'BMAHRIS_KEYCLOAK_IDENTITY'
const REFRESH_TOKEN = 'BMAHRIS_KEYCLOAK_REFRESH'
const keycloakConfig = {
url: 'https://id.frappet.synology.me',
realm: 'bma-ehr',
@ -9,5 +11,60 @@ const keycloakConfig = {
}
const keycloak = new Keycloak(keycloakConfig)
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=/;`
}
export default keycloak
export { keycloakConfig }
export {
keycloakConfig,
getToken,
kcAuthen,
kcLogout,
ACCESS_TOKEN,
REFRESH_TOKEN,
}