Tengo varios tipos de usuarios en el proyecto VueJS . Cualquier rol (excepto el rol X) comienza con /streamers como página de inicio.
Quiero que el rol X no pueda ver la página /streamers . Quiero que vean /streamers/<CURRENT_USER_ID>/detail SOLAMENTE.
const routes = [ { path: '/', name: 'Home', component: Dashboard, redirect: '/streamers/', children:[ { path: 'streamers/', name: 'Streamers', component: Streamers, }, { path: 'streamers/:id/detail/', name: 'StreamerDetail', component: StreamerDetail, }, ], }, { path: '/login', name: 'Login', component: Login, } ] ¿Cómo puedo hacer eso? El componente Dashboard necesita cargar al usuario actual usando la API. Luego debería verificar si el usuario tiene el rol X ( $store.state.auth.user.is_X ). En caso afirmativo, solo deberían poder ver su página de detalles.
Tablero
<template> <div if="$store.getters.isAuthenticated"> .... </div> </template> export default { name: "Dashboard.vue", data() { return { snackbar: { color: null, message: null, } } }, mounted(){ this.$store.dispatch('checkCookiesOnInit') // checks for JWT token in cookies if (!this.$store.getters.isAuthenticated){ this.$store.dispatch('refreshToken') } }, methods: { }, }Podría usar router.beforeEach para crear un protector de ruta con estas reglas.
Ejemplo: https://codesandbox.io/s/zealous-cartwright-yhcuy?file=/src/main.js
import { createApp } from "vue"; import { createRouter, createWebHashHistory } from "vue-router"; import App from "./App.vue"; import Home from "./components/Home.vue"; import View1 from "./components/View1.vue"; import View2 from "./components/View2.vue"; const getLoggedInUser = () => { // user to test routes with const user123 = { name: "John", id: "123", role: "user" }; const user5 = { name: "Sam", id: "5", role: "user" }; const admin = { name: "Dean", id: "5", role: "admin" }; return user123; }; const routeGuard = (to, from) => { const { loggedInRequired, idCheckRequired, authorize } = to.meta; // if login not required then allow entry if (!loggedInRequired) { return true; } const currentUser = getLoggedInUser(); if (!currentUser) { // not logged in so redirect to home return false; } if (authorize.length && !authorize.includes(currentUser.role)) { // if they don't have the correct role redirect home return false; } if (idCheckRequired && to.params.id != currentUser.id) { // if the :id param doesn't match the logged in user's id return false; } return true; }; const router = createRouter({ history: createWebHashHistory(), routes: [ { path: "/", name: "Home", component: Home, children: [ { path: "streamers/", name: "Streamers", component: View1, meta: { loggedInRequired: true, authorize: ["admin"], idCheckRequired: false } }, { path: "streamers/:id/detail/", name: "StreamerDetail", component: View2, meta: { loggedInRequired: true, authorize: ["user"], idCheckRequired: true } } ] } ] }); router.beforeEach(routeGuard); createApp(App).use(router).mount("#app");