Issue #140: Done.

This commit is contained in:
chiayin
2023-10-13 17:58:47 +08:00
parent 1cfbddf510
commit cf3d799ed7
4 changed files with 191 additions and 39 deletions

View File

@@ -11,7 +11,7 @@ import NotFound404 from '@/views/NotFound404.vue';
const routes = [
{
path: '/', // 預設進入路由
redirect: '/files' //重定向
redirect: '/files', //重定向
},
{
path: '/',
@@ -29,6 +29,10 @@ const routes = [
path: "/",
name: "MainContainer",
component: MainContainer,
meta: {
title: "MainContainer",
requiresAuth: true
},
children: [
{
path: "/member-area",
@@ -65,13 +69,10 @@ const routes = [
},
];
const base_url = import.meta.env.BASE_URL;
const router = createRouter({
history: createWebHistory(base_url), //(/)
// history: createWebHashHistory(base_url), // (/#)
routes
});
@@ -79,15 +80,13 @@ const router = createRouter({
router.beforeEach((to, from) => {
// to: Route: 即將要進入的目標 路由物件
// from: Route: 當前導航正要離開的路由
const nextRoute = ['MemberArea', 'Files'];
let isCookie = document.cookie.split(';').some(c => c.trim().startsWith('luciaToken=')); // 是否登入
// 未登入狀態當路由到nextRoute指定頁時跳轉至login
if (nextRoute.indexOf(to.name) >= 0) {
if (!isCookie) router.push({ name: 'Login' });
// 需要驗證登入的頁面,判斷有無登入,無登入要轉址 login
if(to.meta.requiresAuth) {
if (!isCookie) router.push({ name: 'Login' });
}
// 已登入狀態;當路由到login時跳轉至home
// 當路由到 login 時,有登入要跳轉至home
if (to.name === 'Login') {
if (isCookie) router.push({ name: 'Files' });
}

View File

@@ -36,8 +36,15 @@ export default defineStore('loginStore', {
if(response.status === 200){
// 將 token 儲存在 cookie
const token = response.data.access_token;
// 取得當前日期
const currentDate = new Date();
// 設定 cookie 的過期日期為一天後
const expirationDate = new Date();
expirationDate.setDate(currentDate.getDate() + 1);
// 格式化過期日期為 Cookie 格式
const expires = expirationDate.toUTCString();
document.cookie = `luciaToken=${token}`;
document.cookie = `luciaToken=${token}; expires=${expires};`;
this.$router.push('/files');
}
} catch(error) {
@@ -53,10 +60,8 @@ export default defineStore('loginStore', {
let expires = new Date();
expires.setTime(expires.getTime() - 60000);
if(isCookie){
document.cookie = `luciaToken=; expires=${expires.toGMTString()}`;
if(isCookie) document.cookie = `luciaToken=; expires=${expires.toGMTString()}`;
this.$router.push('/login');
}
},
/**
* get user detail for 'my-account' api

View File

@@ -50,14 +50,11 @@ export default {
leaveFilter
},
created() {
/**
* Save token in Headers.
*/
// Save token in Headers.
const token = document.cookie.replace(/(?:(?:^|.*;\s*)luciaToken\s*\=\s*([^;]*).*$)|^.*$/, "$1");
this.$http.defaults.headers.common['Authorization'] = `Bearer ${token}`;
/**
* check login for 'my-account' api
*/
// check login for 'my-account' api
this.checkLogin();
},
beforeRouteUpdate(to, from, next) {