77 lines
2.2 KiB
Cheetah
77 lines
2.2 KiB
Cheetah
import { createRouter, createWebHistory } from 'vue-router'
|
||
import { useAuthenticationStore } from '@/stores/authentication.ts'
|
||
|
||
const router = createRouter({
|
||
history: createWebHistory(import.meta.env.BASE_URL),
|
||
routes: [
|
||
{
|
||
path: '/login',
|
||
name: 'Login',
|
||
component: () => import('../layouts/Login.vue'), // Lazy-loaded
|
||
meta: { public: true }, // Indicates this route doesn’t require auth
|
||
children: [
|
||
{
|
||
path: '',
|
||
name: 'Password',
|
||
component: () => import('../views/Password.vue'),
|
||
},
|
||
],
|
||
},
|
||
{
|
||
path: '/',
|
||
component: () => import('../layouts/MainLayout.vue'), // Protected layout
|
||
meta: { requiresAuth: true },
|
||
children: [
|
||
{
|
||
path: '',
|
||
name: 'Home',
|
||
component: () => import('../views/HomeView.vue'),
|
||
},
|
||
{
|
||
path: '/overview',
|
||
name: 'Overview',
|
||
component: () => import('../views/AboutView.vue'),
|
||
},
|
||
{
|
||
path: '/settings',
|
||
name: 'Settings',
|
||
component: () => import('../views/HomeView.vue'),
|
||
},
|
||
],
|
||
},
|
||
{
|
||
path: '/logout',
|
||
name: 'Logout',
|
||
meta: { public: true },
|
||
redirect: '/login',
|
||
},
|
||
],
|
||
});
|
||
|
||
router.beforeEach(async (to, from, next) => {
|
||
const authenticationStore = useAuthenticationStore();
|
||
|
||
if (to.redirectedFrom?.path === '/logout') {
|
||
authenticationStore.logout();
|
||
}
|
||
|
||
const isAuthenticated = await Promise.resolve(authenticationStore.isAuthenticated); /* logic to check auth state, e.g., from a store */
|
||
if (to.meta.requiresAuth && !isAuthenticated) {
|
||
// save the desired route in localStorage and redirect to login
|
||
localStorage.setItem('redirect', to.fullPath);
|
||
return next({ path: '/login' });
|
||
}
|
||
// if (to.meta.public && isAuthenticated) {
|
||
// // TODO: Decide if you want to redirect to a different page if the user is already authenticated
|
||
// }
|
||
const deepLink = localStorage.getItem('redirect');
|
||
if (to.meta.requiresAuth && isAuthenticated && !!deepLink) {
|
||
// remove redirect from localStorage and redirect to the deep link
|
||
localStorage.removeItem('redirect');
|
||
return next({ path: deepLink });
|
||
}
|
||
next();
|
||
});
|
||
|
||
export default router
|