update auth

This commit is contained in:
DESKTOP-1R2VSQH\Lenovo ThinkPad E490 2024-08-28 13:43:21 +07:00
parent 23afdc4df9
commit ff3fb68219
12 changed files with 222 additions and 308 deletions

4
.env Normal file
View file

@ -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"

View file

@ -3,7 +3,7 @@ import App from '@/App.vue'
import '@/registerServiceWorker' import '@/registerServiceWorker'
import router from '@/router' import router from '@/router'
import { createPinia } from 'pinia' import { createPinia } from 'pinia'
import keycloak, { getToken } from '@/plugins/keycloak' // import keycloak, { getToken } from '@/plugins/keycloak'
import { Quasar, Dialog, Notify, Loading } from 'quasar' import { Quasar, Dialog, Notify, Loading } from 'quasar'
import '@vuepic/vue-datepicker/dist/main.css' import '@vuepic/vue-datepicker/dist/main.css'
@ -37,38 +37,38 @@ app.component(
app.config.globalProperties.$http = http app.config.globalProperties.$http = http
// authen with keycloak client // // authen with keycloak client
function getCookie(name: string) { // function getCookie(name: string) {
const nameEQ = name + '=' // const nameEQ = name + '='
const ca = document.cookie.split(';') // const ca = document.cookie.split(';')
for (let i = 0; i < ca.length; i++) { // for (let i = 0; i < ca.length; i++) {
let c = ca[i] // let c = ca[i]
while (c.charAt(0) == ' ') c = c.substring(1, c.length) // while (c.charAt(0) == ' ') c = c.substring(1, c.length)
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length) // if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length)
} // }
return null // return null
} // }
const auth = await getToken() // const auth = await getToken()
if (auth.token && auth.refresh_token) { // if (auth.token && auth.refresh_token) {
keycloak.init({ // keycloak.init({
checkLoginIframe: false, // checkLoginIframe: false,
token: auth.token, // token: auth.token,
refreshToken: auth.refresh_token, // refreshToken: auth.refresh_token,
}) // })
// .then((authenticated) => { // // .then((authenticated) => {
// console.log('authenticated', authenticated) // // console.log('authenticated', authenticated)
// if (!authenticated) { // // if (!authenticated) {
// window.location.reload() // // window.location.reload()
// } else { // // } else {
// console.log('Authenticated') // // console.log('Authenticated')
// } // // }
// }) // // })
// .catch((err) => { // // .catch((err) => {
// console.error('Keycloak initialization failed:', err) // // console.error('Keycloak initialization failed:', err)
// }) // // })
} // }
app.mount('#app') app.mount('#app')

71
src/plugins/auth.ts Normal file
View file

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

View file

