diff --git a/src/router/index.js b/src/router/index.js index d052c3a23fdef7196c724765a9e11c455b6960d9..0aa3b0b9210366f8675c82f5fa9cf8ac948394b4 100644 --- a/src/router/index.js +++ b/src/router/index.js @@ -4,34 +4,44 @@ import HomeView from "../views/HomeView.vue"; import LoginView from "../views/LoginView.vue"; import NewPasswordView from "../views/NewPasswordView"; +/** + * Guards routes. If token is null, no user is logged in and only the + * login page and the register page will be accessible. + */ +function guardRoute(to, from, next) { + var isAuthenticated = false; + if (store.state.user.token != null) isAuthenticated = true; + else isAuthenticated = false; + if (isAuthenticated) { + next(); // allow to enter route + } else { + next("/login"); // go to '/login'; + } +} const routes = [ { path: "/", //Endre før push name: "home", + beforeEnter: guardRoute, component: HomeView, }, { path: "/about", name: "about", + beforeEnter: guardRoute, component: () => import("../views/AboutView.vue"), }, { path: "/profile/:id", name: "profile", component: () => import("../views/ProfileView.vue"), - beforeEnter: () => { - if (store.state.user.token == null) router.push("login"); - }, + beforeEnter: guardRoute, }, { path: "/register", name: "register", - // route level code-splitting - // this generates a separate chunk (register.[hash].js) for this route - // which is lazy-loaded when the route is visited. - component: () => - import(/* webpackChunkName: "register" */ "../views/RegisterView.vue"), + component: () => import("../views/RegisterView.vue"), }, { path: "/login", @@ -42,21 +52,25 @@ const routes = [ path: "/newPassword", name: "newPassword", component: NewPasswordView, + beforeEnter: guardRoute, }, { path: "/searchItemList", name: "searchItemList", component: () => import("../views/SearchItemListView.vue"), + beforeEnter: guardRoute, }, { path: "/createNewGroup", name: "createNewGroup", component: () => import("../views/CreateNewGroupView.vue"), + beforeEnter: guardRoute, }, { path: "/addNewItem", name: "addNewItem", component: () => import("../views/AddNewItemView.vue"), + beforeEnter: guardRoute, }, { path: "/notifications",