feature: refresh token. if not logged in then refresh token; else redirect to login page.

This commit is contained in:
Cindy Chang
2024-06-28 12:10:19 +08:00
parent 9b2bab9124
commit a4aab21b98
5 changed files with 84 additions and 50 deletions

View File

@@ -33,9 +33,11 @@ export default {
const allMapDataStore = AllMapDataStore();
const conformanceStore = ConformanceStore();
const pageAdminStore = PageAdminStore();
const loginStore = LoginStore();
const { tempFilterId, createFilterId, temporaryData, postRuleData, ruleData } = storeToRefs(allMapDataStore);
const { conformanceLogTempCheckId, conformanceFilterTempCheckId } = storeToRefs(conformanceStore);
const router = useRouter();
const { isLoggedIn, auth } = storeToRefs(loginStore);
const setHighlightedNavItemOnLanding = () => {
const currentPath = router.currentRoute.value.path;
@@ -72,6 +74,7 @@ export default {
]),
...mapState(LoginStore, [
'isLoggedIn',
'auth',
])
},
methods: {
@@ -81,23 +84,46 @@ export default {
'clearShouldKeepPreviousPageBoolean',
'setActivePageComputedByRoute',
],),
...mapActions(LoginStore, [
'refreshToken',
],),
},
created() {
// Save token in Headers.
const token = document.cookie.replace(/(?:(?:^|.*;\s*)luciaToken\s*\=\s*([^;]*).*$)|^.*$/, "$1");
this.$http.defaults.headers.common['Authorization'] = `Bearer ${token}`;
},
beforeRouteEnter(to, from, next) {
// 重新整理畫面以及第一次進入網頁時beforeRouteEnter這個hook會被執行然而beforeRouteUpdate不會被執行
if (!getCookie("isLuciaLoggedIn")) {
next({
path: '/login',
query: {
'return-to': btoa(window.location.href),
}
});
} else {
next();
// 重新整理畫面以及第一次進入網頁時beforeRouteEnter這個hook會被執行然而beforeRouteUpdate不會被執行
// PSEUDOCODE
// if (not logged in) {
// if (has refresh token) {
// refresh_token();
// if (refresh failed) {
// go to log in();
// } else {
// cookie add("refresh_token=" + refresh_token "; expire=****")
// }
// } else {
// go to log in();
// }
// }
beforeRouteEnter(to, from, next) {
const loginStore = LoginStore();
if (!loginStore.isLoggedIn) {
if (getCookie('luciaRefreshToken')) {
loginStore.refreshToken();
} else {
next({
path: '/login',
query: {
// 記憶未來登入後要進入的網址且記憶的時候要用base64編碼包裹住
'return-to': btoa(window.location.href),
}
});
}
} else {
next();
}
},
// Remember, Swal modal handling is called before beforeRouteUpdate