@ -2,7 +2,8 @@ import axios from 'axios'
import config from 'process' import config from 'process'
// import { dotnetPath } from "../path/axiosPath"; // import { dotnetPath } from "../path/axiosPath";
// import { getToken } from "@baloise/vue-keycloak"; // import { getToken } from "@baloise/vue-keycloak";
import keycloak from '@/plugins/keycloak' // import keycloak from '@/plugins/keycloak'
import { getToken } from './auth'
const axiosInstance = axios.create({ const axiosInstance = axios.create({
withCredentials: false, withCredentials: false,
@ -11,7 +12,7 @@ const axiosInstance = axios.create({
// axiosInstance.defaults.baseURL = dotnetPath; // axiosInstance.defaults.baseURL = dotnetPath;
axiosInstance.interceptors.request.use( axiosInstance.interceptors.request.use(
async (config) => { async (config) => {
const token = await keycloak.token const token = await getToken()
config.headers = { config.headers = {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
} }

View file

@ -1,5 +1,5 @@
import Axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios' import Axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios'
import keycloak from './keycloak' import { getToken } from './auth'
const http = Axios.create({ const http = Axios.create({
timeout: 1000000000, // เพิ่มค่า timeout timeout: 1000000000, // เพิ่มค่า timeout
@ -10,10 +10,9 @@ const http = Axios.create({
http.interceptors.request.use( http.interceptors.request.use(
async function (config: AxiosRequestConfig<any>) { async function (config: AxiosRequestConfig<any>) {
// await keycloak.updateToken(1)
config.headers = config.headers ?? {} config.headers = config.headers ?? {}
const token = keycloak.token const token = await getToken()
// const token = localStorage.getItem("access_token")
if (token) config.headers.Authorization = `Bearer ${token}` if (token) config.headers.Authorization = `Bearer ${token}`
return config return config
}, },

View file

@ -1,70 +1,70 @@
// authen with keycloak client // // authen with keycloak client
import Keycloak from 'keycloak-js' // import Keycloak from 'keycloak-js'
const ACCESS_TOKEN = 'BMAHRIS_KEYCLOAK_IDENTITY' // const ACCESS_TOKEN = 'BMAHRIS_KEYCLOAK_IDENTITY'
const REFRESH_TOKEN = 'BMAHRIS_KEYCLOAK_REFRESH' // const REFRESH_TOKEN = 'BMAHRIS_KEYCLOAK_REFRESH'
const keycloakConfig = { // const keycloakConfig = {
url: import.meta.env.VITE_URL_KEYCLOAK, // url: import.meta.env.VITE_URL_KEYCLOAK,
realm: import.meta.env.VITE_REALM_KEYCLOAK, // realm: import.meta.env.VITE_REALM_KEYCLOAK,
clientId: import.meta.env.VITE_CLIENTID_KEYCLOAK, // clientId: import.meta.env.VITE_CLIENTID_KEYCLOAK,
clientSecret: import.meta.env.VITE_CLIENTSECRET_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) { // async function kcAuthen(access_token: string, refresh_token: string) {
await setCookie(ACCESS_TOKEN, access_token, 1) // await setCookie(ACCESS_TOKEN, access_token, 1)
await setCookie(REFRESH_TOKEN, refresh_token, 1) // await setCookie(REFRESH_TOKEN, refresh_token, 1)
window.location.href = '/' // window.location.href = '/'
} // }
async function kcLogout() { // async function kcLogout() {
await deleteCookie(ACCESS_TOKEN) // await deleteCookie(ACCESS_TOKEN)
await deleteCookie(REFRESH_TOKEN) // await deleteCookie(REFRESH_TOKEN)
if (keycloak.authenticated !== undefined) { // if (keycloak.authenticated !== undefined) {
keycloak.logout() // keycloak.logout()
} // }
window.location.href = '/login' // window.location.href = '/login'
} // }
async function getToken() { // async function getToken() {
return { // return {
token: getCookie(ACCESS_TOKEN), // token: getCookie(ACCESS_TOKEN),
refresh_token: getCookie(REFRESH_TOKEN), // refresh_token: getCookie(REFRESH_TOKEN),
} // }
} // }
function setCookie(name: string, value: any, days: number) { // function setCookie(name: string, value: any, days: number) {
let expires = '' // let expires = ''
if (days) { // if (days) {
const date = new Date() // const date = new Date()
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000) // date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)
expires = '; expires=' + date.toUTCString() // expires = '; expires=' + date.toUTCString()
} // }
document.cookie = name + '=' + (value || '') + expires + '; path=/' // document.cookie = name + '=' + (value || '') + expires + '; path=/'
} // }
function getCookie(name: string) { // function getCookie(name: string) {
const nameEQ = name + '=' // const nameEQ = name + '='
const ca = document.cookie.split(';') // const ca = document.cookie.split(';')
for (let i = 0; i < ca.length; i++) { // for (let i = 0; i < ca.length; i++) {
let c = ca[i] // let c = ca[i]
while (c.charAt(0) == ' ') c = c.substring(1, c.length) // while (c.charAt(0) == ' ') c = c.substring(1, c.length)
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length) // if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length)
} // }
return null // return null
} // }
function deleteCookie(name: string) { // function deleteCookie(name: string) {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;` // document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`
} // }
export default keycloak // export default keycloak
export { // export {
keycloakConfig, // keycloakConfig,
getToken, // getToken,
kcAuthen, // kcAuthen,
kcLogout, // kcLogout,
ACCESS_TOKEN, // ACCESS_TOKEN,
REFRESH_TOKEN, // REFRESH_TOKEN,
} // }

View file

@ -4,7 +4,7 @@ import MapView from '@/views/MapView.vue'
import MainView from '@/views/MainView.vue' import MainView from '@/views/MainView.vue'
const loginView = () => import('@/views/login.vue') const loginView = () => import('@/views/login.vue')
import keycloak, { kcLogout } from '@/plugins/keycloak' import { authenticated, logout } from '@/plugins/auth'
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
@ -82,12 +82,9 @@ const router = createRouter({
// authen with keycloak client // authen with keycloak client
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
// console.log('keycloak==>', keycloak)
console.log('keycloak==>', keycloak.authenticated)
if (to.meta.Auth) { if (to.meta.Auth) {
if (keycloak.authenticated === undefined && to.meta.Auth) { if (authenticated === undefined && to.meta.Auth) {
kcLogout() logout()
} }
} else { } else {
next() next()

View file

@ -1,7 +1,7 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import CustomComponent from '@/components/CustomDialog.vue' import CustomComponent from '@/components/CustomDialog.vue'
import { Loading, QSpinnerCube } from 'quasar' import { Loading, QSpinnerCube } from 'quasar'
import { kcLogout } from '@/plugins/keycloak' import { logout } from '@/plugins/auth'
export const useCounterMixin = defineStore('mixin', () => { export const useCounterMixin = defineStore('mixin', () => {
function date2Thai(srcDate: Date, isFullMonth = false, isTime = false) { function date2Thai(srcDate: Date, isFullMonth = false, isTime = false) {
@ -146,7 +146,7 @@ export const useCounterMixin = defineStore('mixin', () => {
}, },
}).onCancel(async () => { }).onCancel(async () => {
showLoader() showLoader()
await kcLogout() await logout()
setTimeout(() => { setTimeout(() => {
hideLoader() hideLoader()
}, 1000) }, 1000)
@ -178,7 +178,7 @@ export const useCounterMixin = defineStore('mixin', () => {
}, },
}).onCancel(async () => { }).onCancel(async () => {
showLoader() showLoader()
await kcLogout() await logout()
setTimeout(() => { setTimeout(() => {
hideLoader() hideLoader()
}, 1000) }, 1000)
@ -196,7 +196,7 @@ export const useCounterMixin = defineStore('mixin', () => {
}, },
}).onCancel(async () => { }).onCancel(async () => {
showLoader() showLoader()
await kcLogout() await logout()
setTimeout(() => { setTimeout(() => {
hideLoader() hideLoader()
}, 1000) }, 1000)

View file

@ -2,9 +2,9 @@
import { ref, onMounted, watch } from 'vue' import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { useQuasar } from 'quasar' import { useQuasar } from 'quasar'
import keycloak, { kcLogout } from '@/plugins/keycloak'
import http from '@/plugins/http' import http from '@/plugins/http'
import config from '@/app.config' import config from '@/app.config'
import { logout, tokenParsed } from '@/plugins/auth'
import type { notiType } from '@/interface/index/Main' import type { notiType } from '@/interface/index/Main'
import { useCounterMixin } from '@/stores/mixin' import { useCounterMixin } from '@/stores/mixin'
@ -46,22 +46,20 @@ async function fetchNotifications(index: number, type: string) {
notiList.value = [] notiList.value = []
} }
if (response.length === 0) { response.map((e: Noti) => {
response.map((e: Noti) => { list.push({
list.push({ id: e.id,
id: e.id, sender:
sender: e.createdFullName == '' || e.createdFullName == null
e.createdFullName == '' || e.createdFullName == null ? 'เจ้าหน้าที่'[0]
? 'เจ้าหน้าที่'[0] : e.createdFullName[0],
: e.createdFullName[0], body: e.body ?? '',
body: e.body ?? '', timereceive: e.receiveDate,
timereceive: e.receiveDate, isOpen: e.isOpen,
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) => { // .catch((err) => {
// messageError($q, err) // messageError($q, err)
@ -100,7 +98,7 @@ function onClickLogout() {
ok: 'ยืนยัน', ok: 'ยืนยัน',
persistent: true, persistent: true,
}).onOk(async () => { }).onOk(async () => {
kcLogout() logout()
}) })
} }
@ -145,8 +143,9 @@ watch(
const fullName = ref<string>('') const fullName = ref<string>('')
onMounted(async () => { onMounted(async () => {
fetchTotolNotificate() fetchTotolNotificate()
if (keycloak.tokenParsed != null) { const checkTokenParsed = await tokenParsed()
fullName.value = keycloak.tokenParsed.name if (checkTokenParsed != null) {
fullName.value = checkTokenParsed.name
} }
}) })
</script> </script>

View file

@ -6,7 +6,7 @@ import moment from 'moment'
import Camera from 'simple-vue-camera' import Camera from 'simple-vue-camera'
import http from '@/plugins/http' import http from '@/plugins/http'
import config from '@/app.config' import config from '@/app.config'
import keycloak from '@/plugins/keycloak' import { tokenParsed } from '@/plugins/auth'
// import Type // import Type
import type { FormRef } from '@/interface/response/checkin' import type { FormRef } from '@/interface/response/checkin'
@ -52,58 +52,6 @@ async function fetchCheckTime() {
}) })
} }
const notiTrigger = ref<boolean>(false)
const notiList = ref<notiType[]>([])
/** 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 อัพเดทเวลา*/ /** ref อัพเดทเวลา*/
const dateNow = ref<Date>(new Date()) const dateNow = ref<Date>(new Date())
const Thai = ref<Date>(dateNow.value) const Thai = ref<Date>(dateNow.value)
@ -302,9 +250,9 @@ const fullName = ref<string>('')
/** Hook*/ /** Hook*/
onMounted(async () => { onMounted(async () => {
await fetchCheckTime() await fetchCheckTime()
await fetchNotifications() const checkToken = await tokenParsed()
if (keycloak.tokenParsed != null) { if (checkToken != null) {
fullName.value = keycloak.tokenParsed.name fullName.value = checkToken.name
} }
updateClock() updateClock()
@ -317,113 +265,12 @@ onMounted(async () => {
<q-card flat class="row col-12 cardNone"> <q-card flat class="row col-12 cardNone">
<div :class="getClass(stetusCheckin)"> <div :class="getClass(stetusCheckin)">
<q-toolbar class="text-primary"> <q-toolbar class="text-primary">
<!-- <q-btn
icon="history"
unelevated
rounded
dense
flat
color="white"
:label="$q.screen.gt.xs ? 'ประวัติการลงเวลา' : ''"
:class="$q.screen.gt.xs ? 'q-px-md' : ''"
@click="router.push('/history')"
/> -->
<q-toolbar-title> <q-toolbar-title>
<span class="text-white text-body1 text-weight-bold text-center"> <span class="text-white text-body1 text-weight-bold text-center">
<span v-if="stetusCheckin">ลงเวลาเข้างาน</span> <span v-if="stetusCheckin">ลงเวลาเข้างาน</span>
<span v-else>ลงเวลาออกงาน</span> <span v-else>ลงเวลาออกงาน</span>
</span> </span>
</q-toolbar-title> </q-toolbar-title>
<!-- <q-btn
round
dense
flat
size="13px"
class="q-mx-md"
:disable="notiList.length === 0"
>
<q-icon name="notifications" size="24px" color="white" />
<q-badge
rounded
v-show="notiList.length > 0"
color="negative"
text-color="white"
floating
>{{ notiList.length }}</q-badge
>
<q-menu v-model="notiTrigger" max-width="480px" :offset="[0, 10]">
<div class="q-px-md q-py-sm row col-12 items-center">
<div class="text-subtitle1 text-weight-medium">
การแจงเตอน
</div>
</div>
<q-list
style="min-width: 300px"
v-for="n in notiList"
:key="n.id"
>
<q-item v-ripple class="mytry q-py-xs" dense>
<q-item-section avatar top style="min-width: 40px">
<q-avatar color="primary" size="22px" text-color="white">
<span class="text-weight-medium text-uppercase">{{
n.sender
}}</span>
</q-avatar>
</q-item-section>
<q-item-section>
<q-item-label caption class="text-black">{{
n.body
}}</q-item-label>
<q-item-label
caption
class="row items-center text-grey-7"
>{{ date2Thai(n.timereceive) }}</q-item-label
>
</q-item-section>
<q-btn
size="sm"
unelevated
dense
icon="mdi-close"
class="mybtn q-mx-xs"
@click="onClickDelete(n.id)"
></q-btn>
</q-item>
<q-separator color="grey-2" />
</q-list>
</q-menu>
</q-btn> -->
<!-- <q-btn round dense flat size="13px" class="q-mx-md">
<q-icon name="account_circle" size="24px" color="white" />
<q-menu>
<div class="q-pa-md" style="max-width: 500px">
<q-list>
<q-item>
<q-item-section avatar>
<q-icon color="primary" name="account_circle" />
</q-item-section>
<q-item-section>{{ fullName }}</q-item-section>
</q-item>
<q-item class="text-center">
<q-item-section>
<q-item-label>
<q-btn
color="primary"
label="ออกจากระบบ"
push
size="sm"
@click="onClickLogout"
/></q-item-label>
</q-item-section>
</q-item>
</q-list>
</div>
</q-menu>
</q-btn> -->
</q-toolbar> </q-toolbar>
</div> </div>
<div class="col-12 q-pa-md text-grey-9"> <div class="col-12 q-pa-md text-grey-9">
@ -560,7 +407,7 @@ onMounted(async () => {
v-model="model" v-model="model"
:options="options" :options="options"
prefix="ระบุสถานที่ :" prefix="ระบุสถานที่ :"
:rules="[(val) => !!val || 'กรุณาระบุสถานที่']" :rules="[(val:string) => !!val || 'กรุณาระบุสถานที่']"
lazy-rules lazy-rules
@update:model-value="selectLocation()" @update:model-value="selectLocation()"
/> />
@ -576,7 +423,7 @@ onMounted(async () => {
outlined outlined
v-model="useLocation" v-model="useLocation"
label="ระบุสถานที่" label="ระบุสถานที่"
:rules="[(val) => !!val || 'กรุณาระบุสถานที่']" :rules="[(val:string) => !!val || 'กรุณาระบุสถานที่']"
lazy-rules lazy-rules
/> />
</div> </div>

View file

@ -1,15 +1,19 @@
<script setup lang="ts"> <script setup lang="ts">
import { kcAuthen } from '@/plugins/keycloak'
import { onMounted } from 'vue' import { onMounted } from 'vue'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import { setAuthen } from '@/plugins/auth'
const route = useRoute() const route = useRoute()
onMounted(async () => { onMounted(async () => {
if (route.query.token && route.query.accessToken) { if (route.query.token && route.query.accessToken) {
// console.log('query', route.query.token) const params: any = await {
// console.log('accessToken', route.query.accessToken) access_token: route.query.token,
kcAuthen(route.query.token.toString(), route.query.accessToken.toString()) expires_in: route.query.expires ? route.query.expires : 36000,
refresh_token: route.query.accessToken,
}
setAuthen(params)
} }
}) })
</script> </script>

View file

@ -2,10 +2,10 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from 'vue' import { onMounted, ref } from 'vue'
import axios from 'axios' import axios from 'axios'
import keycloak, { kcAuthen, keycloakConfig } from '@/plugins/keycloak'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { useQuasar } from 'quasar' import { useQuasar } from 'quasar'
import { useCounterMixin } from '@/stores/mixin' import { useCounterMixin } from '@/stores/mixin'
import { setAuthen, authenticated } from '@/plugins/auth'
const router = useRouter() const router = useRouter()
const mixin = useCounterMixin() const mixin = useCounterMixin()
@ -18,24 +18,17 @@ const password = ref<string>('')
async function onSubmit() { async function onSubmit() {
showLoader() showLoader()
const formdata = new URLSearchParams() const formdata = new URLSearchParams()
formdata.append('client_id', keycloakConfig.clientId)
formdata.append('client_secret', keycloakConfig.clientSecret)
formdata.append('grant_type', 'password')
formdata.append('username', username.value) formdata.append('username', username.value)
formdata.append('password', password.value) formdata.append('password', password.value)
await axios await axios
.post( .post(`${import.meta.env.VITE_API_URI_CONFIG}/org/login`, formdata, {
`${keycloakConfig.url}/realms/${keycloakConfig.realm}/protocol/openid-connect/token`, headers: {
formdata, 'Content-Type': 'application/x-www-form-urlencoded',
{ },
headers: { })
'Content-Type': 'application/x-www-form-urlencoded',
},
}
)
.then(async (res) => { .then(async (res) => {
kcAuthen(res.data.access_token, res.data.refresh_token) setAuthen(res.data.result)
}) })
.catch((err) => { .catch((err) => {
messageError($q, err, 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง') messageError($q, err, 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง')
@ -45,10 +38,9 @@ async function onSubmit() {
}) })
} }
onMounted(() => { onMounted(async () => {
if (keycloak.authenticated) { const checkAuthen = await authenticated()
console.log('authenticated', keycloak.authenticated) if (checkAuthen) {
router.push('/') router.push('/')
} }
}) })