import { createRouter, createWebHistory } from 'vue-router' import { store } from '@/store.js' import { LoginView, SubscriptionsView, EpisodesView, ForgotPasswordView, SettingsView, RegistrationView, ResetPasswordView } from '@/views' import { useLogger } from '@/logger.js' const logger = useLogger(); const routes = [ { path: '/', redirect: to => { return store.isLoggedIn ? '/subscriptions' : '/login'; }, meta: { requiresAuth: false }, }, { path: '/login', name: 'Login', component: LoginView, meta: { requiresAuth: false }, }, { path: '/forgotPassword', name: 'ForgotPassword', component: ForgotPasswordView, meta: { requiresAuth: false }, }, { path: '/registration', name: 'Registration', component: RegistrationView, meta: { requiresAuth: false }, }, { path: '/resetPassword', name: 'ResetPassword', component: ResetPasswordView, props: router => ({ token: router.query.token, username: router.query.username }), meta: { requiresAuth: false }, }, { path: '/subscriptions', name: 'Subscriptions', component: SubscriptionsView, meta: { requiresAuth: true } }, { path: '/episodes', name: 'Episodes', component: EpisodesView, meta: { requiresAuth: true } }, { path: '/settings', name: 'Settings', component: SettingsView, meta: { requiresAuth: true } }, { path: '/:pathMatch(.*)*', name: 'NotFound', redirect: to => { logger.pageNotFound(); return "/"; }, meta: { requiresAuth: false }, } ] const baseURL = import.meta.env.BASE_URL || "/"; console.log("Base-URL", baseURL); const router = createRouter({ history: createWebHistory(baseURL), routes }) router.beforeEach((to, from, next) => { // instead of having to check every route record with // to.matched.some(record => record.meta.requiresAuth) if (to.meta.requiresAuth && !store.isLoggedIn) { // this route requires auth, check if logged in // if not, redirect to login page. next({ path: '/', // save the location we were at to come back later query: { redirect: to.fullPath }, }); } else if (!to.meta.requiresAuth && store.isLoggedIn) { next({ path: '/' }); } else if (store.isLoggedIn && from.query.redirect) { // user is logged in and there's a saved location in the query // redirect them to that location const redirect = from.query.redirect; delete from.query.redirect; next(redirect); } else { next(); } }); export default router