Newer
Older
smart-home-server / webclient / src / router / index.js
import { createRouter, createWebHashHistory } from "vue-router";
import { routes } from "./routes";
import { useAuthStore } from "../stores/auth.js";

export const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore();

  // Ensure auth initialization completes before any routing decision.
  // init() is cached: repeated calls are no-ops after the first resolution.
  await authStore.init();

  // Allow public routes unconditionally
  if (to.meta?.public) {
    if (to.name === "login" && authStore.isAuthenticated) {
      next({ name: "areas-favorites" });
      return;
    }
    next();
    return;
  }

  // Require authentication
  if (!authStore.isAuthenticated) {
    next({ name: "login" });
    return;
  }

  // Check route-level permission
  const required = to.meta?.permission;
  if (required && !authStore.hasPermission(required)) {
    next({ name: "areas-favorites" });
    return;
  }

  next();
});