diff --git a/src/router/index.ts b/src/router/index.ts index 95f6ef6..474be5e 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -162,12 +162,12 @@ const router = createRouter({ router.beforeEach((to, from) => { // to: Route: 即將要進入的目標 路由物件 // from: Route: 當前導航正要離開的路由 - let isRemoveCookie = document.cookie.split(';').some(c => c.trim().startsWith('expires=Thu, 01 Jan 1970 00:00:00 UTC;')); // 是否登入,有到期日表示已登出。 - // 當路由到 login 時,有登入要跳轉至home + // 當路由到 login 時,已登入則跳轉至 Files if (to.name === 'Login') { - if (isRemoveCookie) router.push({ name: 'Files' }); + const isLoggedIn = document.cookie.split(';').some(c => c.trim().startsWith('isLuciaLoggedIn=')); + if (isLoggedIn) return { name: 'Files' }; } - }); +}); export default router; diff --git a/tests/router/routerGuard.test.js b/tests/router/routerGuard.test.js new file mode 100644 index 0000000..aa2b255 --- /dev/null +++ b/tests/router/routerGuard.test.js @@ -0,0 +1,39 @@ +import { describe, it, expect, beforeEach } from 'vitest'; + +describe('router beforeEach guard logic', () => { + beforeEach(() => { + // Clear cookies + document.cookie.split(';').forEach((c) => { + const name = c.split('=')[0].trim(); + if (name) { + document.cookie = name + '=; Max-Age=-99999999; path=/'; + } + }); + }); + + // Simulate the guard logic from router/index.ts + function runGuard(to) { + const isLoggedIn = document.cookie + .split(';') + .some((c) => c.trim().startsWith('isLuciaLoggedIn=')); + + if (to.name === 'Login') { + if (isLoggedIn) return { name: 'Files' }; + } + return undefined; + } + + it('redirects logged-in user from Login to Files', () => { + document.cookie = 'isLuciaLoggedIn=true'; + expect(runGuard({ name: 'Login' })).toEqual({ name: 'Files' }); + }); + + it('allows unauthenticated user to visit Login', () => { + expect(runGuard({ name: 'Login' })).toBeUndefined(); + }); + + it('does not interfere with non-Login routes', () => { + document.cookie = 'isLuciaLoggedIn=true'; + expect(runGuard({ name: 'Files' })).toBeUndefined(); + }); +});