import { getSelectedProfile } from '@/api/profile' import { useAuthStore } from '@/stores/auth-store' import { createRouter, createWebHistory, type RouteLocationNormalized } from 'vue-router' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/login', component: () => import('@/pages/LoginPage.vue'), meta: { title: 'Login' }, }, { path: '/', component: () => import('@/pages/UserAccountLayout.vue'), beforeEnter: onlyAuthenticated, children: [ { path: '', redirect: '/profiles', }, { path: 'me', component: () => import('@/pages/MyUserPage.vue'), meta: { title: 'My User' }, }, { path: 'profiles', component: () => import('@/pages/ProfilesPage.vue'), meta: { title: 'Profiles' }, }, { path: 'profiles/:profileName', children: [ { path: '', component: () => import('@/pages/UserHomePage.vue'), meta: { title: (to: RouteLocationNormalized) => 'Profile ' + getSelectedProfile(to) }, }, { path: 'accounts/:id', component: () => import('@/pages/AccountPage.vue'), meta: { title: 'Account' }, }, { path: 'accounts/:id/edit', component: () => import('@/pages/forms/EditAccountPage.vue'), meta: { title: 'Edit Account' }, }, { path: 'add-account', component: () => import('@/pages/forms/EditAccountPage.vue'), meta: { title: 'Add Account' }, }, { path: 'transactions/:id', component: () => import('@/pages/TransactionPage.vue'), meta: { title: 'Transaction' }, }, { path: 'transactions/:id/edit', component: () => import('@/pages/forms/EditTransactionPage.vue'), meta: { title: 'Edit Transaction' }, }, { path: 'add-transaction', component: () => import('@/pages/forms/EditTransactionPage.vue'), meta: { title: 'Add Transaction' }, }, { path: 'vendors', component: () => import('@/pages/VendorsPage.vue'), meta: { title: 'Vendors' }, }, { path: 'categories', component: () => import('@/pages/CategoriesPage.vue'), meta: { title: 'Categories' }, }, ], }, ], }, ], }) // Adds a webpage title to each route based on the "meta.title" attribute. router.beforeEach((to, _, next) => { if (to.meta.title !== undefined && typeof to.meta.title === 'string') { document.title = 'Finnow - ' + to.meta.title } else if (to.meta.title !== undefined && typeof to.meta.title === 'function') { document.title = 'Finnow - ' + to.meta.title(to) } else { document.title = 'Finnow' } if (import.meta.env.DEV) { document.title = '[DEV]' + document.title } next() }) /** * Guard to ensure a route can only be accessed by authenticated users. * @param to The route to guard. * @returns True if the user is authenticated, or a redirect to the `/login` * page if the user isn't logged in. */ function onlyAuthenticated(to: RouteLocationNormalized) { const authStore = useAuthStore() if (authStore.state) return true if (to.path === '/') return '/login' return '/login?next=' + encodeURIComponent(to.path) } export default router