Newer
Older
bugtrail / packages / web / src / router.ts
import { createRouter, createWebHistory } from "vue-router";
import { useAuth } from "./stores/auth";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: "/login", component: () => import("./pages/LoginPage.vue"), meta: { guestOnly: true } },
    { path: "/register", component: () => import("./pages/RegisterPage.vue"), meta: { guestOnly: true } },
    { path: "/", component: () => import("./pages/ProjectsPage.vue"), meta: { requiresAuth: true } },
    { path: "/settings", component: () => import("./pages/SettingsPage.vue"), meta: { requiresAuth: true } },
    { path: "/p/:token", component: () => import("./pages/ProjectPage.vue") }, // public: token = authorization
    { path: "/r/:token", component: () => import("./pages/ReportPage.vue") }, // public: token = authorization
    { path: "/:pathMatch(.*)*", redirect: "/" },
  ],
});

router.beforeEach(async (to) => {
  const auth = useAuth();
  if (to.meta.requiresAuth && auth.user.value === null) {
    await auth.fetch();
  }
  if (to.meta.requiresAuth && !auth.isAuthenticated.value) {
    return { path: "/login", query: { redirect: to.fullPath } };
  }
  if (to.meta.guestOnly && auth.isAuthenticated.value) {
    return { path: "/" };
  }
});

export default router;