diff --git a/.env b/.env new file mode 100644 index 0000000..f254a14 --- /dev/null +++ b/.env @@ -0,0 +1,4 @@ +VITE_API_URI_CONFIG: "https://bma-ehr.frappet.synology.me/api/v1" +VITE_API_PUBLISH_URL: "https://bma-ehr-publish.frappet.synology.me" + + \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index e3aa46f..b6a1b64 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3,7 +3,7 @@ import App from '@/App.vue' import '@/registerServiceWorker' import router from '@/router' import { createPinia } from 'pinia' -import keycloak, { getToken } from '@/plugins/keycloak' +// import keycloak, { getToken } from '@/plugins/keycloak' import { Quasar, Dialog, Notify, Loading } from 'quasar' import '@vuepic/vue-datepicker/dist/main.css' @@ -37,38 +37,38 @@ app.component( app.config.globalProperties.$http = http -// authen with keycloak client -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 -} +// // authen with keycloak client +// 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 auth = await getToken() +// const auth = await getToken() -if (auth.token && auth.refresh_token) { - keycloak.init({ - checkLoginIframe: false, - token: auth.token, - refreshToken: auth.refresh_token, - }) +// if (auth.token && auth.refresh_token) { +// keycloak.init({ +// checkLoginIframe: false, +// token: auth.token, +// refreshToken: auth.refresh_token, +// }) - // .then((authenticated) => { - // console.log('authenticated', authenticated) - // if (!authenticated) { - // window.location.reload() - // } else { - // console.log('Authenticated') - // } - // }) - // .catch((err) => { - // console.error('Keycloak initialization failed:', err) - // }) -} +// // .then((authenticated) => { +// // console.log('authenticated', authenticated) +// // if (!authenticated) { +// // window.location.reload() +// // } else { +// // console.log('Authenticated') +// // } +// // }) +// // .catch((err) => { +// // console.error('Keycloak initialization failed:', err) +// // }) +// } app.mount('#app') diff --git a/src/plugins/auth.ts b/src/plugins/auth.ts new file mode 100644 index 0000000..7d6e7f2 --- /dev/null +++ b/src/plugins/auth.ts @@ -0,0 +1,71 @@ +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 }; diff --git a/src/plugins/axios.ts b/src/plugins/axios.ts index e34aec6..ac858bd 100644 --- a/src/plugins/axios.ts +++ b/src/plugins/axios.ts @@ -2,7 +2,8 @@ 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' +import { getToken } from './auth' const axiosInstance = axios.create({ withCredentials: false, @@ -11,7 +12,7 @@ const axiosInstance = axios.create({ // axiosInstance.defaults.baseURL = dotnetPath; axiosInstance.interceptors.request.use( async (config) => { - const token = await keycloak.token + const token = await getToken() config.headers = { Authorization: `Bearer ${token}`, } diff --git a/src/plugins/http.ts b/src/plugins/http.ts index b82f8c1..9020cb6 100644 --- a/src/plugins/http.ts +++ b/src/plugins/http.ts @@ -1,5 +1,5 @@ import Axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios' -import keycloak from './keycloak' +import { getToken } from './auth' const http = Axios.create({ timeout: 1000000000, // เพิ่มค่า timeout @@ -10,10 +10,9 @@ const http = Axios.create({ http.interceptors.request.use( async function (config: AxiosRequestConfig) { - // await keycloak.updateToken(1) config.headers = config.headers ?? {} - const token = keycloak.token - // const token = localStorage.getItem("access_token") + const token = await getToken() + if (token) config.headers.Authorization = `Bearer ${token}` return config }, diff --git a/src/plugins/keycloak.ts b/src/plugins/keycloak.ts index 088afab..bb382dd 100644 --- a/src/plugins/keycloak.ts +++ b/src/plugins/keycloak.ts @@ -1,70 +1,70 @@ -// authen with keycloak client -import Keycloak from 'keycloak-js' +// // authen with keycloak client +// import Keycloak from 'keycloak-js' -const ACCESS_TOKEN = 'BMAHRIS_KEYCLOAK_IDENTITY' -const REFRESH_TOKEN = 'BMAHRIS_KEYCLOAK_REFRESH' -const keycloakConfig = { - 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, -} +// const ACCESS_TOKEN = 'BMAHRIS_KEYCLOAK_IDENTITY' +// const REFRESH_TOKEN = 'BMAHRIS_KEYCLOAK_REFRESH' +// const keycloakConfig = { +// 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, +// } -const keycloak = new Keycloak(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 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 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), - } -} +// 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 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 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=/;` -} +// function deleteCookie(name: string) { +// document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;` +// } -export default keycloak -export { - keycloakConfig, - getToken, - kcAuthen, - kcLogout, - ACCESS_TOKEN, - REFRESH_TOKEN, -} +// export default keycloak +// export { +// keycloakConfig, +// getToken, +// kcAuthen, +// kcLogout, +// ACCESS_TOKEN, +// REFRESH_TOKEN, +// } diff --git a/src/router/index.ts b/src/router/index.ts index e0915e7..1f40b9a 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -4,7 +4,7 @@ import MapView from '@/views/MapView.vue' import MainView from '@/views/MainView.vue' const loginView = () => import('@/views/login.vue') -import keycloak, { kcLogout } from '@/plugins/keycloak' +import { authenticated, logout } from '@/plugins/auth' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), @@ -82,12 +82,9 @@ const router = createRouter({ // authen with keycloak client router.beforeEach((to, from, next) => { - // console.log('keycloak==>', keycloak) - console.log('keycloak==>', keycloak.authenticated) - if (to.meta.Auth) { - if (keycloak.authenticated === undefined && to.meta.Auth) { - kcLogout() + if (authenticated === undefined && to.meta.Auth) { + logout() } } else { next() diff --git a/src/stores/mixin.ts b/src/stores/mixin.ts index 6516393..8249a7f 100644 --- a/src/stores/mixin.ts +++ b/src/stores/mixin.ts @@ -1,7 +1,7 @@ import { defineStore } from 'pinia' import CustomComponent from '@/components/CustomDialog.vue' import { Loading, QSpinnerCube } from 'quasar' -import { kcLogout } from '@/plugins/keycloak' +import { logout } from '@/plugins/auth' export const useCounterMixin = defineStore('mixin', () => { function date2Thai(srcDate: Date, isFullMonth = false, isTime = false) { @@ -146,7 +146,7 @@ export const useCounterMixin = defineStore('mixin', () => { }, }).onCancel(async () => { showLoader() - await kcLogout() + await logout() setTimeout(() => { hideLoader() }, 1000) @@ -178,7 +178,7 @@ export const useCounterMixin = defineStore('mixin', () => { }, }).onCancel(async () => { showLoader() - await kcLogout() + await logout() setTimeout(() => { hideLoader() }, 1000) @@ -196,7 +196,7 @@ export const useCounterMixin = defineStore('mixin', () => { }, }).onCancel(async () => { showLoader() - await kcLogout() + await logout() setTimeout(() => { hideLoader() }, 1000) diff --git a/src/views/MainView.vue b/src/views/MainView.vue index 7a9acce..0c0871c 100644 --- a/src/views/MainView.vue +++ b/src/views/MainView.vue @@ -2,9 +2,9 @@ import { ref, onMounted, watch } from 'vue' import { useRouter } from 'vue-router' import { useQuasar } from 'quasar' -import keycloak, { kcLogout } from '@/plugins/keycloak' import http from '@/plugins/http' import config from '@/app.config' +import { logout, tokenParsed } from '@/plugins/auth' import type { notiType } from '@/interface/index/Main' import { useCounterMixin } from '@/stores/mixin' @@ -46,22 +46,20 @@ async function fetchNotifications(index: number, type: string) { notiList.value = [] } - if (response.length === 0) { - response.map((e: Noti) => { - list.push({ - id: e.id, - sender: - e.createdFullName == '' || e.createdFullName == null - ? 'เจ้าหน้าที่'[0] - : e.createdFullName[0], - body: e.body ?? '', - timereceive: e.receiveDate, - isOpen: e.isOpen, - }) + response.map((e: Noti) => { + list.push({ + id: e.id, + sender: + e.createdFullName == '' || e.createdFullName == null + ? 'เจ้าหน้าที่'[0] + : e.createdFullName[0], + body: e.body ?? '', + timereceive: e.receiveDate, + isOpen: e.isOpen, }) - notiList.value.push(...list) - statusLoad.value = totalNotiList.value === 0 ? true : false - } + }) + notiList.value.push(...list) + statusLoad.value = totalNotiList.value === 0 ? true : false }) // .catch((err) => { // messageError($q, err) @@ -100,7 +98,7 @@ function onClickLogout() { ok: 'ยืนยัน', persistent: true, }).onOk(async () => { - kcLogout() + logout() }) } @@ -145,8 +143,9 @@ watch( const fullName = ref('') onMounted(async () => { fetchTotolNotificate() - if (keycloak.tokenParsed != null) { - fullName.value = keycloak.tokenParsed.name + const checkTokenParsed = await tokenParsed() + if (checkTokenParsed != null) { + fullName.value = checkTokenParsed.name } }) diff --git a/src/views/MapView.vue b/src/views/MapView.vue index 4491993..6b0beaa 100644 --- a/src/views/MapView.vue +++ b/src/views/MapView.vue @@ -6,7 +6,7 @@ import moment from 'moment' import Camera from 'simple-vue-camera' import http from '@/plugins/http' import config from '@/app.config' -import keycloak from '@/plugins/keycloak' +import { tokenParsed } from '@/plugins/auth' // import Type import type { FormRef } from '@/interface/response/checkin' @@ -52,58 +52,6 @@ async function fetchCheckTime() { }) } -const notiTrigger = ref(false) -const notiList = ref([]) -/** function เรียกข้อมุลแจ้งเตือน */ -async function fetchNotifications() { - showLoader() - await http - .get(config.API.msgNotificate) - .then((res) => { - // const response = res.data.result - // const list: notiType[] = [] - // response.map((e: any) => { - // list.push({ - // id: e.id, - // sender: - // e.createdFullName == '' || e.createdFullName == null - // ? 'เจ้าหน้าที่'[0] - // : e.createdFullName[0], - // body: e.body ?? '', - // timereceive: new Date(e.receiveDate), - // }) - // }) - // notiList.value = list - }) - .catch((err) => { - messageError($q, err) - }) - .finally(() => { - hideLoader() - }) -} - -/** - * function ลบรายการแจ้งเตือน - * @param id noti - */ -async function onClickDelete(id: string) { - dialogRemove($q, async () => { - await http - .delete(config.API.msgId(id)) - .then(() => { - success($q, 'ลบข้อมูลสำเร็จ') - }) - .catch((e) => { - messageError($q, e) - }) - .finally(async () => { - await fetchNotifications() - hideLoader() - }) - }) -} - /** ref อัพเดทเวลา*/ const dateNow = ref(new Date()) const Thai = ref(dateNow.value) @@ -302,9 +250,9 @@ const fullName = ref('') /** Hook*/ onMounted(async () => { await fetchCheckTime() - await fetchNotifications() - if (keycloak.tokenParsed != null) { - fullName.value = keycloak.tokenParsed.name + const checkToken = await tokenParsed() + if (checkToken != null) { + fullName.value = checkToken.name } updateClock() @@ -317,113 +265,12 @@ onMounted(async () => {
- ลงเวลาเข้างาน ลงเวลาออกงาน - -
@@ -560,7 +407,7 @@ onMounted(async () => { v-model="model" :options="options" prefix="ระบุสถานที่ :" - :rules="[(val) => !!val || 'กรุณาระบุสถานที่']" + :rules="[(val:string) => !!val || 'กรุณาระบุสถานที่']" lazy-rules @update:model-value="selectLocation()" /> @@ -576,7 +423,7 @@ onMounted(async () => { outlined v-model="useLocation" label="ระบุสถานที่" - :rules="[(val) => !!val || 'กรุณาระบุสถานที่']" + :rules="[(val:string) => !!val || 'กรุณาระบุสถานที่']" lazy-rules />
diff --git a/src/views/auth.vue b/src/views/auth.vue index 7fc0568..4412823 100644 --- a/src/views/auth.vue +++ b/src/views/auth.vue @@ -1,15 +1,19 @@ diff --git a/src/views/login.vue b/src/views/login.vue index 9d0771d..fd3ed4c 100644 --- a/src/views/login.vue +++ b/src/views/login.vue @@ -2,10 +2,10 @@