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((to, from, next) => {
  const authStore = useAuthStore();

  // 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) {
    if (authStore.isLoading) {
      // Wait briefly then re-evaluate (should not happen if init() runs before mount)
      next({ name: "login" });
      return;
    }
    next({ name: "login" });
    return;
  }

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

  next();
});