updated check token

This commit is contained in:
Warunee Tamkoo 2024-07-26 14:13:10 +07:00
parent 3718dad5f4
commit 974b64bb80
7 changed files with 93 additions and 46 deletions

View file

@ -1,5 +1,5 @@
import Axios, { type AxiosRequestConfig, type AxiosResponse } from "axios";
import keycloak from "./keycloak";
import keycloak, { kcLogout } from "./keycloak";
const http = Axios.create({
timeout: 1000000000, // เพิ่มค่า timeout
@ -33,7 +33,7 @@ http.interceptors.response.use(
// eslint-disable-next-line no-prototype-builtins
if (error.hasOwnProperty("response")) {
if (error.response.status === 401 || error.response.status === 403) {
window.location.href = "/login";
kcLogout();
// Store.commit("SET_ERROR_MESSAGE", error.response.data.message);
// Store.commit("REMOVE_ACCESS_TOKEN")
}

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,
};