import Cookies from "js-cookie"; import { createWebHistory, createRouter } from "vue-router"; import roles from "@/auth/roles"; import Videos from "@/routes/videos"; import Login from "@/routes/auth/Login.vue"; const getUserRoles = () => { const rolesFromCookie = Cookies.get("user_roles"); // TODO: Tirar as permissões do usuário return rolesFromCookie ? JSON.parse(rolesFromCookie) : []; }; export const routes = [ { path: "/login", name: "Login", component: Login, meta: { guest: true, title: "Login", }, }, { path: "/videos", component: Videos, name: "Videos", meta: { requiresAuth: true, title: "Vídeos", permissions: [roles.VIDEOS_LIST], showinModal: true, }, }, { path: "/:pathMatch(.*)*", meta: { showinModal: false, }, redirect: (to) => { return Cookies.get("token") ? "/videos" : "/login"; }, }, { path: "/", meta: { showinModal: false, }, redirect: (to) => { return Cookies.get("token") ? "/videos" : "/login"; }, }, ]; export const router = createRouter({ history: createWebHistory(), routes, }); export const isAuthenticated = () => { return !!Cookies.get("token"); }; const hasPermission = (requiredPermissions = []) => { if (!requiredPermissions.length) return true; const userRoles = getUserRoles(); return requiredPermissions.some((permission) => userRoles.includes(permission) ); }; router.beforeEach((to, from, next) => { if (to.meta.title) { document.title = to.meta.title; } // if (to.matched.some((record) => record.meta.requiresAuth)) { if (!isAuthenticated()) { next({ path: "/login", query: { redirect: to.fullPath }, }); return; } // const requiredPermissions = to.meta.permissions || []; // if (requiredPermissions.length > 0 && !hasPermission(requiredPermissions)) { // next({ path: "/unauthorized" }); // return; // } // } // if (to.matched.some((record) => record.meta.guest) && isAuthenticated()) { // next({ path: "/" }); // return; // } next(); });