const ACCESS_TOKEN = "BMAHRIS_KEYCLOAK_IDENTITY"; interface AuthResponse { access_token: string; expires_in: number; refresh_token: string; } const authenticated = async () => ((await getToken()) ? true : false); async function setAuthen(r: AuthResponse) { await setCookie(ACCESS_TOKEN, r.access_token, r.expires_in); window.location.href = "/"; } async function logout() { await deleteCookie(ACCESS_TOKEN); window.location.href = "/login"; } async function getToken() { return getCookie(ACCESS_TOKEN); } // 2024-08-29T02:55:13.000Z function setCookie(name: string, value: any, time: number) { let expires = ""; if (time) { const date = new Date(); date.setTime(date.getTime() + time * 1000); // 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=/;`; } async function tokenParsed() { const token = await getCookie(ACCESS_TOKEN); if (!token) { return null; } const base64Url = token.split(".")[1]; const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/"); const jsonPayload = decodeURIComponent( window .atob(base64) .split("") .map(function (c) { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); }) .join("") ); return JSON.parse(jsonPayload); } export { getToken, authenticated, logout, setAuthen, tokenParsed };