updateAuthen

This commit is contained in:
DESKTOP-1R2VSQH\Lenovo ThinkPad E490 2024-07-25 12:58:04 +07:00
parent 892b1d507c
commit 7e2350eef8
5 changed files with 99 additions and 57 deletions

View file

@ -98,24 +98,27 @@ const kcToken = getCookie("BMAHRIS_KEYCLOAK_IDENTITY");
const kcRefreshToken = getCookie("BMAHRIS_KEYCLOAK_REFRESH"); const kcRefreshToken = getCookie("BMAHRIS_KEYCLOAK_REFRESH");
if (kcToken && kcRefreshToken) { if (kcToken && kcRefreshToken) {
keycloak keycloak.init({
.init({ // onLoad: 'login-required',
// onLoad: 'login-required', checkLoginIframe: false,
checkLoginIframe: false, token: kcToken,
token: kcToken, refreshToken: kcRefreshToken,
refreshToken: kcRefreshToken, });
}) keycloak.authenticated = true;
.then((authenticated) => {
console.log("authenticated", authenticated); // .then((authenticated) => {
if (!authenticated) { // console.log("authenticated", authenticated);
window.location.reload(); // if (!authenticated) {
} else { // window.location.reload();
console.log("Authenticated"); // } else {
} // console.log("Authenticated");
}) // }
.catch((err) => { // })
console.error("Keycloak initialization failed:", err); // .catch((err) => {
}); // console.error("Keycloak initialization failed:", err);
// });
} else {
keycloak.authenticated = false;
} }
app.mount("#app"); app.mount("#app");

View file

@ -33,6 +33,8 @@ http.interceptors.response.use(
// eslint-disable-next-line no-prototype-builtins // eslint-disable-next-line no-prototype-builtins
if (error.hasOwnProperty("response")) { if (error.hasOwnProperty("response")) {
if (error.response.status === 401 || error.response.status === 403) { if (error.response.status === 401 || error.response.status === 403) {
window.location.href = "/login";
// Store.commit("SET_ERROR_MESSAGE", error.response.data.message); // Store.commit("SET_ERROR_MESSAGE", error.response.data.message);
// Store.commit("REMOVE_ACCESS_TOKEN") // Store.commit("REMOVE_ACCESS_TOKEN")
} }

View file

@ -108,7 +108,7 @@ const router = createRouter({
// authen with keycloak client // authen with keycloak client
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
if (to.meta.Auth) { if (to.meta.Auth) {
if (keycloak.authenticated === undefined && to.meta.Auth) { if (keycloak.authenticated === false && to.meta.Auth) {
window.location.href = "/login"; window.location.href = "/login";
} }
} else { } else {

30
src/views/auth.vue Normal file
View file

@ -0,0 +1,30 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
function setCookie(name: string, value: any, days: number) {
let expires = ''
if (days) {
const date = new Date()
date.setTime(date.getTime() + days * 24 * 60 * 55 * 1000)
expires = '; expires=' + date.toUTCString()
}
document.cookie = name + '=' + (value || '') + expires + '; path=/'
}
onMounted(async () => {
console.log('query', route.query.token)
console.log('accessToken', route.query.accessToken)
setCookie('BMAHRIS_KEYCLOAK_IDENTITY', route.query.token, 1)
setCookie('BMAHRIS_KEYCLOAK_REFRESH', route.query.accessToken, 1)
window.location.href = '/'
})
</script>
<template>
<div></div>
</template>

View file

@ -1,42 +1,42 @@
<!-- authen with keycloak client --> <!-- authen with keycloak client -->
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { ref, onMounted } from "vue";
import axios from 'axios' import axios from "axios";
import { keycloakConfig } from '@/plugins/keycloak' import keycloak, { 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";
const router = useRouter() const router = useRouter();
const mixin = useCounterMixin() const mixin = useCounterMixin();
const $q = useQuasar() // noti quasar const $q = useQuasar(); // noti quasar
const { showLoader, hideLoader, messageError } = mixin const { showLoader, hideLoader, messageError } = mixin;
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=/";
} }
const username = ref<string>('') const username = ref<string>("");
const password = ref<string>('') 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_id", keycloakConfig.clientId);
formdata.append('client_secret', keycloakConfig.clientSecret) formdata.append("client_secret", keycloakConfig.clientSecret);
formdata.append('grant_type', 'password') formdata.append("grant_type", "password");
formdata.append( formdata.append(
'requested_token_type', "requested_token_type",
'urn:ietf:params:oauth:token-type:refresh_token' "urn:ietf:params:oauth:token-type:refresh_token"
) );
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(
@ -44,21 +44,21 @@ async function onSubmit() {
formdata, formdata,
{ {
headers: { headers: {
'Content-Type': 'application/x-www-form-urlencoded', "Content-Type": "application/x-www-form-urlencoded",
}, },
} }
) )
.then(async (res) => { .then(async (res) => {
await setCookie('BMAHRIS_KEYCLOAK_IDENTITY', res.data.access_token, 1) await setCookie("BMAHRIS_KEYCLOAK_IDENTITY", res.data.access_token, 1);
await setCookie('BMAHRIS_KEYCLOAK_REFRESH', res.data.refresh_token, 1) await setCookie("BMAHRIS_KEYCLOAK_REFRESH", res.data.refresh_token, 1);
window.location.href = '/' window.location.href = "/";
}) })
.catch((err) => { .catch((err) => {
messageError($q, err, 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง') messageError($q, err, "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง");
}) })
.finally(() => { .finally(() => {
hideLoader() hideLoader();
}) });
// if (response.status !== 200) { // if (response.status !== 200) {
// messageError($q, err) // messageError($q, err)
@ -68,6 +68,13 @@ async function onSubmit() {
// router.push('/') // router.push('/')
// } // }
} }
onMounted(() => {
if (keycloak.authenticated) {
console.log("authenticated", keycloak.authenticated);
router.push("/");
}
});
</script> </script>
<template> <template>
@ -184,8 +191,8 @@ async function onSubmit() {
margin-bottom: 10px; margin-bottom: 10px;
} }
input[type='checkbox'], input[type="checkbox"],
input[type='radio'] { input[type="radio"] {
margin: 1px 3px 0 0; margin: 1px 3px 0 0;
line-height: normal; line-height: normal;
} }
@ -218,8 +225,8 @@ input[type='radio'] {
z-index: 1 !important; z-index: 1 !important;
} }
.bg-image { .bg-image {
font-family: 'Noto Sans Thai', sans-serif; font-family: "Noto Sans Thai", sans-serif;
font-family: 'Noto Sans Thai', sans-serif; font-family: "Noto Sans Thai", sans-serif;
text-rendering: optimizeLegibility; text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;