From 6538140333ecbffa4ccb6092d5db4dfc8d82e38c Mon Sep 17 00:00:00 2001 From: waruneeauy Date: Tue, 16 Jul 2024 21:27:39 +0700 Subject: [PATCH] updated sso --- src/main.ts | 36 ++++++++++++++++++++++++++++++++- src/plugins/axios.ts | 26 ++++++++++++------------ src/plugins/http.ts | 34 +++++++++++++++---------------- src/plugins/keycloak.ts | 23 ++++----------------- src/router/index.ts | 42 +++++++++++++++++++-------------------- src/views/MianView.vue | 44 ++++++++++++++++++++--------------------- 6 files changed, 111 insertions(+), 94 deletions(-) diff --git a/src/main.ts b/src/main.ts index ba1a714..b05a38c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3,6 +3,7 @@ import App from '@/App.vue' import '@/registerServiceWorker' import router from '@/router' import { createPinia } from 'pinia' +import keycloak from '@/plugins/keycloak' import { Quasar, Dialog, Notify, Loading } from 'quasar' import '@vuepic/vue-datepicker/dist/main.css' @@ -31,9 +32,42 @@ app.use(Quasar, { app.component( 'datepicker', - defineAsyncComponent(() => import('@vuepic/vue-datepicker')), + defineAsyncComponent(() => import('@vuepic/vue-datepicker')) ) app.config.globalProperties.$http = http +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 +} + +const kcToken = getCookie('BMAHRIS_KEYCLOAK_IDENTITY') +const kcRefreshToken = getCookie('BMAHRIS_KEYCLOAK_REFRESH') + +if (kcToken && kcRefreshToken) { + keycloak + .init({ + // onLoad: 'login-required', + checkLoginIframe: false, + token: kcToken, + refreshToken: kcRefreshToken, + }) + .then((authenticated) => { + console.log('authenticated', authenticated) + // // // if (authenticated) { + // // // app.mount('#app') + // // // } + }) + .catch((err) => { + console.error('Keycloak initialization failed:', err) + }) +} + app.mount('#app') diff --git a/src/plugins/axios.ts b/src/plugins/axios.ts index 3ed45c0..e34aec6 100644 --- a/src/plugins/axios.ts +++ b/src/plugins/axios.ts @@ -1,25 +1,25 @@ -import axios from "axios" -import config from "process" +import axios from 'axios' +import config from 'process' // import { dotnetPath } from "../path/axiosPath"; // import { getToken } from "@baloise/vue-keycloak"; -import keycloak from "@/plugins/keycloak" +import keycloak from '@/plugins/keycloak' const axiosInstance = axios.create({ - withCredentials: false, + withCredentials: false, }) // axiosInstance.defaults.baseURL = dotnetPath; axiosInstance.interceptors.request.use( - async (config) => { - const token = await keycloak.token - config.headers = { - Authorization: `Bearer ${token}`, - } - return config - }, - (error) => { - Promise.reject(error) + async (config) => { + const token = await keycloak.token + config.headers = { + Authorization: `Bearer ${token}`, } + return config + }, + (error) => { + Promise.reject(error) + } ) export default axiosInstance diff --git a/src/plugins/http.ts b/src/plugins/http.ts index 494c9aa..b82f8c1 100644 --- a/src/plugins/http.ts +++ b/src/plugins/http.ts @@ -1,45 +1,43 @@ -import Axios, { type AxiosRequestConfig, type AxiosResponse } from "axios"; -import keycloak from "./keycloak"; +import Axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios' +import keycloak from './keycloak' const http = Axios.create({ timeout: 1000000000, // เพิ่มค่า timeout headers: { - "X-Requested-With": "XMLHttpRequest", + 'X-Requested-With': 'XMLHttpRequest', }, -}); +}) http.interceptors.request.use( async function (config: AxiosRequestConfig) { - await keycloak.updateToken(1); - config.headers = config.headers ?? {}; - const token = keycloak.token; + // await keycloak.updateToken(1) + config.headers = config.headers ?? {} + const token = keycloak.token // const token = localStorage.getItem("access_token") - // const token = - // "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIxU2VKV2dVRFVlNXZwNS13Q1ZHaG9lT2l4bDJTTkdKemthLU5ZN211NXZJIn0.eyJleHAiOjE2NzI0MTI1NDksImlhdCI6MTY3MjM3NjU0OSwiYXV0aF90aW1lIjoxNjcyMzc2NTQ5LCJqdGkiOiI1MTVhY2IwNC1jODQ3LTQzM2YtYjUxOC03OD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YXRvciIsImVtYWlsIjoiYWRtaW5AbG9jYWxob3N0In0.xmfJ3pzI-jLYsaiFXyjTW7gfAEpvUmMVsp9BsB1CfRCVOKiGBbuZhnQY8W-1SWVAx1NjJ55L-zMHPK6hk1dRPLbEse3DlIBZw04W9j8m-Wz3eqdHf_UCjmrXb8qAwkeq0Iaxq9mVfJJeQWeKhFBi-Ff8ek4hCXTYDICXS8ny_BaC5WkyrefHQ2xBqQjwRyoxsg4IoVMjXYNb8L9A-4BNlRfs928SqgFYCRlF5h6zw_rC0XoLrGTmqeacBdpey-r3j2g_lTqWy8mQg2T9s65IDqW3kFPOsr0SVO88sjlFbN9Et0L57RmiqORk_RwzbWg-_Yb6dOuolXsnjBOhOoTzkA"; - if (token) config.headers.Authorization = `Bearer ${token}`; - return config; + if (token) config.headers.Authorization = `Bearer ${token}` + return config }, function (error: any) { - return Promise.reject(error); + return Promise.reject(error) } -); +) http.interceptors.response.use( function (response: AxiosResponse) { - return response; + return response }, function (error: any) { if (typeof error !== undefined) { // eslint-disable-next-line no-prototype-builtins - if (error.hasOwnProperty("response")) { + if (error.hasOwnProperty('response')) { if (error.response.status === 401 || error.response.status === 403) { // Store.commit("SET_ERROR_MESSAGE", error.response.data.message); // Store.commit("REMOVE_ACCESS_TOKEN") } } } - return Promise.reject(error); + return Promise.reject(error) } -); +) -export default http; +export default http diff --git a/src/plugins/keycloak.ts b/src/plugins/keycloak.ts index d2231b6..3865d66 100644 --- a/src/plugins/keycloak.ts +++ b/src/plugins/keycloak.ts @@ -1,25 +1,10 @@ -/** - * front connect to keycloak - */ import Keycloak from 'keycloak-js' -// import config from "../app.config"; -// import http from "../shared/http"; -// import router from "../router"; -const initOptions = { - // realm: import.meta.env.VITE_REALM_KEYCLOAK, - // clientId: import.meta.env.VITE_CLIENTID_KEYCLOAK, - // url: import.meta.env.VITE_URL_KEYCLOAK, +const keycloakConfig = { + url: 'https://id.frappet.synology.me/auth', realm: 'bma-ehr', - clientId: 'bma-ehr-vue3', - url: 'https://id.frappet.synology.me/', -} //option keycloak ที่จะ connect - -const keycloak = new Keycloak(initOptions) - -keycloak.onAuthSuccess = () => { - //เพิ่มlogin สำเร็จจะมาทำฟังก์ชันนี้ + clientId: 'gettoken', } -await keycloak.init({ onLoad: 'check-sso', checkLoginIframe: false }) //ทำการ connect keycloak +const keycloak = new Keycloak(keycloakConfig) export default keycloak diff --git a/src/router/index.ts b/src/router/index.ts index a365210..1b9eb5c 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -9,8 +9,8 @@ const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { - path: "/", - name: "home", + path: '/', + name: 'home', component: MianView, children: [ { @@ -54,9 +54,9 @@ const router = createRouter({ // component: () => import('@/views/SampleCamera.vue'), // }, /** - * 404 Not Found - * ref: https://router.vuejs.org/guide/essentials/dynamic-matching.html#catch-all-404-not-found-route - */ + * 404 Not Found + * ref: https://router.vuejs.org/guide/essentials/dynamic-matching.html#catch-all-404-not-found-route + */ { path: '/:pathMatch(.*)*', name: 'NotFound', @@ -65,32 +65,32 @@ const router = createRouter({ Auth: true, }, }, - ] + ], }, ], }) router.beforeEach((to, from, next) => { if (to.meta.Auth) { - if (!keycloak.authenticated) { - keycloak.login({ - redirectUri: `${window.location.protocol}//${window.location.host}${to.path}`, - locale: 'th', - }) - } else { - // keycloak.updateToken(60); - // const role = keycloak.tokenParsed?.role - // if (role.includes(to.meta.Role)) { - next() - // } else { - // next({ path: '' }) - // // next(); - // } + console.log('keycloak===>', keycloak) + console.log('keycloak authenticated===>', keycloak.authenticated) + + if (keycloak.authenticated === undefined) { + window.location.href = 'https://bma-sso.frappet.synology.me' + // } else { + // // keycloak.updateToken(60); + // // const role = keycloak.tokenParsed?.role + // // if (role.includes(to.meta.Role)) { + // next() + // // } else { + // // next({ path: '' }) + // // // next(); + // // } } } else { next() } - // next(); + next() }) export default router diff --git a/src/views/MianView.vue b/src/views/MianView.vue index f526c47..76fe642 100644 --- a/src/views/MianView.vue +++ b/src/views/MianView.vue @@ -11,13 +11,7 @@ import { useCounterMixin } from '@/stores/mixin' import type { Noti } from '@/interface/response/Main' const mixin = useCounterMixin() -const { - date2Thai, - hideLoader, - messageError, - dialogRemove, - success, -} = mixin +const { date2Thai, hideLoader, messageError, dialogRemove, success } = mixin const router = useRouter() const $q = useQuasar() @@ -27,14 +21,12 @@ const totalNotiList = ref(0) const totalNoti = ref(0) /*** ฟังก์ชั่นดึงข้อมูลจำนวนการแจ้งเตือน */ async function fetchTotolNotificate() { - await http - .get(config.API.msgNotificateTotal) - .then((res) => { - totalNoti.value = res.data.result - }) - // .catch((err) => { - // messageError($q, err) - // }) + await http.get(config.API.msgNotificateTotal).then((res) => { + totalNoti.value = res.data.result + }) + // .catch((err) => { + // messageError($q, err) + // }) } const statusLoad = ref(false) @@ -68,9 +60,9 @@ async function fetchNotifications(index: number, type: string) { notiList.value.push(...list) statusLoad.value = totalNotiList.value === 0 ? true : false }) - // .catch((err) => { - // messageError($q, err) - // }) + // .catch((err) => { + // messageError($q, err) + // }) } /** @@ -104,11 +96,19 @@ function onClickLogout() { cancel: 'ยกเลิก', ok: 'ยืนยัน', persistent: true, - }).onOk(() => { - keycloak.logout() + }).onOk(async () => { + // keycloak.logout() + await deleteCookie('BMAHRIS_KEYCLOAK_IDENTITY') + await deleteCookie('BMAHRIS_KEYCLOAK_REFRESH') + // window.location.href = 'https://bma-sso.frappet.synology.me' + window.location.href = 'http://localhost:3020' }) } +function deleteCookie(name) { + document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;` +} + const thaiOptions: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit', @@ -117,8 +117,8 @@ const thaiOptions: Intl.DateTimeFormatOptions = { const page = ref(0) /** * โหลดรายการแจ้งเตือนเพิ่มเมื่อ scroll - * @param index - * @param done + * @param index + * @param done */ function onLoad(index: any, done: any) { if (